xref: /netbsd-src/external/apache2/llvm/dist/llvm/lib/CodeGen/LiveDebugValues/VarLocBasedImpl.cpp (revision 82d56013d7b633d116a93943de88e08335357a7c)
1*82d56013Sjoerg //===- VarLocBasedImpl.cpp - Tracking Debug Value MIs with VarLoc class----===//
2*82d56013Sjoerg //
3*82d56013Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*82d56013Sjoerg // See https://llvm.org/LICENSE.txt for license information.
5*82d56013Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*82d56013Sjoerg //
7*82d56013Sjoerg //===----------------------------------------------------------------------===//
8*82d56013Sjoerg ///
9*82d56013Sjoerg /// \file VarLocBasedImpl.cpp
10*82d56013Sjoerg ///
11*82d56013Sjoerg /// LiveDebugValues is an optimistic "available expressions" dataflow
12*82d56013Sjoerg /// algorithm. The set of expressions is the set of machine locations
13*82d56013Sjoerg /// (registers, spill slots, constants) that a variable fragment might be
14*82d56013Sjoerg /// located, qualified by a DIExpression and indirect-ness flag, while each
15*82d56013Sjoerg /// variable is identified by a DebugVariable object. The availability of an
16*82d56013Sjoerg /// expression begins when a DBG_VALUE instruction specifies the location of a
17*82d56013Sjoerg /// DebugVariable, and continues until that location is clobbered or
18*82d56013Sjoerg /// re-specified by a different DBG_VALUE for the same DebugVariable.
19*82d56013Sjoerg ///
20*82d56013Sjoerg /// The output of LiveDebugValues is additional DBG_VALUE instructions,
21*82d56013Sjoerg /// placed to extend variable locations as far they're available. This file
22*82d56013Sjoerg /// and the VarLocBasedLDV class is an implementation that explicitly tracks
23*82d56013Sjoerg /// locations, using the VarLoc class.
24*82d56013Sjoerg ///
25*82d56013Sjoerg /// The canonical "available expressions" problem doesn't have expression
26*82d56013Sjoerg /// clobbering, instead when a variable is re-assigned, any expressions using
27*82d56013Sjoerg /// that variable get invalidated. LiveDebugValues can map onto "available
28*82d56013Sjoerg /// expressions" by having every register represented by a variable, which is
29*82d56013Sjoerg /// used in an expression that becomes available at a DBG_VALUE instruction.
30*82d56013Sjoerg /// When the register is clobbered, its variable is effectively reassigned, and
31*82d56013Sjoerg /// expressions computed from it become unavailable. A similar construct is
32*82d56013Sjoerg /// needed when a DebugVariable has its location re-specified, to invalidate
33*82d56013Sjoerg /// all other locations for that DebugVariable.
34*82d56013Sjoerg ///
35*82d56013Sjoerg /// Using the dataflow analysis to compute the available expressions, we create
36*82d56013Sjoerg /// a DBG_VALUE at the beginning of each block where the expression is
37*82d56013Sjoerg /// live-in. This propagates variable locations into every basic block where
38*82d56013Sjoerg /// the location can be determined, rather than only having DBG_VALUEs in blocks
39*82d56013Sjoerg /// where locations are specified due to an assignment or some optimization.
40*82d56013Sjoerg /// Movements of values between registers and spill slots are annotated with
41*82d56013Sjoerg /// DBG_VALUEs too to track variable values bewteen locations. All this allows
42*82d56013Sjoerg /// DbgEntityHistoryCalculator to focus on only the locations within individual
43*82d56013Sjoerg /// blocks, facilitating testing and improving modularity.
44*82d56013Sjoerg ///
45*82d56013Sjoerg /// We follow an optimisic dataflow approach, with this lattice:
46*82d56013Sjoerg ///
47*82d56013Sjoerg /// \verbatim
48*82d56013Sjoerg ///                    ┬ "Unknown"
49*82d56013Sjoerg ///                          |
50*82d56013Sjoerg ///                          v
51*82d56013Sjoerg ///                         True
52*82d56013Sjoerg ///                          |
53*82d56013Sjoerg ///                          v
54*82d56013Sjoerg ///                      ⊥ False
55*82d56013Sjoerg /// \endverbatim With "True" signifying that the expression is available (and
56*82d56013Sjoerg /// thus a DebugVariable's location is the corresponding register), while
57*82d56013Sjoerg /// "False" signifies that the expression is unavailable. "Unknown"s never
58*82d56013Sjoerg /// survive to the end of the analysis (see below).
59*82d56013Sjoerg ///
60*82d56013Sjoerg /// Formally, all DebugVariable locations that are live-out of a block are
61*82d56013Sjoerg /// initialized to \top.  A blocks live-in values take the meet of the lattice
62*82d56013Sjoerg /// value for every predecessors live-outs, except for the entry block, where
63*82d56013Sjoerg /// all live-ins are \bot. The usual dataflow propagation occurs: the transfer
64*82d56013Sjoerg /// function for a block assigns an expression for a DebugVariable to be "True"
65*82d56013Sjoerg /// if a DBG_VALUE in the block specifies it; "False" if the location is
66*82d56013Sjoerg /// clobbered; or the live-in value if it is unaffected by the block. We
67*82d56013Sjoerg /// visit each block in reverse post order until a fixedpoint is reached. The
68*82d56013Sjoerg /// solution produced is maximal.
69*82d56013Sjoerg ///
70*82d56013Sjoerg /// Intuitively, we start by assuming that every expression / variable location
71*82d56013Sjoerg /// is at least "True", and then propagate "False" from the entry block and any
72*82d56013Sjoerg /// clobbers until there are no more changes to make. This gives us an accurate
73*82d56013Sjoerg /// solution because all incorrect locations will have a "False" propagated into
74*82d56013Sjoerg /// them. It also gives us a solution that copes well with loops by assuming
75*82d56013Sjoerg /// that variable locations are live-through every loop, and then removing those
76*82d56013Sjoerg /// that are not through dataflow.
77*82d56013Sjoerg ///
78*82d56013Sjoerg /// Within LiveDebugValues: each variable location is represented by a
79*82d56013Sjoerg /// VarLoc object that identifies the source variable, the set of
80*82d56013Sjoerg /// machine-locations that currently describe it (a single location for
81*82d56013Sjoerg /// DBG_VALUE or multiple for DBG_VALUE_LIST), and the DBG_VALUE inst that
82*82d56013Sjoerg /// specifies the location. Each VarLoc is indexed in the (function-scope) \p
83*82d56013Sjoerg /// VarLocMap, giving each VarLoc a set of unique indexes, each of which
84*82d56013Sjoerg /// corresponds to one of the VarLoc's machine-locations and can be used to
85*82d56013Sjoerg /// lookup the VarLoc in the VarLocMap. Rather than operate directly on machine
86*82d56013Sjoerg /// locations, the dataflow analysis in this pass identifies locations by their
87*82d56013Sjoerg /// indices in the VarLocMap, meaning all the variable locations in a block can
88*82d56013Sjoerg /// be described by a sparse vector of VarLocMap indicies.
89*82d56013Sjoerg ///
90*82d56013Sjoerg /// All the storage for the dataflow analysis is local to the ExtendRanges
91*82d56013Sjoerg /// method and passed down to helper methods. "OutLocs" and "InLocs" record the
92*82d56013Sjoerg /// in and out lattice values for each block. "OpenRanges" maintains a list of
93*82d56013Sjoerg /// variable locations and, with the "process" method, evaluates the transfer
94*82d56013Sjoerg /// function of each block. "flushPendingLocs" installs debug value instructions
95*82d56013Sjoerg /// for each live-in location at the start of blocks, while "Transfers" records
96*82d56013Sjoerg /// transfers of values between machine-locations.
97*82d56013Sjoerg ///
98*82d56013Sjoerg /// We avoid explicitly representing the "Unknown" (\top) lattice value in the
99*82d56013Sjoerg /// implementation. Instead, unvisited blocks implicitly have all lattice
100*82d56013Sjoerg /// values set as "Unknown". After being visited, there will be path back to
101*82d56013Sjoerg /// the entry block where the lattice value is "False", and as the transfer
102*82d56013Sjoerg /// function cannot make new "Unknown" locations, there are no scenarios where
103*82d56013Sjoerg /// a block can have an "Unknown" location after being visited. Similarly, we
104*82d56013Sjoerg /// don't enumerate all possible variable locations before exploring the
105*82d56013Sjoerg /// function: when a new location is discovered, all blocks previously explored
106*82d56013Sjoerg /// were implicitly "False" but unrecorded, and become explicitly "False" when
107*82d56013Sjoerg /// a new VarLoc is created with its bit not set in predecessor InLocs or
108*82d56013Sjoerg /// OutLocs.
109*82d56013Sjoerg ///
110*82d56013Sjoerg //===----------------------------------------------------------------------===//
111*82d56013Sjoerg 
112*82d56013Sjoerg #include "LiveDebugValues.h"
113*82d56013Sjoerg 
114*82d56013Sjoerg #include "llvm/ADT/CoalescingBitVector.h"
115*82d56013Sjoerg #include "llvm/ADT/DenseMap.h"
116*82d56013Sjoerg #include "llvm/ADT/PostOrderIterator.h"
117*82d56013Sjoerg #include "llvm/ADT/SmallPtrSet.h"
118*82d56013Sjoerg #include "llvm/ADT/SmallSet.h"
119*82d56013Sjoerg #include "llvm/ADT/SmallVector.h"
120*82d56013Sjoerg #include "llvm/ADT/Statistic.h"
121*82d56013Sjoerg #include "llvm/ADT/UniqueVector.h"
122*82d56013Sjoerg #include "llvm/CodeGen/LexicalScopes.h"
123*82d56013Sjoerg #include "llvm/CodeGen/MachineBasicBlock.h"
124*82d56013Sjoerg #include "llvm/CodeGen/MachineFrameInfo.h"
125*82d56013Sjoerg #include "llvm/CodeGen/MachineFunction.h"
126*82d56013Sjoerg #include "llvm/CodeGen/MachineFunctionPass.h"
127*82d56013Sjoerg #include "llvm/CodeGen/MachineInstr.h"
128*82d56013Sjoerg #include "llvm/CodeGen/MachineInstrBuilder.h"
129*82d56013Sjoerg #include "llvm/CodeGen/MachineMemOperand.h"
130*82d56013Sjoerg #include "llvm/CodeGen/MachineOperand.h"
131*82d56013Sjoerg #include "llvm/CodeGen/PseudoSourceValue.h"
132*82d56013Sjoerg #include "llvm/CodeGen/RegisterScavenging.h"
133*82d56013Sjoerg #include "llvm/CodeGen/TargetFrameLowering.h"
134*82d56013Sjoerg #include "llvm/CodeGen/TargetInstrInfo.h"
135*82d56013Sjoerg #include "llvm/CodeGen/TargetLowering.h"
136*82d56013Sjoerg #include "llvm/CodeGen/TargetPassConfig.h"
137*82d56013Sjoerg #include "llvm/CodeGen/TargetRegisterInfo.h"
138*82d56013Sjoerg #include "llvm/CodeGen/TargetSubtargetInfo.h"
139*82d56013Sjoerg #include "llvm/Config/llvm-config.h"
140*82d56013Sjoerg #include "llvm/IR/DIBuilder.h"
141*82d56013Sjoerg #include "llvm/IR/DebugInfoMetadata.h"
142*82d56013Sjoerg #include "llvm/IR/DebugLoc.h"
143*82d56013Sjoerg #include "llvm/IR/Function.h"
144*82d56013Sjoerg #include "llvm/IR/Module.h"
145*82d56013Sjoerg #include "llvm/InitializePasses.h"
146*82d56013Sjoerg #include "llvm/MC/MCRegisterInfo.h"
147*82d56013Sjoerg #include "llvm/Pass.h"
148*82d56013Sjoerg #include "llvm/Support/Casting.h"
149*82d56013Sjoerg #include "llvm/Support/Compiler.h"
150*82d56013Sjoerg #include "llvm/Support/Debug.h"
151*82d56013Sjoerg #include "llvm/Support/TypeSize.h"
152*82d56013Sjoerg #include "llvm/Support/raw_ostream.h"
153*82d56013Sjoerg #include "llvm/Target/TargetMachine.h"
154*82d56013Sjoerg #include <algorithm>
155*82d56013Sjoerg #include <cassert>
156*82d56013Sjoerg #include <cstdint>
157*82d56013Sjoerg #include <functional>
158*82d56013Sjoerg #include <queue>
159*82d56013Sjoerg #include <tuple>
160*82d56013Sjoerg #include <utility>
161*82d56013Sjoerg #include <vector>
162*82d56013Sjoerg 
163*82d56013Sjoerg using namespace llvm;
164*82d56013Sjoerg 
165*82d56013Sjoerg #define DEBUG_TYPE "livedebugvalues"
166*82d56013Sjoerg 
167*82d56013Sjoerg STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
168*82d56013Sjoerg 
169*82d56013Sjoerg // Options to prevent pathological compile-time behavior. If InputBBLimit and
170*82d56013Sjoerg // InputDbgValueLimit are both exceeded, range extension is disabled.
171*82d56013Sjoerg static cl::opt<unsigned> InputBBLimit(
172*82d56013Sjoerg     "livedebugvalues-input-bb-limit",
173*82d56013Sjoerg     cl::desc("Maximum input basic blocks before DBG_VALUE limit applies"),
174*82d56013Sjoerg     cl::init(10000), cl::Hidden);
175*82d56013Sjoerg static cl::opt<unsigned> InputDbgValueLimit(
176*82d56013Sjoerg     "livedebugvalues-input-dbg-value-limit",
177*82d56013Sjoerg     cl::desc(
178*82d56013Sjoerg         "Maximum input DBG_VALUE insts supported by debug range extension"),
179*82d56013Sjoerg     cl::init(50000), cl::Hidden);
180*82d56013Sjoerg 
181*82d56013Sjoerg /// If \p Op is a stack or frame register return true, otherwise return false.
182*82d56013Sjoerg /// This is used to avoid basing the debug entry values on the registers, since
183*82d56013Sjoerg /// we do not support it at the moment.
isRegOtherThanSPAndFP(const MachineOperand & Op,const MachineInstr & MI,const TargetRegisterInfo * TRI)184*82d56013Sjoerg static bool isRegOtherThanSPAndFP(const MachineOperand &Op,
185*82d56013Sjoerg                                   const MachineInstr &MI,
186*82d56013Sjoerg                                   const TargetRegisterInfo *TRI) {
187*82d56013Sjoerg   if (!Op.isReg())
188*82d56013Sjoerg     return false;
189*82d56013Sjoerg 
190*82d56013Sjoerg   const MachineFunction *MF = MI.getParent()->getParent();
191*82d56013Sjoerg   const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
192*82d56013Sjoerg   Register SP = TLI->getStackPointerRegisterToSaveRestore();
193*82d56013Sjoerg   Register FP = TRI->getFrameRegister(*MF);
194*82d56013Sjoerg   Register Reg = Op.getReg();
195*82d56013Sjoerg 
196*82d56013Sjoerg   return Reg && Reg != SP && Reg != FP;
197*82d56013Sjoerg }
198*82d56013Sjoerg 
199*82d56013Sjoerg namespace {
200*82d56013Sjoerg 
201*82d56013Sjoerg // Max out the number of statically allocated elements in DefinedRegsSet, as
202*82d56013Sjoerg // this prevents fallback to std::set::count() operations.
203*82d56013Sjoerg using DefinedRegsSet = SmallSet<Register, 32>;
204*82d56013Sjoerg 
205*82d56013Sjoerg // The IDs in this set correspond to MachineLocs in VarLocs, as well as VarLocs
206*82d56013Sjoerg // that represent Entry Values; every VarLoc in the set will also appear
207*82d56013Sjoerg // exactly once at Location=0.
208*82d56013Sjoerg // As a result, each VarLoc may appear more than once in this "set", but each
209*82d56013Sjoerg // range corresponding to a Reg, SpillLoc, or EntryValue type will still be a
210*82d56013Sjoerg // "true" set (i.e. each VarLoc may appear only once), and the range Location=0
211*82d56013Sjoerg // is the set of all VarLocs.
212*82d56013Sjoerg using VarLocSet = CoalescingBitVector<uint64_t>;
213*82d56013Sjoerg 
214*82d56013Sjoerg /// A type-checked pair of {Register Location (or 0), Index}, used to index
215*82d56013Sjoerg /// into a \ref VarLocMap. This can be efficiently converted to a 64-bit int
216*82d56013Sjoerg /// for insertion into a \ref VarLocSet, and efficiently converted back. The
217*82d56013Sjoerg /// type-checker helps ensure that the conversions aren't lossy.
218*82d56013Sjoerg ///
219*82d56013Sjoerg /// Why encode a location /into/ the VarLocMap index? This makes it possible
220*82d56013Sjoerg /// to find the open VarLocs killed by a register def very quickly. This is a
221*82d56013Sjoerg /// performance-critical operation for LiveDebugValues.
222*82d56013Sjoerg struct LocIndex {
223*82d56013Sjoerg   using u32_location_t = uint32_t;
224*82d56013Sjoerg   using u32_index_t = uint32_t;
225*82d56013Sjoerg 
226*82d56013Sjoerg   u32_location_t Location; // Physical registers live in the range [1;2^30) (see
227*82d56013Sjoerg                            // \ref MCRegister), so we have plenty of range left
228*82d56013Sjoerg                            // here to encode non-register locations.
229*82d56013Sjoerg   u32_index_t Index;
230*82d56013Sjoerg 
231*82d56013Sjoerg   /// The location that has an entry for every VarLoc in the map.
232*82d56013Sjoerg   static constexpr u32_location_t kUniversalLocation = 0;
233*82d56013Sjoerg 
234*82d56013Sjoerg   /// The first location that is reserved for VarLocs with locations of kind
235*82d56013Sjoerg   /// RegisterKind.
236*82d56013Sjoerg   static constexpr u32_location_t kFirstRegLocation = 1;
237*82d56013Sjoerg 
238*82d56013Sjoerg   /// The first location greater than 0 that is not reserved for VarLocs with
239*82d56013Sjoerg   /// locations of kind RegisterKind.
240*82d56013Sjoerg   static constexpr u32_location_t kFirstInvalidRegLocation = 1 << 30;
241*82d56013Sjoerg 
242*82d56013Sjoerg   /// A special location reserved for VarLocs with locations of kind
243*82d56013Sjoerg   /// SpillLocKind.
244*82d56013Sjoerg   static constexpr u32_location_t kSpillLocation = kFirstInvalidRegLocation;
245*82d56013Sjoerg 
246*82d56013Sjoerg   /// A special location reserved for VarLocs of kind EntryValueBackupKind and
247*82d56013Sjoerg   /// EntryValueCopyBackupKind.
248*82d56013Sjoerg   static constexpr u32_location_t kEntryValueBackupLocation =
249*82d56013Sjoerg       kFirstInvalidRegLocation + 1;
250*82d56013Sjoerg 
LocIndex__anon250db9ad0111::LocIndex251*82d56013Sjoerg   LocIndex(u32_location_t Location, u32_index_t Index)
252*82d56013Sjoerg       : Location(Location), Index(Index) {}
253*82d56013Sjoerg 
getAsRawInteger__anon250db9ad0111::LocIndex254*82d56013Sjoerg   uint64_t getAsRawInteger() const {
255*82d56013Sjoerg     return (static_cast<uint64_t>(Location) << 32) | Index;
256*82d56013Sjoerg   }
257*82d56013Sjoerg 
fromRawInteger__anon250db9ad0111::LocIndex258*82d56013Sjoerg   template<typename IntT> static LocIndex fromRawInteger(IntT ID) {
259*82d56013Sjoerg     static_assert(std::is_unsigned<IntT>::value &&
260*82d56013Sjoerg                       sizeof(ID) == sizeof(uint64_t),
261*82d56013Sjoerg                   "Cannot convert raw integer to LocIndex");
262*82d56013Sjoerg     return {static_cast<u32_location_t>(ID >> 32),
263*82d56013Sjoerg             static_cast<u32_index_t>(ID)};
264*82d56013Sjoerg   }
265*82d56013Sjoerg 
266*82d56013Sjoerg   /// Get the start of the interval reserved for VarLocs of kind RegisterKind
267*82d56013Sjoerg   /// which reside in \p Reg. The end is at rawIndexForReg(Reg+1)-1.
rawIndexForReg__anon250db9ad0111::LocIndex268*82d56013Sjoerg   static uint64_t rawIndexForReg(Register Reg) {
269*82d56013Sjoerg     return LocIndex(Reg, 0).getAsRawInteger();
270*82d56013Sjoerg   }
271*82d56013Sjoerg 
272*82d56013Sjoerg   /// Return a range covering all set indices in the interval reserved for
273*82d56013Sjoerg   /// \p Location in \p Set.
indexRangeForLocation__anon250db9ad0111::LocIndex274*82d56013Sjoerg   static auto indexRangeForLocation(const VarLocSet &Set,
275*82d56013Sjoerg                                     u32_location_t Location) {
276*82d56013Sjoerg     uint64_t Start = LocIndex(Location, 0).getAsRawInteger();
277*82d56013Sjoerg     uint64_t End = LocIndex(Location + 1, 0).getAsRawInteger();
278*82d56013Sjoerg     return Set.half_open_range(Start, End);
279*82d56013Sjoerg   }
280*82d56013Sjoerg };
281*82d56013Sjoerg 
282*82d56013Sjoerg // Simple Set for storing all the VarLoc Indices at a Location bucket.
283*82d56013Sjoerg using VarLocsInRange = SmallSet<LocIndex::u32_index_t, 32>;
284*82d56013Sjoerg // Vector of all `LocIndex`s for a given VarLoc; the same Location should not
285*82d56013Sjoerg // appear in any two of these, as each VarLoc appears at most once in any
286*82d56013Sjoerg // Location bucket.
287*82d56013Sjoerg using LocIndices = SmallVector<LocIndex, 2>;
288*82d56013Sjoerg 
289*82d56013Sjoerg class VarLocBasedLDV : public LDVImpl {
290*82d56013Sjoerg private:
291*82d56013Sjoerg   const TargetRegisterInfo *TRI;
292*82d56013Sjoerg   const TargetInstrInfo *TII;
293*82d56013Sjoerg   const TargetFrameLowering *TFI;
294*82d56013Sjoerg   TargetPassConfig *TPC;
295*82d56013Sjoerg   BitVector CalleeSavedRegs;
296*82d56013Sjoerg   LexicalScopes LS;
297*82d56013Sjoerg   VarLocSet::Allocator Alloc;
298*82d56013Sjoerg 
299*82d56013Sjoerg   enum struct TransferKind { TransferCopy, TransferSpill, TransferRestore };
300*82d56013Sjoerg 
301*82d56013Sjoerg   using FragmentInfo = DIExpression::FragmentInfo;
302*82d56013Sjoerg   using OptFragmentInfo = Optional<DIExpression::FragmentInfo>;
303*82d56013Sjoerg 
304*82d56013Sjoerg   /// A pair of debug variable and value location.
305*82d56013Sjoerg   struct VarLoc {
306*82d56013Sjoerg     // The location at which a spilled variable resides. It consists of a
307*82d56013Sjoerg     // register and an offset.
308*82d56013Sjoerg     struct SpillLoc {
309*82d56013Sjoerg       unsigned SpillBase;
310*82d56013Sjoerg       StackOffset SpillOffset;
operator ==__anon250db9ad0111::VarLocBasedLDV::VarLoc::SpillLoc311*82d56013Sjoerg       bool operator==(const SpillLoc &Other) const {
312*82d56013Sjoerg         return SpillBase == Other.SpillBase && SpillOffset == Other.SpillOffset;
313*82d56013Sjoerg       }
operator !=__anon250db9ad0111::VarLocBasedLDV::VarLoc::SpillLoc314*82d56013Sjoerg       bool operator!=(const SpillLoc &Other) const {
315*82d56013Sjoerg         return !(*this == Other);
316*82d56013Sjoerg       }
317*82d56013Sjoerg     };
318*82d56013Sjoerg 
319*82d56013Sjoerg     /// Identity of the variable at this location.
320*82d56013Sjoerg     const DebugVariable Var;
321*82d56013Sjoerg 
322*82d56013Sjoerg     /// The expression applied to this location.
323*82d56013Sjoerg     const DIExpression *Expr;
324*82d56013Sjoerg 
325*82d56013Sjoerg     /// DBG_VALUE to clone var/expr information from if this location
326*82d56013Sjoerg     /// is moved.
327*82d56013Sjoerg     const MachineInstr &MI;
328*82d56013Sjoerg 
329*82d56013Sjoerg     enum class MachineLocKind {
330*82d56013Sjoerg       InvalidKind = 0,
331*82d56013Sjoerg       RegisterKind,
332*82d56013Sjoerg       SpillLocKind,
333*82d56013Sjoerg       ImmediateKind
334*82d56013Sjoerg     };
335*82d56013Sjoerg 
336*82d56013Sjoerg     enum class EntryValueLocKind {
337*82d56013Sjoerg       NonEntryValueKind = 0,
338*82d56013Sjoerg       EntryValueKind,
339*82d56013Sjoerg       EntryValueBackupKind,
340*82d56013Sjoerg       EntryValueCopyBackupKind
341*82d56013Sjoerg     } EVKind;
342*82d56013Sjoerg 
343*82d56013Sjoerg     /// The value location. Stored separately to avoid repeatedly
344*82d56013Sjoerg     /// extracting it from MI.
345*82d56013Sjoerg     union MachineLocValue {
346*82d56013Sjoerg       uint64_t RegNo;
347*82d56013Sjoerg       SpillLoc SpillLocation;
348*82d56013Sjoerg       uint64_t Hash;
349*82d56013Sjoerg       int64_t Immediate;
350*82d56013Sjoerg       const ConstantFP *FPImm;
351*82d56013Sjoerg       const ConstantInt *CImm;
MachineLocValue()352*82d56013Sjoerg       MachineLocValue() : Hash(0) {}
353*82d56013Sjoerg     };
354*82d56013Sjoerg 
355*82d56013Sjoerg     /// A single machine location; its Kind is either a register, spill
356*82d56013Sjoerg     /// location, or immediate value.
357*82d56013Sjoerg     /// If the VarLoc is not a NonEntryValueKind, then it will use only a
358*82d56013Sjoerg     /// single MachineLoc of RegisterKind.
359*82d56013Sjoerg     struct MachineLoc {
360*82d56013Sjoerg       MachineLocKind Kind;
361*82d56013Sjoerg       MachineLocValue Value;
operator ==__anon250db9ad0111::VarLocBasedLDV::VarLoc::MachineLoc362*82d56013Sjoerg       bool operator==(const MachineLoc &Other) const {
363*82d56013Sjoerg         if (Kind != Other.Kind)
364*82d56013Sjoerg           return false;
365*82d56013Sjoerg         switch (Kind) {
366*82d56013Sjoerg         case MachineLocKind::SpillLocKind:
367*82d56013Sjoerg           return Value.SpillLocation == Other.Value.SpillLocation;
368*82d56013Sjoerg         case MachineLocKind::RegisterKind:
369*82d56013Sjoerg         case MachineLocKind::ImmediateKind:
370*82d56013Sjoerg           return Value.Hash == Other.Value.Hash;
371*82d56013Sjoerg         default:
372*82d56013Sjoerg           llvm_unreachable("Invalid kind");
373*82d56013Sjoerg         }
374*82d56013Sjoerg       }
operator <__anon250db9ad0111::VarLocBasedLDV::VarLoc::MachineLoc375*82d56013Sjoerg       bool operator<(const MachineLoc &Other) const {
376*82d56013Sjoerg         switch (Kind) {
377*82d56013Sjoerg         case MachineLocKind::SpillLocKind:
378*82d56013Sjoerg           return std::make_tuple(
379*82d56013Sjoerg                      Kind, Value.SpillLocation.SpillBase,
380*82d56013Sjoerg                      Value.SpillLocation.SpillOffset.getFixed(),
381*82d56013Sjoerg                      Value.SpillLocation.SpillOffset.getScalable()) <
382*82d56013Sjoerg                  std::make_tuple(
383*82d56013Sjoerg                      Other.Kind, Other.Value.SpillLocation.SpillBase,
384*82d56013Sjoerg                      Other.Value.SpillLocation.SpillOffset.getFixed(),
385*82d56013Sjoerg                      Other.Value.SpillLocation.SpillOffset.getScalable());
386*82d56013Sjoerg         case MachineLocKind::RegisterKind:
387*82d56013Sjoerg         case MachineLocKind::ImmediateKind:
388*82d56013Sjoerg           return std::tie(Kind, Value.Hash) <
389*82d56013Sjoerg                  std::tie(Other.Kind, Other.Value.Hash);
390*82d56013Sjoerg         default:
391*82d56013Sjoerg           llvm_unreachable("Invalid kind");
392*82d56013Sjoerg         }
393*82d56013Sjoerg       }
394*82d56013Sjoerg     };
395*82d56013Sjoerg 
396*82d56013Sjoerg     /// The set of machine locations used to determine the variable's value, in
397*82d56013Sjoerg     /// conjunction with Expr. Initially populated with MI's debug operands,
398*82d56013Sjoerg     /// but may be transformed independently afterwards.
399*82d56013Sjoerg     SmallVector<MachineLoc, 8> Locs;
400*82d56013Sjoerg     /// Used to map the index of each location in Locs back to the index of its
401*82d56013Sjoerg     /// original debug operand in MI. Used when multiple location operands are
402*82d56013Sjoerg     /// coalesced and the original MI's operands need to be accessed while
403*82d56013Sjoerg     /// emitting a debug value.
404*82d56013Sjoerg     SmallVector<unsigned, 8> OrigLocMap;
405*82d56013Sjoerg 
VarLoc__anon250db9ad0111::VarLocBasedLDV::VarLoc406*82d56013Sjoerg     VarLoc(const MachineInstr &MI, LexicalScopes &LS)
407*82d56013Sjoerg         : Var(MI.getDebugVariable(), MI.getDebugExpression(),
408*82d56013Sjoerg               MI.getDebugLoc()->getInlinedAt()),
409*82d56013Sjoerg           Expr(MI.getDebugExpression()), MI(MI),
410*82d56013Sjoerg           EVKind(EntryValueLocKind::NonEntryValueKind) {
411*82d56013Sjoerg       assert(MI.isDebugValue() && "not a DBG_VALUE");
412*82d56013Sjoerg       assert((MI.isDebugValueList() || MI.getNumOperands() == 4) &&
413*82d56013Sjoerg              "malformed DBG_VALUE");
414*82d56013Sjoerg       for (const MachineOperand &Op : MI.debug_operands()) {
415*82d56013Sjoerg         MachineLoc ML = GetLocForOp(Op);
416*82d56013Sjoerg         auto It = find(Locs, ML);
417*82d56013Sjoerg         if (It == Locs.end()) {
418*82d56013Sjoerg           Locs.push_back(ML);
419*82d56013Sjoerg           OrigLocMap.push_back(MI.getDebugOperandIndex(&Op));
420*82d56013Sjoerg         } else {
421*82d56013Sjoerg           // ML duplicates an element in Locs; replace references to Op
422*82d56013Sjoerg           // with references to the duplicating element.
423*82d56013Sjoerg           unsigned OpIdx = Locs.size();
424*82d56013Sjoerg           unsigned DuplicatingIdx = std::distance(Locs.begin(), It);
425*82d56013Sjoerg           Expr = DIExpression::replaceArg(Expr, OpIdx, DuplicatingIdx);
426*82d56013Sjoerg         }
427*82d56013Sjoerg       }
428*82d56013Sjoerg 
429*82d56013Sjoerg       // We create the debug entry values from the factory functions rather
430*82d56013Sjoerg       // than from this ctor.
431*82d56013Sjoerg       assert(EVKind != EntryValueLocKind::EntryValueKind &&
432*82d56013Sjoerg              !isEntryBackupLoc());
433*82d56013Sjoerg     }
434*82d56013Sjoerg 
GetLocForOp__anon250db9ad0111::VarLocBasedLDV::VarLoc435*82d56013Sjoerg     static MachineLoc GetLocForOp(const MachineOperand &Op) {
436*82d56013Sjoerg       MachineLocKind Kind;
437*82d56013Sjoerg       MachineLocValue Loc;
438*82d56013Sjoerg       if (Op.isReg()) {
439*82d56013Sjoerg         Kind = MachineLocKind::RegisterKind;
440*82d56013Sjoerg         Loc.RegNo = Op.getReg();
441*82d56013Sjoerg       } else if (Op.isImm()) {
442*82d56013Sjoerg         Kind = MachineLocKind::ImmediateKind;
443*82d56013Sjoerg         Loc.Immediate = Op.getImm();
444*82d56013Sjoerg       } else if (Op.isFPImm()) {
445*82d56013Sjoerg         Kind = MachineLocKind::ImmediateKind;
446*82d56013Sjoerg         Loc.FPImm = Op.getFPImm();
447*82d56013Sjoerg       } else if (Op.isCImm()) {
448*82d56013Sjoerg         Kind = MachineLocKind::ImmediateKind;
449*82d56013Sjoerg         Loc.CImm = Op.getCImm();
450*82d56013Sjoerg       } else
451*82d56013Sjoerg         llvm_unreachable("Invalid Op kind for MachineLoc.");
452*82d56013Sjoerg       return {Kind, Loc};
453*82d56013Sjoerg     }
454*82d56013Sjoerg 
455*82d56013Sjoerg     /// Take the variable and machine-location in DBG_VALUE MI, and build an
456*82d56013Sjoerg     /// entry location using the given expression.
CreateEntryLoc__anon250db9ad0111::VarLocBasedLDV::VarLoc457*82d56013Sjoerg     static VarLoc CreateEntryLoc(const MachineInstr &MI, LexicalScopes &LS,
458*82d56013Sjoerg                                  const DIExpression *EntryExpr, Register Reg) {
459*82d56013Sjoerg       VarLoc VL(MI, LS);
460*82d56013Sjoerg       assert(VL.Locs.size() == 1 &&
461*82d56013Sjoerg              VL.Locs[0].Kind == MachineLocKind::RegisterKind);
462*82d56013Sjoerg       VL.EVKind = EntryValueLocKind::EntryValueKind;
463*82d56013Sjoerg       VL.Expr = EntryExpr;
464*82d56013Sjoerg       VL.Locs[0].Value.RegNo = Reg;
465*82d56013Sjoerg       return VL;
466*82d56013Sjoerg     }
467*82d56013Sjoerg 
468*82d56013Sjoerg     /// Take the variable and machine-location from the DBG_VALUE (from the
469*82d56013Sjoerg     /// function entry), and build an entry value backup location. The backup
470*82d56013Sjoerg     /// location will turn into the normal location if the backup is valid at
471*82d56013Sjoerg     /// the time of the primary location clobbering.
CreateEntryBackupLoc__anon250db9ad0111::VarLocBasedLDV::VarLoc472*82d56013Sjoerg     static VarLoc CreateEntryBackupLoc(const MachineInstr &MI,
473*82d56013Sjoerg                                        LexicalScopes &LS,
474*82d56013Sjoerg                                        const DIExpression *EntryExpr) {
475*82d56013Sjoerg       VarLoc VL(MI, LS);
476*82d56013Sjoerg       assert(VL.Locs.size() == 1 &&
477*82d56013Sjoerg              VL.Locs[0].Kind == MachineLocKind::RegisterKind);
478*82d56013Sjoerg       VL.EVKind = EntryValueLocKind::EntryValueBackupKind;
479*82d56013Sjoerg       VL.Expr = EntryExpr;
480*82d56013Sjoerg       return VL;
481*82d56013Sjoerg     }
482*82d56013Sjoerg 
483*82d56013Sjoerg     /// Take the variable and machine-location from the DBG_VALUE (from the
484*82d56013Sjoerg     /// function entry), and build a copy of an entry value backup location by
485*82d56013Sjoerg     /// setting the register location to NewReg.
CreateEntryCopyBackupLoc__anon250db9ad0111::VarLocBasedLDV::VarLoc486*82d56013Sjoerg     static VarLoc CreateEntryCopyBackupLoc(const MachineInstr &MI,
487*82d56013Sjoerg                                            LexicalScopes &LS,
488*82d56013Sjoerg                                            const DIExpression *EntryExpr,
489*82d56013Sjoerg                                            Register NewReg) {
490*82d56013Sjoerg       VarLoc VL(MI, LS);
491*82d56013Sjoerg       assert(VL.Locs.size() == 1 &&
492*82d56013Sjoerg              VL.Locs[0].Kind == MachineLocKind::RegisterKind);
493*82d56013Sjoerg       VL.EVKind = EntryValueLocKind::EntryValueCopyBackupKind;
494*82d56013Sjoerg       VL.Expr = EntryExpr;
495*82d56013Sjoerg       VL.Locs[0].Value.RegNo = NewReg;
496*82d56013Sjoerg       return VL;
497*82d56013Sjoerg     }
498*82d56013Sjoerg 
499*82d56013Sjoerg     /// Copy the register location in DBG_VALUE MI, updating the register to
500*82d56013Sjoerg     /// be NewReg.
CreateCopyLoc__anon250db9ad0111::VarLocBasedLDV::VarLoc501*82d56013Sjoerg     static VarLoc CreateCopyLoc(const VarLoc &OldVL, const MachineLoc &OldML,
502*82d56013Sjoerg                                 Register NewReg) {
503*82d56013Sjoerg       VarLoc VL = OldVL;
504*82d56013Sjoerg       for (size_t I = 0, E = VL.Locs.size(); I < E; ++I)
505*82d56013Sjoerg         if (VL.Locs[I] == OldML) {
506*82d56013Sjoerg           VL.Locs[I].Kind = MachineLocKind::RegisterKind;
507*82d56013Sjoerg           VL.Locs[I].Value.RegNo = NewReg;
508*82d56013Sjoerg           return VL;
509*82d56013Sjoerg         }
510*82d56013Sjoerg       llvm_unreachable("Should have found OldML in new VarLoc.");
511*82d56013Sjoerg     }
512*82d56013Sjoerg 
513*82d56013Sjoerg     /// Take the variable described by DBG_VALUE* MI, and create a VarLoc
514*82d56013Sjoerg     /// locating it in the specified spill location.
CreateSpillLoc__anon250db9ad0111::VarLocBasedLDV::VarLoc515*82d56013Sjoerg     static VarLoc CreateSpillLoc(const VarLoc &OldVL, const MachineLoc &OldML,
516*82d56013Sjoerg                                  unsigned SpillBase, StackOffset SpillOffset) {
517*82d56013Sjoerg       VarLoc VL = OldVL;
518*82d56013Sjoerg       for (int I = 0, E = VL.Locs.size(); I < E; ++I)
519*82d56013Sjoerg         if (VL.Locs[I] == OldML) {
520*82d56013Sjoerg           VL.Locs[I].Kind = MachineLocKind::SpillLocKind;
521*82d56013Sjoerg           VL.Locs[I].Value.SpillLocation = {SpillBase, SpillOffset};
522*82d56013Sjoerg           return VL;
523*82d56013Sjoerg         }
524*82d56013Sjoerg       llvm_unreachable("Should have found OldML in new VarLoc.");
525*82d56013Sjoerg     }
526*82d56013Sjoerg 
527*82d56013Sjoerg     /// Create a DBG_VALUE representing this VarLoc in the given function.
528*82d56013Sjoerg     /// Copies variable-specific information such as DILocalVariable and
529*82d56013Sjoerg     /// inlining information from the original DBG_VALUE instruction, which may
530*82d56013Sjoerg     /// have been several transfers ago.
BuildDbgValue__anon250db9ad0111::VarLocBasedLDV::VarLoc531*82d56013Sjoerg     MachineInstr *BuildDbgValue(MachineFunction &MF) const {
532*82d56013Sjoerg       assert(!isEntryBackupLoc() &&
533*82d56013Sjoerg              "Tried to produce DBG_VALUE for backup VarLoc");
534*82d56013Sjoerg       const DebugLoc &DbgLoc = MI.getDebugLoc();
535*82d56013Sjoerg       bool Indirect = MI.isIndirectDebugValue();
536*82d56013Sjoerg       const auto &IID = MI.getDesc();
537*82d56013Sjoerg       const DILocalVariable *Var = MI.getDebugVariable();
538*82d56013Sjoerg       NumInserted++;
539*82d56013Sjoerg 
540*82d56013Sjoerg       const DIExpression *DIExpr = Expr;
541*82d56013Sjoerg       SmallVector<MachineOperand, 8> MOs;
542*82d56013Sjoerg       for (unsigned I = 0, E = Locs.size(); I < E; ++I) {
543*82d56013Sjoerg         MachineLocKind LocKind = Locs[I].Kind;
544*82d56013Sjoerg         MachineLocValue Loc = Locs[I].Value;
545*82d56013Sjoerg         const MachineOperand &Orig = MI.getDebugOperand(OrigLocMap[I]);
546*82d56013Sjoerg         switch (LocKind) {
547*82d56013Sjoerg         case MachineLocKind::RegisterKind:
548*82d56013Sjoerg           // An entry value is a register location -- but with an updated
549*82d56013Sjoerg           // expression. The register location of such DBG_VALUE is always the
550*82d56013Sjoerg           // one from the entry DBG_VALUE, it does not matter if the entry value
551*82d56013Sjoerg           // was copied in to another register due to some optimizations.
552*82d56013Sjoerg           // Non-entry value register locations are like the source
553*82d56013Sjoerg           // DBG_VALUE, but with the register number from this VarLoc.
554*82d56013Sjoerg           MOs.push_back(MachineOperand::CreateReg(
555*82d56013Sjoerg               EVKind == EntryValueLocKind::EntryValueKind ? Orig.getReg()
556*82d56013Sjoerg                                                           : Register(Loc.RegNo),
557*82d56013Sjoerg               false));
558*82d56013Sjoerg           MOs.back().setIsDebug();
559*82d56013Sjoerg           break;
560*82d56013Sjoerg         case MachineLocKind::SpillLocKind: {
561*82d56013Sjoerg           // Spills are indirect DBG_VALUEs, with a base register and offset.
562*82d56013Sjoerg           // Use the original DBG_VALUEs expression to build the spilt location
563*82d56013Sjoerg           // on top of. FIXME: spill locations created before this pass runs
564*82d56013Sjoerg           // are not recognized, and not handled here.
565*82d56013Sjoerg           unsigned Base = Loc.SpillLocation.SpillBase;
566*82d56013Sjoerg           auto *TRI = MF.getSubtarget().getRegisterInfo();
567*82d56013Sjoerg           if (MI.isNonListDebugValue()) {
568*82d56013Sjoerg             DIExpr =
569*82d56013Sjoerg                 TRI->prependOffsetExpression(DIExpr, DIExpression::ApplyOffset,
570*82d56013Sjoerg                                              Loc.SpillLocation.SpillOffset);
571*82d56013Sjoerg             Indirect = true;
572*82d56013Sjoerg           } else {
573*82d56013Sjoerg             SmallVector<uint64_t, 4> Ops;
574*82d56013Sjoerg             TRI->getOffsetOpcodes(Loc.SpillLocation.SpillOffset, Ops);
575*82d56013Sjoerg             Ops.push_back(dwarf::DW_OP_deref);
576*82d56013Sjoerg             DIExpr = DIExpression::appendOpsToArg(DIExpr, Ops, I);
577*82d56013Sjoerg           }
578*82d56013Sjoerg           MOs.push_back(MachineOperand::CreateReg(Base, false));
579*82d56013Sjoerg           MOs.back().setIsDebug();
580*82d56013Sjoerg           break;
581*82d56013Sjoerg         }
582*82d56013Sjoerg         case MachineLocKind::ImmediateKind: {
583*82d56013Sjoerg           MOs.push_back(Orig);
584*82d56013Sjoerg           break;
585*82d56013Sjoerg         }
586*82d56013Sjoerg         case MachineLocKind::InvalidKind:
587*82d56013Sjoerg           llvm_unreachable("Tried to produce DBG_VALUE for invalid VarLoc");
588*82d56013Sjoerg         }
589*82d56013Sjoerg       }
590*82d56013Sjoerg       return BuildMI(MF, DbgLoc, IID, Indirect, MOs, Var, DIExpr);
591*82d56013Sjoerg     }
592*82d56013Sjoerg 
593*82d56013Sjoerg     /// Is the Loc field a constant or constant object?
isConstant__anon250db9ad0111::VarLocBasedLDV::VarLoc594*82d56013Sjoerg     bool isConstant(MachineLocKind Kind) const {
595*82d56013Sjoerg       return Kind == MachineLocKind::ImmediateKind;
596*82d56013Sjoerg     }
597*82d56013Sjoerg 
598*82d56013Sjoerg     /// Check if the Loc field is an entry backup location.
isEntryBackupLoc__anon250db9ad0111::VarLocBasedLDV::VarLoc599*82d56013Sjoerg     bool isEntryBackupLoc() const {
600*82d56013Sjoerg       return EVKind == EntryValueLocKind::EntryValueBackupKind ||
601*82d56013Sjoerg              EVKind == EntryValueLocKind::EntryValueCopyBackupKind;
602*82d56013Sjoerg     }
603*82d56013Sjoerg 
604*82d56013Sjoerg     /// If this variable is described by register \p Reg holding the entry
605*82d56013Sjoerg     /// value, return true.
isEntryValueBackupReg__anon250db9ad0111::VarLocBasedLDV::VarLoc606*82d56013Sjoerg     bool isEntryValueBackupReg(Register Reg) const {
607*82d56013Sjoerg       return EVKind == EntryValueLocKind::EntryValueBackupKind && usesReg(Reg);
608*82d56013Sjoerg     }
609*82d56013Sjoerg 
610*82d56013Sjoerg     /// If this variable is described by register \p Reg holding a copy of the
611*82d56013Sjoerg     /// entry value, return true.
isEntryValueCopyBackupReg__anon250db9ad0111::VarLocBasedLDV::VarLoc612*82d56013Sjoerg     bool isEntryValueCopyBackupReg(Register Reg) const {
613*82d56013Sjoerg       return EVKind == EntryValueLocKind::EntryValueCopyBackupKind &&
614*82d56013Sjoerg              usesReg(Reg);
615*82d56013Sjoerg     }
616*82d56013Sjoerg 
617*82d56013Sjoerg     /// If this variable is described in whole or part by \p Reg, return true.
usesReg__anon250db9ad0111::VarLocBasedLDV::VarLoc618*82d56013Sjoerg     bool usesReg(Register Reg) const {
619*82d56013Sjoerg       MachineLoc RegML;
620*82d56013Sjoerg       RegML.Kind = MachineLocKind::RegisterKind;
621*82d56013Sjoerg       RegML.Value.RegNo = Reg;
622*82d56013Sjoerg       return is_contained(Locs, RegML);
623*82d56013Sjoerg     }
624*82d56013Sjoerg 
625*82d56013Sjoerg     /// If this variable is described in whole or part by \p Reg, return true.
getRegIdx__anon250db9ad0111::VarLocBasedLDV::VarLoc626*82d56013Sjoerg     unsigned getRegIdx(Register Reg) const {
627*82d56013Sjoerg       for (unsigned Idx = 0; Idx < Locs.size(); ++Idx)
628*82d56013Sjoerg         if (Locs[Idx].Kind == MachineLocKind::RegisterKind &&
629*82d56013Sjoerg             Locs[Idx].Value.RegNo == Reg)
630*82d56013Sjoerg           return Idx;
631*82d56013Sjoerg       llvm_unreachable("Could not find given Reg in Locs");
632*82d56013Sjoerg     }
633*82d56013Sjoerg 
634*82d56013Sjoerg     /// If this variable is described in whole or part by 1 or more registers,
635*82d56013Sjoerg     /// add each of them to \p Regs and return true.
getDescribingRegs__anon250db9ad0111::VarLocBasedLDV::VarLoc636*82d56013Sjoerg     bool getDescribingRegs(SmallVectorImpl<uint32_t> &Regs) const {
637*82d56013Sjoerg       bool AnyRegs = false;
638*82d56013Sjoerg       for (auto Loc : Locs)
639*82d56013Sjoerg         if (Loc.Kind == MachineLocKind::RegisterKind) {
640*82d56013Sjoerg           Regs.push_back(Loc.Value.RegNo);
641*82d56013Sjoerg           AnyRegs = true;
642*82d56013Sjoerg         }
643*82d56013Sjoerg       return AnyRegs;
644*82d56013Sjoerg     }
645*82d56013Sjoerg 
containsSpillLocs__anon250db9ad0111::VarLocBasedLDV::VarLoc646*82d56013Sjoerg     bool containsSpillLocs() const {
647*82d56013Sjoerg       return any_of(Locs, [](VarLoc::MachineLoc ML) {
648*82d56013Sjoerg         return ML.Kind == VarLoc::MachineLocKind::SpillLocKind;
649*82d56013Sjoerg       });
650*82d56013Sjoerg     }
651*82d56013Sjoerg 
652*82d56013Sjoerg     /// If this variable is described in whole or part by \p SpillLocation,
653*82d56013Sjoerg     /// return true.
usesSpillLoc__anon250db9ad0111::VarLocBasedLDV::VarLoc654*82d56013Sjoerg     bool usesSpillLoc(SpillLoc SpillLocation) const {
655*82d56013Sjoerg       MachineLoc SpillML;
656*82d56013Sjoerg       SpillML.Kind = MachineLocKind::SpillLocKind;
657*82d56013Sjoerg       SpillML.Value.SpillLocation = SpillLocation;
658*82d56013Sjoerg       return is_contained(Locs, SpillML);
659*82d56013Sjoerg     }
660*82d56013Sjoerg 
661*82d56013Sjoerg     /// If this variable is described in whole or part by \p SpillLocation,
662*82d56013Sjoerg     /// return the index .
getSpillLocIdx__anon250db9ad0111::VarLocBasedLDV::VarLoc663*82d56013Sjoerg     unsigned getSpillLocIdx(SpillLoc SpillLocation) const {
664*82d56013Sjoerg       for (unsigned Idx = 0; Idx < Locs.size(); ++Idx)
665*82d56013Sjoerg         if (Locs[Idx].Kind == MachineLocKind::SpillLocKind &&
666*82d56013Sjoerg             Locs[Idx].Value.SpillLocation == SpillLocation)
667*82d56013Sjoerg           return Idx;
668*82d56013Sjoerg       llvm_unreachable("Could not find given SpillLoc in Locs");
669*82d56013Sjoerg     }
670*82d56013Sjoerg 
671*82d56013Sjoerg     /// Determine whether the lexical scope of this value's debug location
672*82d56013Sjoerg     /// dominates MBB.
dominates__anon250db9ad0111::VarLocBasedLDV::VarLoc673*82d56013Sjoerg     bool dominates(LexicalScopes &LS, MachineBasicBlock &MBB) const {
674*82d56013Sjoerg       return LS.dominates(MI.getDebugLoc().get(), &MBB);
675*82d56013Sjoerg     }
676*82d56013Sjoerg 
677*82d56013Sjoerg #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
678*82d56013Sjoerg     // TRI can be null.
dump__anon250db9ad0111::VarLocBasedLDV::VarLoc679*82d56013Sjoerg     void dump(const TargetRegisterInfo *TRI, raw_ostream &Out = dbgs()) const {
680*82d56013Sjoerg       Out << "VarLoc(";
681*82d56013Sjoerg       for (const MachineLoc &MLoc : Locs) {
682*82d56013Sjoerg         if (Locs.begin() != &MLoc)
683*82d56013Sjoerg           Out << ", ";
684*82d56013Sjoerg         switch (MLoc.Kind) {
685*82d56013Sjoerg         case MachineLocKind::RegisterKind:
686*82d56013Sjoerg           Out << printReg(MLoc.Value.RegNo, TRI);
687*82d56013Sjoerg           break;
688*82d56013Sjoerg         case MachineLocKind::SpillLocKind:
689*82d56013Sjoerg           Out << printReg(MLoc.Value.SpillLocation.SpillBase, TRI);
690*82d56013Sjoerg           Out << "[" << MLoc.Value.SpillLocation.SpillOffset.getFixed() << " + "
691*82d56013Sjoerg               << MLoc.Value.SpillLocation.SpillOffset.getScalable()
692*82d56013Sjoerg               << "x vscale"
693*82d56013Sjoerg               << "]";
694*82d56013Sjoerg           break;
695*82d56013Sjoerg         case MachineLocKind::ImmediateKind:
696*82d56013Sjoerg           Out << MLoc.Value.Immediate;
697*82d56013Sjoerg           break;
698*82d56013Sjoerg         case MachineLocKind::InvalidKind:
699*82d56013Sjoerg           llvm_unreachable("Invalid VarLoc in dump method");
700*82d56013Sjoerg         }
701*82d56013Sjoerg       }
702*82d56013Sjoerg 
703*82d56013Sjoerg       Out << ", \"" << Var.getVariable()->getName() << "\", " << *Expr << ", ";
704*82d56013Sjoerg       if (Var.getInlinedAt())
705*82d56013Sjoerg         Out << "!" << Var.getInlinedAt()->getMetadataID() << ")\n";
706*82d56013Sjoerg       else
707*82d56013Sjoerg         Out << "(null))";
708*82d56013Sjoerg 
709*82d56013Sjoerg       if (isEntryBackupLoc())
710*82d56013Sjoerg         Out << " (backup loc)\n";
711*82d56013Sjoerg       else
712*82d56013Sjoerg         Out << "\n";
713*82d56013Sjoerg     }
714*82d56013Sjoerg #endif
715*82d56013Sjoerg 
operator ==__anon250db9ad0111::VarLocBasedLDV::VarLoc716*82d56013Sjoerg     bool operator==(const VarLoc &Other) const {
717*82d56013Sjoerg       return std::tie(EVKind, Var, Expr, Locs) ==
718*82d56013Sjoerg              std::tie(Other.EVKind, Other.Var, Other.Expr, Other.Locs);
719*82d56013Sjoerg     }
720*82d56013Sjoerg 
721*82d56013Sjoerg     /// This operator guarantees that VarLocs are sorted by Variable first.
operator <__anon250db9ad0111::VarLocBasedLDV::VarLoc722*82d56013Sjoerg     bool operator<(const VarLoc &Other) const {
723*82d56013Sjoerg       return std::tie(Var, EVKind, Locs, Expr) <
724*82d56013Sjoerg              std::tie(Other.Var, Other.EVKind, Other.Locs, Other.Expr);
725*82d56013Sjoerg     }
726*82d56013Sjoerg   };
727*82d56013Sjoerg 
728*82d56013Sjoerg #ifndef NDEBUG
729*82d56013Sjoerg   using VarVec = SmallVector<VarLoc, 32>;
730*82d56013Sjoerg #endif
731*82d56013Sjoerg 
732*82d56013Sjoerg   /// VarLocMap is used for two things:
733*82d56013Sjoerg   /// 1) Assigning LocIndices to a VarLoc. The LocIndices can be used to
734*82d56013Sjoerg   ///    virtually insert a VarLoc into a VarLocSet.
735*82d56013Sjoerg   /// 2) Given a LocIndex, look up the unique associated VarLoc.
736*82d56013Sjoerg   class VarLocMap {
737*82d56013Sjoerg     /// Map a VarLoc to an index within the vector reserved for its location
738*82d56013Sjoerg     /// within Loc2Vars.
739*82d56013Sjoerg     std::map<VarLoc, LocIndices> Var2Indices;
740*82d56013Sjoerg 
741*82d56013Sjoerg     /// Map a location to a vector which holds VarLocs which live in that
742*82d56013Sjoerg     /// location.
743*82d56013Sjoerg     SmallDenseMap<LocIndex::u32_location_t, std::vector<VarLoc>> Loc2Vars;
744*82d56013Sjoerg 
745*82d56013Sjoerg   public:
746*82d56013Sjoerg     /// Retrieve LocIndices for \p VL.
insert(const VarLoc & VL)747*82d56013Sjoerg     LocIndices insert(const VarLoc &VL) {
748*82d56013Sjoerg       LocIndices &Indices = Var2Indices[VL];
749*82d56013Sjoerg       // If Indices is not empty, VL is already in the map.
750*82d56013Sjoerg       if (!Indices.empty())
751*82d56013Sjoerg         return Indices;
752*82d56013Sjoerg       SmallVector<LocIndex::u32_location_t, 4> Locations;
753*82d56013Sjoerg       // LocIndices are determined by EVKind and MLs; each Register has a
754*82d56013Sjoerg       // unique location, while all SpillLocs use a single bucket, and any EV
755*82d56013Sjoerg       // VarLocs use only the Backup bucket or none at all (except the
756*82d56013Sjoerg       // compulsory entry at the universal location index). LocIndices will
757*82d56013Sjoerg       // always have an index at the universal location index as the last index.
758*82d56013Sjoerg       if (VL.EVKind == VarLoc::EntryValueLocKind::NonEntryValueKind) {
759*82d56013Sjoerg         VL.getDescribingRegs(Locations);
760*82d56013Sjoerg         assert(all_of(Locations,
761*82d56013Sjoerg                       [](auto RegNo) {
762*82d56013Sjoerg                         return RegNo < LocIndex::kFirstInvalidRegLocation;
763*82d56013Sjoerg                       }) &&
764*82d56013Sjoerg                "Physreg out of range?");
765*82d56013Sjoerg         if (VL.containsSpillLocs()) {
766*82d56013Sjoerg           LocIndex::u32_location_t Loc = LocIndex::kSpillLocation;
767*82d56013Sjoerg           Locations.push_back(Loc);
768*82d56013Sjoerg         }
769*82d56013Sjoerg       } else if (VL.EVKind != VarLoc::EntryValueLocKind::EntryValueKind) {
770*82d56013Sjoerg         LocIndex::u32_location_t Loc = LocIndex::kEntryValueBackupLocation;
771*82d56013Sjoerg         Locations.push_back(Loc);
772*82d56013Sjoerg       }
773*82d56013Sjoerg       Locations.push_back(LocIndex::kUniversalLocation);
774*82d56013Sjoerg       for (LocIndex::u32_location_t Location : Locations) {
775*82d56013Sjoerg         auto &Vars = Loc2Vars[Location];
776*82d56013Sjoerg         Indices.push_back(
777*82d56013Sjoerg             {Location, static_cast<LocIndex::u32_index_t>(Vars.size())});
778*82d56013Sjoerg         Vars.push_back(VL);
779*82d56013Sjoerg       }
780*82d56013Sjoerg       return Indices;
781*82d56013Sjoerg     }
782*82d56013Sjoerg 
getAllIndices(const VarLoc & VL) const783*82d56013Sjoerg     LocIndices getAllIndices(const VarLoc &VL) const {
784*82d56013Sjoerg       auto IndIt = Var2Indices.find(VL);
785*82d56013Sjoerg       assert(IndIt != Var2Indices.end() && "VarLoc not tracked");
786*82d56013Sjoerg       return IndIt->second;
787*82d56013Sjoerg     }
788*82d56013Sjoerg 
789*82d56013Sjoerg     /// Retrieve the unique VarLoc associated with \p ID.
operator [](LocIndex ID) const790*82d56013Sjoerg     const VarLoc &operator[](LocIndex ID) const {
791*82d56013Sjoerg       auto LocIt = Loc2Vars.find(ID.Location);
792*82d56013Sjoerg       assert(LocIt != Loc2Vars.end() && "Location not tracked");
793*82d56013Sjoerg       return LocIt->second[ID.Index];
794*82d56013Sjoerg     }
795*82d56013Sjoerg   };
796*82d56013Sjoerg 
797*82d56013Sjoerg   using VarLocInMBB =
798*82d56013Sjoerg       SmallDenseMap<const MachineBasicBlock *, std::unique_ptr<VarLocSet>>;
799*82d56013Sjoerg   struct TransferDebugPair {
800*82d56013Sjoerg     MachineInstr *TransferInst; ///< Instruction where this transfer occurs.
801*82d56013Sjoerg     LocIndex LocationID;        ///< Location number for the transfer dest.
802*82d56013Sjoerg   };
803*82d56013Sjoerg   using TransferMap = SmallVector<TransferDebugPair, 4>;
804*82d56013Sjoerg 
805*82d56013Sjoerg   // Types for recording sets of variable fragments that overlap. For a given
806*82d56013Sjoerg   // local variable, we record all other fragments of that variable that could
807*82d56013Sjoerg   // overlap it, to reduce search time.
808*82d56013Sjoerg   using FragmentOfVar =
809*82d56013Sjoerg       std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
810*82d56013Sjoerg   using OverlapMap =
811*82d56013Sjoerg       DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
812*82d56013Sjoerg 
813*82d56013Sjoerg   // Helper while building OverlapMap, a map of all fragments seen for a given
814*82d56013Sjoerg   // DILocalVariable.
815*82d56013Sjoerg   using VarToFragments =
816*82d56013Sjoerg       DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
817*82d56013Sjoerg 
818*82d56013Sjoerg   /// Collects all VarLocs from \p CollectFrom. Each unique VarLoc is added
819*82d56013Sjoerg   /// to \p Collected once, in order of insertion into \p VarLocIDs.
820*82d56013Sjoerg   static void collectAllVarLocs(SmallVectorImpl<VarLoc> &Collected,
821*82d56013Sjoerg                                 const VarLocSet &CollectFrom,
822*82d56013Sjoerg                                 const VarLocMap &VarLocIDs);
823*82d56013Sjoerg 
824*82d56013Sjoerg   /// Get the registers which are used by VarLocs of kind RegisterKind tracked
825*82d56013Sjoerg   /// by \p CollectFrom.
826*82d56013Sjoerg   void getUsedRegs(const VarLocSet &CollectFrom,
827*82d56013Sjoerg                    SmallVectorImpl<Register> &UsedRegs) const;
828*82d56013Sjoerg 
829*82d56013Sjoerg   /// This holds the working set of currently open ranges. For fast
830*82d56013Sjoerg   /// access, this is done both as a set of VarLocIDs, and a map of
831*82d56013Sjoerg   /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
832*82d56013Sjoerg   /// previous open ranges for the same variable. In addition, we keep
833*82d56013Sjoerg   /// two different maps (Vars/EntryValuesBackupVars), so erase/insert
834*82d56013Sjoerg   /// methods act differently depending on whether a VarLoc is primary
835*82d56013Sjoerg   /// location or backup one. In the case the VarLoc is backup location
836*82d56013Sjoerg   /// we will erase/insert from the EntryValuesBackupVars map, otherwise
837*82d56013Sjoerg   /// we perform the operation on the Vars.
838*82d56013Sjoerg   class OpenRangesSet {
839*82d56013Sjoerg     VarLocSet::Allocator &Alloc;
840*82d56013Sjoerg     VarLocSet VarLocs;
841*82d56013Sjoerg     // Map the DebugVariable to recent primary location ID.
842*82d56013Sjoerg     SmallDenseMap<DebugVariable, LocIndices, 8> Vars;
843*82d56013Sjoerg     // Map the DebugVariable to recent backup location ID.
844*82d56013Sjoerg     SmallDenseMap<DebugVariable, LocIndices, 8> EntryValuesBackupVars;
845*82d56013Sjoerg     OverlapMap &OverlappingFragments;
846*82d56013Sjoerg 
847*82d56013Sjoerg   public:
OpenRangesSet(VarLocSet::Allocator & Alloc,OverlapMap & _OLapMap)848*82d56013Sjoerg     OpenRangesSet(VarLocSet::Allocator &Alloc, OverlapMap &_OLapMap)
849*82d56013Sjoerg         : Alloc(Alloc), VarLocs(Alloc), OverlappingFragments(_OLapMap) {}
850*82d56013Sjoerg 
getVarLocs() const851*82d56013Sjoerg     const VarLocSet &getVarLocs() const { return VarLocs; }
852*82d56013Sjoerg 
853*82d56013Sjoerg     // Fetches all VarLocs in \p VarLocIDs and inserts them into \p Collected.
854*82d56013Sjoerg     // This method is needed to get every VarLoc once, as each VarLoc may have
855*82d56013Sjoerg     // multiple indices in a VarLocMap (corresponding to each applicable
856*82d56013Sjoerg     // location), but all VarLocs appear exactly once at the universal location
857*82d56013Sjoerg     // index.
getUniqueVarLocs(SmallVectorImpl<VarLoc> & Collected,const VarLocMap & VarLocIDs) const858*82d56013Sjoerg     void getUniqueVarLocs(SmallVectorImpl<VarLoc> &Collected,
859*82d56013Sjoerg                           const VarLocMap &VarLocIDs) const {
860*82d56013Sjoerg       collectAllVarLocs(Collected, VarLocs, VarLocIDs);
861*82d56013Sjoerg     }
862*82d56013Sjoerg 
863*82d56013Sjoerg     /// Terminate all open ranges for VL.Var by removing it from the set.
864*82d56013Sjoerg     void erase(const VarLoc &VL);
865*82d56013Sjoerg 
866*82d56013Sjoerg     /// Terminate all open ranges listed as indices in \c KillSet with
867*82d56013Sjoerg     /// \c Location by removing them from the set.
868*82d56013Sjoerg     void erase(const VarLocsInRange &KillSet, const VarLocMap &VarLocIDs,
869*82d56013Sjoerg                LocIndex::u32_location_t Location);
870*82d56013Sjoerg 
871*82d56013Sjoerg     /// Insert a new range into the set.
872*82d56013Sjoerg     void insert(LocIndices VarLocIDs, const VarLoc &VL);
873*82d56013Sjoerg 
874*82d56013Sjoerg     /// Insert a set of ranges.
875*82d56013Sjoerg     void insertFromLocSet(const VarLocSet &ToLoad, const VarLocMap &Map);
876*82d56013Sjoerg 
877*82d56013Sjoerg     llvm::Optional<LocIndices> getEntryValueBackup(DebugVariable Var);
878*82d56013Sjoerg 
879*82d56013Sjoerg     /// Empty the set.
clear()880*82d56013Sjoerg     void clear() {
881*82d56013Sjoerg       VarLocs.clear();
882*82d56013Sjoerg       Vars.clear();
883*82d56013Sjoerg       EntryValuesBackupVars.clear();
884*82d56013Sjoerg     }
885*82d56013Sjoerg 
886*82d56013Sjoerg     /// Return whether the set is empty or not.
empty() const887*82d56013Sjoerg     bool empty() const {
888*82d56013Sjoerg       assert(Vars.empty() == EntryValuesBackupVars.empty() &&
889*82d56013Sjoerg              Vars.empty() == VarLocs.empty() &&
890*82d56013Sjoerg              "open ranges are inconsistent");
891*82d56013Sjoerg       return VarLocs.empty();
892*82d56013Sjoerg     }
893*82d56013Sjoerg 
894*82d56013Sjoerg     /// Get an empty range of VarLoc IDs.
getEmptyVarLocRange() const895*82d56013Sjoerg     auto getEmptyVarLocRange() const {
896*82d56013Sjoerg       return iterator_range<VarLocSet::const_iterator>(getVarLocs().end(),
897*82d56013Sjoerg                                                        getVarLocs().end());
898*82d56013Sjoerg     }
899*82d56013Sjoerg 
900*82d56013Sjoerg     /// Get all set IDs for VarLocs with MLs of kind RegisterKind in \p Reg.
getRegisterVarLocs(Register Reg) const901*82d56013Sjoerg     auto getRegisterVarLocs(Register Reg) const {
902*82d56013Sjoerg       return LocIndex::indexRangeForLocation(getVarLocs(), Reg);
903*82d56013Sjoerg     }
904*82d56013Sjoerg 
905*82d56013Sjoerg     /// Get all set IDs for VarLocs with MLs of kind SpillLocKind.
getSpillVarLocs() const906*82d56013Sjoerg     auto getSpillVarLocs() const {
907*82d56013Sjoerg       return LocIndex::indexRangeForLocation(getVarLocs(),
908*82d56013Sjoerg                                              LocIndex::kSpillLocation);
909*82d56013Sjoerg     }
910*82d56013Sjoerg 
911*82d56013Sjoerg     /// Get all set IDs for VarLocs of EVKind EntryValueBackupKind or
912*82d56013Sjoerg     /// EntryValueCopyBackupKind.
getEntryValueBackupVarLocs() const913*82d56013Sjoerg     auto getEntryValueBackupVarLocs() const {
914*82d56013Sjoerg       return LocIndex::indexRangeForLocation(
915*82d56013Sjoerg           getVarLocs(), LocIndex::kEntryValueBackupLocation);
916*82d56013Sjoerg     }
917*82d56013Sjoerg   };
918*82d56013Sjoerg 
919*82d56013Sjoerg   /// Collect all VarLoc IDs from \p CollectFrom for VarLocs with MLs of kind
920*82d56013Sjoerg   /// RegisterKind which are located in any reg in \p Regs. The IDs for each
921*82d56013Sjoerg   /// VarLoc correspond to entries in the universal location bucket, which every
922*82d56013Sjoerg   /// VarLoc has exactly 1 entry for. Insert collected IDs into \p Collected.
923*82d56013Sjoerg   static void collectIDsForRegs(VarLocsInRange &Collected,
924*82d56013Sjoerg                                 const DefinedRegsSet &Regs,
925*82d56013Sjoerg                                 const VarLocSet &CollectFrom,
926*82d56013Sjoerg                                 const VarLocMap &VarLocIDs);
927*82d56013Sjoerg 
getVarLocsInMBB(const MachineBasicBlock * MBB,VarLocInMBB & Locs)928*82d56013Sjoerg   VarLocSet &getVarLocsInMBB(const MachineBasicBlock *MBB, VarLocInMBB &Locs) {
929*82d56013Sjoerg     std::unique_ptr<VarLocSet> &VLS = Locs[MBB];
930*82d56013Sjoerg     if (!VLS)
931*82d56013Sjoerg       VLS = std::make_unique<VarLocSet>(Alloc);
932*82d56013Sjoerg     return *VLS.get();
933*82d56013Sjoerg   }
934*82d56013Sjoerg 
getVarLocsInMBB(const MachineBasicBlock * MBB,const VarLocInMBB & Locs) const935*82d56013Sjoerg   const VarLocSet &getVarLocsInMBB(const MachineBasicBlock *MBB,
936*82d56013Sjoerg                                    const VarLocInMBB &Locs) const {
937*82d56013Sjoerg     auto It = Locs.find(MBB);
938*82d56013Sjoerg     assert(It != Locs.end() && "MBB not in map");
939*82d56013Sjoerg     return *It->second.get();
940*82d56013Sjoerg   }
941*82d56013Sjoerg 
942*82d56013Sjoerg   /// Tests whether this instruction is a spill to a stack location.
943*82d56013Sjoerg   bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF);
944*82d56013Sjoerg 
945*82d56013Sjoerg   /// Decide if @MI is a spill instruction and return true if it is. We use 2
946*82d56013Sjoerg   /// criteria to make this decision:
947*82d56013Sjoerg   /// - Is this instruction a store to a spill slot?
948*82d56013Sjoerg   /// - Is there a register operand that is both used and killed?
949*82d56013Sjoerg   /// TODO: Store optimization can fold spills into other stores (including
950*82d56013Sjoerg   /// other spills). We do not handle this yet (more than one memory operand).
951*82d56013Sjoerg   bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF,
952*82d56013Sjoerg                        Register &Reg);
953*82d56013Sjoerg 
954*82d56013Sjoerg   /// Returns true if the given machine instruction is a debug value which we
955*82d56013Sjoerg   /// can emit entry values for.
956*82d56013Sjoerg   ///
957*82d56013Sjoerg   /// Currently, we generate debug entry values only for parameters that are
958*82d56013Sjoerg   /// unmodified throughout the function and located in a register.
959*82d56013Sjoerg   bool isEntryValueCandidate(const MachineInstr &MI,
960*82d56013Sjoerg                              const DefinedRegsSet &Regs) const;
961*82d56013Sjoerg 
962*82d56013Sjoerg   /// If a given instruction is identified as a spill, return the spill location
963*82d56013Sjoerg   /// and set \p Reg to the spilled register.
964*82d56013Sjoerg   Optional<VarLoc::SpillLoc> isRestoreInstruction(const MachineInstr &MI,
965*82d56013Sjoerg                                                   MachineFunction *MF,
966*82d56013Sjoerg                                                   Register &Reg);
967*82d56013Sjoerg   /// Given a spill instruction, extract the register and offset used to
968*82d56013Sjoerg   /// address the spill location in a target independent way.
969*82d56013Sjoerg   VarLoc::SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI);
970*82d56013Sjoerg   void insertTransferDebugPair(MachineInstr &MI, OpenRangesSet &OpenRanges,
971*82d56013Sjoerg                                TransferMap &Transfers, VarLocMap &VarLocIDs,
972*82d56013Sjoerg                                LocIndex OldVarID, TransferKind Kind,
973*82d56013Sjoerg                                const VarLoc::MachineLoc &OldLoc,
974*82d56013Sjoerg                                Register NewReg = Register());
975*82d56013Sjoerg 
976*82d56013Sjoerg   void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
977*82d56013Sjoerg                           VarLocMap &VarLocIDs);
978*82d56013Sjoerg   void transferSpillOrRestoreInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
979*82d56013Sjoerg                                   VarLocMap &VarLocIDs, TransferMap &Transfers);
980*82d56013Sjoerg   bool removeEntryValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
981*82d56013Sjoerg                         VarLocMap &VarLocIDs, const VarLoc &EntryVL);
982*82d56013Sjoerg   void emitEntryValues(MachineInstr &MI, OpenRangesSet &OpenRanges,
983*82d56013Sjoerg                        VarLocMap &VarLocIDs, TransferMap &Transfers,
984*82d56013Sjoerg                        VarLocsInRange &KillSet);
985*82d56013Sjoerg   void recordEntryValue(const MachineInstr &MI,
986*82d56013Sjoerg                         const DefinedRegsSet &DefinedRegs,
987*82d56013Sjoerg                         OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs);
988*82d56013Sjoerg   void transferRegisterCopy(MachineInstr &MI, OpenRangesSet &OpenRanges,
989*82d56013Sjoerg                             VarLocMap &VarLocIDs, TransferMap &Transfers);
990*82d56013Sjoerg   void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
991*82d56013Sjoerg                            VarLocMap &VarLocIDs, TransferMap &Transfers);
992*82d56013Sjoerg   bool transferTerminator(MachineBasicBlock *MBB, OpenRangesSet &OpenRanges,
993*82d56013Sjoerg                           VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
994*82d56013Sjoerg 
995*82d56013Sjoerg   void process(MachineInstr &MI, OpenRangesSet &OpenRanges,
996*82d56013Sjoerg                VarLocMap &VarLocIDs, TransferMap &Transfers);
997*82d56013Sjoerg 
998*82d56013Sjoerg   void accumulateFragmentMap(MachineInstr &MI, VarToFragments &SeenFragments,
999*82d56013Sjoerg                              OverlapMap &OLapMap);
1000*82d56013Sjoerg 
1001*82d56013Sjoerg   bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
1002*82d56013Sjoerg             const VarLocMap &VarLocIDs,
1003*82d56013Sjoerg             SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
1004*82d56013Sjoerg             SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks);
1005*82d56013Sjoerg 
1006*82d56013Sjoerg   /// Create DBG_VALUE insts for inlocs that have been propagated but
1007*82d56013Sjoerg   /// had their instruction creation deferred.
1008*82d56013Sjoerg   void flushPendingLocs(VarLocInMBB &PendingInLocs, VarLocMap &VarLocIDs);
1009*82d56013Sjoerg 
1010*82d56013Sjoerg   bool ExtendRanges(MachineFunction &MF, TargetPassConfig *TPC) override;
1011*82d56013Sjoerg 
1012*82d56013Sjoerg public:
1013*82d56013Sjoerg   /// Default construct and initialize the pass.
1014*82d56013Sjoerg   VarLocBasedLDV();
1015*82d56013Sjoerg 
1016*82d56013Sjoerg   ~VarLocBasedLDV();
1017*82d56013Sjoerg 
1018*82d56013Sjoerg   /// Print to ostream with a message.
1019*82d56013Sjoerg   void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
1020*82d56013Sjoerg                         const VarLocMap &VarLocIDs, const char *msg,
1021*82d56013Sjoerg                         raw_ostream &Out) const;
1022*82d56013Sjoerg };
1023*82d56013Sjoerg 
1024*82d56013Sjoerg } // end anonymous namespace
1025*82d56013Sjoerg 
1026*82d56013Sjoerg //===----------------------------------------------------------------------===//
1027*82d56013Sjoerg //            Implementation
1028*82d56013Sjoerg //===----------------------------------------------------------------------===//
1029*82d56013Sjoerg 
VarLocBasedLDV()1030*82d56013Sjoerg VarLocBasedLDV::VarLocBasedLDV() { }
1031*82d56013Sjoerg 
~VarLocBasedLDV()1032*82d56013Sjoerg VarLocBasedLDV::~VarLocBasedLDV() { }
1033*82d56013Sjoerg 
1034*82d56013Sjoerg /// Erase a variable from the set of open ranges, and additionally erase any
1035*82d56013Sjoerg /// fragments that may overlap it. If the VarLoc is a backup location, erase
1036*82d56013Sjoerg /// the variable from the EntryValuesBackupVars set, indicating we should stop
1037*82d56013Sjoerg /// tracking its backup entry location. Otherwise, if the VarLoc is primary
1038*82d56013Sjoerg /// location, erase the variable from the Vars set.
erase(const VarLoc & VL)1039*82d56013Sjoerg void VarLocBasedLDV::OpenRangesSet::erase(const VarLoc &VL) {
1040*82d56013Sjoerg   // Erasure helper.
1041*82d56013Sjoerg   auto DoErase = [VL, this](DebugVariable VarToErase) {
1042*82d56013Sjoerg     auto *EraseFrom = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
1043*82d56013Sjoerg     auto It = EraseFrom->find(VarToErase);
1044*82d56013Sjoerg     if (It != EraseFrom->end()) {
1045*82d56013Sjoerg       LocIndices IDs = It->second;
1046*82d56013Sjoerg       for (LocIndex ID : IDs)
1047*82d56013Sjoerg         VarLocs.reset(ID.getAsRawInteger());
1048*82d56013Sjoerg       EraseFrom->erase(It);
1049*82d56013Sjoerg     }
1050*82d56013Sjoerg   };
1051*82d56013Sjoerg 
1052*82d56013Sjoerg   DebugVariable Var = VL.Var;
1053*82d56013Sjoerg 
1054*82d56013Sjoerg   // Erase the variable/fragment that ends here.
1055*82d56013Sjoerg   DoErase(Var);
1056*82d56013Sjoerg 
1057*82d56013Sjoerg   // Extract the fragment. Interpret an empty fragment as one that covers all
1058*82d56013Sjoerg   // possible bits.
1059*82d56013Sjoerg   FragmentInfo ThisFragment = Var.getFragmentOrDefault();
1060*82d56013Sjoerg 
1061*82d56013Sjoerg   // There may be fragments that overlap the designated fragment. Look them up
1062*82d56013Sjoerg   // in the pre-computed overlap map, and erase them too.
1063*82d56013Sjoerg   auto MapIt = OverlappingFragments.find({Var.getVariable(), ThisFragment});
1064*82d56013Sjoerg   if (MapIt != OverlappingFragments.end()) {
1065*82d56013Sjoerg     for (auto Fragment : MapIt->second) {
1066*82d56013Sjoerg       VarLocBasedLDV::OptFragmentInfo FragmentHolder;
1067*82d56013Sjoerg       if (!DebugVariable::isDefaultFragment(Fragment))
1068*82d56013Sjoerg         FragmentHolder = VarLocBasedLDV::OptFragmentInfo(Fragment);
1069*82d56013Sjoerg       DoErase({Var.getVariable(), FragmentHolder, Var.getInlinedAt()});
1070*82d56013Sjoerg     }
1071*82d56013Sjoerg   }
1072*82d56013Sjoerg }
1073*82d56013Sjoerg 
erase(const VarLocsInRange & KillSet,const VarLocMap & VarLocIDs,LocIndex::u32_location_t Location)1074*82d56013Sjoerg void VarLocBasedLDV::OpenRangesSet::erase(const VarLocsInRange &KillSet,
1075*82d56013Sjoerg                                           const VarLocMap &VarLocIDs,
1076*82d56013Sjoerg                                           LocIndex::u32_location_t Location) {
1077*82d56013Sjoerg   VarLocSet RemoveSet(Alloc);
1078*82d56013Sjoerg   for (LocIndex::u32_index_t ID : KillSet) {
1079*82d56013Sjoerg     const VarLoc &VL = VarLocIDs[LocIndex(Location, ID)];
1080*82d56013Sjoerg     auto *EraseFrom = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
1081*82d56013Sjoerg     EraseFrom->erase(VL.Var);
1082*82d56013Sjoerg     LocIndices VLI = VarLocIDs.getAllIndices(VL);
1083*82d56013Sjoerg     for (LocIndex ID : VLI)
1084*82d56013Sjoerg       RemoveSet.set(ID.getAsRawInteger());
1085*82d56013Sjoerg   }
1086*82d56013Sjoerg   VarLocs.intersectWithComplement(RemoveSet);
1087*82d56013Sjoerg }
1088*82d56013Sjoerg 
insertFromLocSet(const VarLocSet & ToLoad,const VarLocMap & Map)1089*82d56013Sjoerg void VarLocBasedLDV::OpenRangesSet::insertFromLocSet(const VarLocSet &ToLoad,
1090*82d56013Sjoerg                                                      const VarLocMap &Map) {
1091*82d56013Sjoerg   VarLocsInRange UniqueVarLocIDs;
1092*82d56013Sjoerg   DefinedRegsSet Regs;
1093*82d56013Sjoerg   Regs.insert(LocIndex::kUniversalLocation);
1094*82d56013Sjoerg   collectIDsForRegs(UniqueVarLocIDs, Regs, ToLoad, Map);
1095*82d56013Sjoerg   for (uint64_t ID : UniqueVarLocIDs) {
1096*82d56013Sjoerg     LocIndex Idx = LocIndex::fromRawInteger(ID);
1097*82d56013Sjoerg     const VarLoc &VarL = Map[Idx];
1098*82d56013Sjoerg     const LocIndices Indices = Map.getAllIndices(VarL);
1099*82d56013Sjoerg     insert(Indices, VarL);
1100*82d56013Sjoerg   }
1101*82d56013Sjoerg }
1102*82d56013Sjoerg 
insert(LocIndices VarLocIDs,const VarLoc & VL)1103*82d56013Sjoerg void VarLocBasedLDV::OpenRangesSet::insert(LocIndices VarLocIDs,
1104*82d56013Sjoerg                                            const VarLoc &VL) {
1105*82d56013Sjoerg   auto *InsertInto = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
1106*82d56013Sjoerg   for (LocIndex ID : VarLocIDs)
1107*82d56013Sjoerg     VarLocs.set(ID.getAsRawInteger());
1108*82d56013Sjoerg   InsertInto->insert({VL.Var, VarLocIDs});
1109*82d56013Sjoerg }
1110*82d56013Sjoerg 
1111*82d56013Sjoerg /// Return the Loc ID of an entry value backup location, if it exists for the
1112*82d56013Sjoerg /// variable.
1113*82d56013Sjoerg llvm::Optional<LocIndices>
getEntryValueBackup(DebugVariable Var)1114*82d56013Sjoerg VarLocBasedLDV::OpenRangesSet::getEntryValueBackup(DebugVariable Var) {
1115*82d56013Sjoerg   auto It = EntryValuesBackupVars.find(Var);
1116*82d56013Sjoerg   if (It != EntryValuesBackupVars.end())
1117*82d56013Sjoerg     return It->second;
1118*82d56013Sjoerg 
1119*82d56013Sjoerg   return llvm::None;
1120*82d56013Sjoerg }
1121*82d56013Sjoerg 
collectIDsForRegs(VarLocsInRange & Collected,const DefinedRegsSet & Regs,const VarLocSet & CollectFrom,const VarLocMap & VarLocIDs)1122*82d56013Sjoerg void VarLocBasedLDV::collectIDsForRegs(VarLocsInRange &Collected,
1123*82d56013Sjoerg                                        const DefinedRegsSet &Regs,
1124*82d56013Sjoerg                                        const VarLocSet &CollectFrom,
1125*82d56013Sjoerg                                        const VarLocMap &VarLocIDs) {
1126*82d56013Sjoerg   assert(!Regs.empty() && "Nothing to collect");
1127*82d56013Sjoerg   SmallVector<Register, 32> SortedRegs;
1128*82d56013Sjoerg   append_range(SortedRegs, Regs);
1129*82d56013Sjoerg   array_pod_sort(SortedRegs.begin(), SortedRegs.end());
1130*82d56013Sjoerg   auto It = CollectFrom.find(LocIndex::rawIndexForReg(SortedRegs.front()));
1131*82d56013Sjoerg   auto End = CollectFrom.end();
1132*82d56013Sjoerg   for (Register Reg : SortedRegs) {
1133*82d56013Sjoerg     // The half-open interval [FirstIndexForReg, FirstInvalidIndex) contains
1134*82d56013Sjoerg     // all possible VarLoc IDs for VarLocs with MLs of kind RegisterKind which
1135*82d56013Sjoerg     // live in Reg.
1136*82d56013Sjoerg     uint64_t FirstIndexForReg = LocIndex::rawIndexForReg(Reg);
1137*82d56013Sjoerg     uint64_t FirstInvalidIndex = LocIndex::rawIndexForReg(Reg + 1);
1138*82d56013Sjoerg     It.advanceToLowerBound(FirstIndexForReg);
1139*82d56013Sjoerg 
1140*82d56013Sjoerg     // Iterate through that half-open interval and collect all the set IDs.
1141*82d56013Sjoerg     for (; It != End && *It < FirstInvalidIndex; ++It) {
1142*82d56013Sjoerg       LocIndex ItIdx = LocIndex::fromRawInteger(*It);
1143*82d56013Sjoerg       const VarLoc &VL = VarLocIDs[ItIdx];
1144*82d56013Sjoerg       LocIndices LI = VarLocIDs.getAllIndices(VL);
1145*82d56013Sjoerg       // For now, the back index is always the universal location index.
1146*82d56013Sjoerg       assert(LI.back().Location == LocIndex::kUniversalLocation &&
1147*82d56013Sjoerg              "Unexpected order of LocIndices for VarLoc; was it inserted into "
1148*82d56013Sjoerg              "the VarLocMap correctly?");
1149*82d56013Sjoerg       Collected.insert(LI.back().Index);
1150*82d56013Sjoerg     }
1151*82d56013Sjoerg 
1152*82d56013Sjoerg     if (It == End)
1153*82d56013Sjoerg       return;
1154*82d56013Sjoerg   }
1155*82d56013Sjoerg }
1156*82d56013Sjoerg 
getUsedRegs(const VarLocSet & CollectFrom,SmallVectorImpl<Register> & UsedRegs) const1157*82d56013Sjoerg void VarLocBasedLDV::getUsedRegs(const VarLocSet &CollectFrom,
1158*82d56013Sjoerg                                  SmallVectorImpl<Register> &UsedRegs) const {
1159*82d56013Sjoerg   // All register-based VarLocs are assigned indices greater than or equal to
1160*82d56013Sjoerg   // FirstRegIndex.
1161*82d56013Sjoerg   uint64_t FirstRegIndex =
1162*82d56013Sjoerg       LocIndex::rawIndexForReg(LocIndex::kFirstRegLocation);
1163*82d56013Sjoerg   uint64_t FirstInvalidIndex =
1164*82d56013Sjoerg       LocIndex::rawIndexForReg(LocIndex::kFirstInvalidRegLocation);
1165*82d56013Sjoerg   for (auto It = CollectFrom.find(FirstRegIndex),
1166*82d56013Sjoerg             End = CollectFrom.find(FirstInvalidIndex);
1167*82d56013Sjoerg        It != End;) {
1168*82d56013Sjoerg     // We found a VarLoc ID for a VarLoc that lives in a register. Figure out
1169*82d56013Sjoerg     // which register and add it to UsedRegs.
1170*82d56013Sjoerg     uint32_t FoundReg = LocIndex::fromRawInteger(*It).Location;
1171*82d56013Sjoerg     assert((UsedRegs.empty() || FoundReg != UsedRegs.back()) &&
1172*82d56013Sjoerg            "Duplicate used reg");
1173*82d56013Sjoerg     UsedRegs.push_back(FoundReg);
1174*82d56013Sjoerg 
1175*82d56013Sjoerg     // Skip to the next /set/ register. Note that this finds a lower bound, so
1176*82d56013Sjoerg     // even if there aren't any VarLocs living in `FoundReg+1`, we're still
1177*82d56013Sjoerg     // guaranteed to move on to the next register (or to end()).
1178*82d56013Sjoerg     uint64_t NextRegIndex = LocIndex::rawIndexForReg(FoundReg + 1);
1179*82d56013Sjoerg     It.advanceToLowerBound(NextRegIndex);
1180*82d56013Sjoerg   }
1181*82d56013Sjoerg }
1182*82d56013Sjoerg 
1183*82d56013Sjoerg //===----------------------------------------------------------------------===//
1184*82d56013Sjoerg //            Debug Range Extension Implementation
1185*82d56013Sjoerg //===----------------------------------------------------------------------===//
1186*82d56013Sjoerg 
1187*82d56013Sjoerg #ifndef NDEBUG
printVarLocInMBB(const MachineFunction & MF,const VarLocInMBB & V,const VarLocMap & VarLocIDs,const char * msg,raw_ostream & Out) const1188*82d56013Sjoerg void VarLocBasedLDV::printVarLocInMBB(const MachineFunction &MF,
1189*82d56013Sjoerg                                        const VarLocInMBB &V,
1190*82d56013Sjoerg                                        const VarLocMap &VarLocIDs,
1191*82d56013Sjoerg                                        const char *msg,
1192*82d56013Sjoerg                                        raw_ostream &Out) const {
1193*82d56013Sjoerg   Out << '\n' << msg << '\n';
1194*82d56013Sjoerg   for (const MachineBasicBlock &BB : MF) {
1195*82d56013Sjoerg     if (!V.count(&BB))
1196*82d56013Sjoerg       continue;
1197*82d56013Sjoerg     const VarLocSet &L = getVarLocsInMBB(&BB, V);
1198*82d56013Sjoerg     if (L.empty())
1199*82d56013Sjoerg       continue;
1200*82d56013Sjoerg     SmallVector<VarLoc, 32> VarLocs;
1201*82d56013Sjoerg     collectAllVarLocs(VarLocs, L, VarLocIDs);
1202*82d56013Sjoerg     Out << "MBB: " << BB.getNumber() << ":\n";
1203*82d56013Sjoerg     for (const VarLoc &VL : VarLocs) {
1204*82d56013Sjoerg       Out << " Var: " << VL.Var.getVariable()->getName();
1205*82d56013Sjoerg       Out << " MI: ";
1206*82d56013Sjoerg       VL.dump(TRI, Out);
1207*82d56013Sjoerg     }
1208*82d56013Sjoerg   }
1209*82d56013Sjoerg   Out << "\n";
1210*82d56013Sjoerg }
1211*82d56013Sjoerg #endif
1212*82d56013Sjoerg 
1213*82d56013Sjoerg VarLocBasedLDV::VarLoc::SpillLoc
extractSpillBaseRegAndOffset(const MachineInstr & MI)1214*82d56013Sjoerg VarLocBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
1215*82d56013Sjoerg   assert(MI.hasOneMemOperand() &&
1216*82d56013Sjoerg          "Spill instruction does not have exactly one memory operand?");
1217*82d56013Sjoerg   auto MMOI = MI.memoperands_begin();
1218*82d56013Sjoerg   const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
1219*82d56013Sjoerg   assert(PVal->kind() == PseudoSourceValue::FixedStack &&
1220*82d56013Sjoerg          "Inconsistent memory operand in spill instruction");
1221*82d56013Sjoerg   int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
1222*82d56013Sjoerg   const MachineBasicBlock *MBB = MI.getParent();
1223*82d56013Sjoerg   Register Reg;
1224*82d56013Sjoerg   StackOffset Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
1225*82d56013Sjoerg   return {Reg, Offset};
1226*82d56013Sjoerg }
1227*82d56013Sjoerg 
1228*82d56013Sjoerg /// Try to salvage the debug entry value if we encounter a new debug value
1229*82d56013Sjoerg /// describing the same parameter, otherwise stop tracking the value. Return
1230*82d56013Sjoerg /// true if we should stop tracking the entry value, otherwise return false.
removeEntryValue(const MachineInstr & MI,OpenRangesSet & OpenRanges,VarLocMap & VarLocIDs,const VarLoc & EntryVL)1231*82d56013Sjoerg bool VarLocBasedLDV::removeEntryValue(const MachineInstr &MI,
1232*82d56013Sjoerg                                        OpenRangesSet &OpenRanges,
1233*82d56013Sjoerg                                        VarLocMap &VarLocIDs,
1234*82d56013Sjoerg                                        const VarLoc &EntryVL) {
1235*82d56013Sjoerg   // Skip the DBG_VALUE which is the debug entry value itself.
1236*82d56013Sjoerg   if (MI.isIdenticalTo(EntryVL.MI))
1237*82d56013Sjoerg     return false;
1238*82d56013Sjoerg 
1239*82d56013Sjoerg   // If the parameter's location is not register location, we can not track
1240*82d56013Sjoerg   // the entry value any more. In addition, if the debug expression from the
1241*82d56013Sjoerg   // DBG_VALUE is not empty, we can assume the parameter's value has changed
1242*82d56013Sjoerg   // indicating that we should stop tracking its entry value as well.
1243*82d56013Sjoerg   if (!MI.getDebugOperand(0).isReg() ||
1244*82d56013Sjoerg       MI.getDebugExpression()->getNumElements() != 0)
1245*82d56013Sjoerg     return true;
1246*82d56013Sjoerg 
1247*82d56013Sjoerg   // If the DBG_VALUE comes from a copy instruction that copies the entry value,
1248*82d56013Sjoerg   // it means the parameter's value has not changed and we should be able to use
1249*82d56013Sjoerg   // its entry value.
1250*82d56013Sjoerg   Register Reg = MI.getDebugOperand(0).getReg();
1251*82d56013Sjoerg   auto I = std::next(MI.getReverseIterator());
1252*82d56013Sjoerg   const MachineOperand *SrcRegOp, *DestRegOp;
1253*82d56013Sjoerg   if (I != MI.getParent()->rend()) {
1254*82d56013Sjoerg 
1255*82d56013Sjoerg     // TODO: Try to keep tracking of an entry value if we encounter a propagated
1256*82d56013Sjoerg     // DBG_VALUE describing the copy of the entry value. (Propagated entry value
1257*82d56013Sjoerg     // does not indicate the parameter modification.)
1258*82d56013Sjoerg     auto DestSrc = TII->isCopyInstr(*I);
1259*82d56013Sjoerg     if (!DestSrc)
1260*82d56013Sjoerg       return true;
1261*82d56013Sjoerg 
1262*82d56013Sjoerg     SrcRegOp = DestSrc->Source;
1263*82d56013Sjoerg     DestRegOp = DestSrc->Destination;
1264*82d56013Sjoerg     if (Reg != DestRegOp->getReg())
1265*82d56013Sjoerg       return true;
1266*82d56013Sjoerg 
1267*82d56013Sjoerg     for (uint64_t ID : OpenRanges.getEntryValueBackupVarLocs()) {
1268*82d56013Sjoerg       const VarLoc &VL = VarLocIDs[LocIndex::fromRawInteger(ID)];
1269*82d56013Sjoerg       if (VL.isEntryValueCopyBackupReg(Reg) &&
1270*82d56013Sjoerg           // Entry Values should not be variadic.
1271*82d56013Sjoerg           VL.MI.getDebugOperand(0).getReg() == SrcRegOp->getReg())
1272*82d56013Sjoerg         return false;
1273*82d56013Sjoerg     }
1274*82d56013Sjoerg   }
1275*82d56013Sjoerg 
1276*82d56013Sjoerg   return true;
1277*82d56013Sjoerg }
1278*82d56013Sjoerg 
1279*82d56013Sjoerg /// End all previous ranges related to @MI and start a new range from @MI
1280*82d56013Sjoerg /// if it is a DBG_VALUE instr.
transferDebugValue(const MachineInstr & MI,OpenRangesSet & OpenRanges,VarLocMap & VarLocIDs)1281*82d56013Sjoerg void VarLocBasedLDV::transferDebugValue(const MachineInstr &MI,
1282*82d56013Sjoerg                                          OpenRangesSet &OpenRanges,
1283*82d56013Sjoerg                                          VarLocMap &VarLocIDs) {
1284*82d56013Sjoerg   if (!MI.isDebugValue())
1285*82d56013Sjoerg     return;
1286*82d56013Sjoerg   const DILocalVariable *Var = MI.getDebugVariable();
1287*82d56013Sjoerg   const DIExpression *Expr = MI.getDebugExpression();
1288*82d56013Sjoerg   const DILocation *DebugLoc = MI.getDebugLoc();
1289*82d56013Sjoerg   const DILocation *InlinedAt = DebugLoc->getInlinedAt();
1290*82d56013Sjoerg   assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
1291*82d56013Sjoerg          "Expected inlined-at fields to agree");
1292*82d56013Sjoerg 
1293*82d56013Sjoerg   DebugVariable V(Var, Expr, InlinedAt);
1294*82d56013Sjoerg 
1295*82d56013Sjoerg   // Check if this DBG_VALUE indicates a parameter's value changing.
1296*82d56013Sjoerg   // If that is the case, we should stop tracking its entry value.
1297*82d56013Sjoerg   auto EntryValBackupID = OpenRanges.getEntryValueBackup(V);
1298*82d56013Sjoerg   if (Var->isParameter() && EntryValBackupID) {
1299*82d56013Sjoerg     const VarLoc &EntryVL = VarLocIDs[EntryValBackupID->back()];
1300*82d56013Sjoerg     if (removeEntryValue(MI, OpenRanges, VarLocIDs, EntryVL)) {
1301*82d56013Sjoerg       LLVM_DEBUG(dbgs() << "Deleting a DBG entry value because of: ";
1302*82d56013Sjoerg                  MI.print(dbgs(), /*IsStandalone*/ false,
1303*82d56013Sjoerg                           /*SkipOpers*/ false, /*SkipDebugLoc*/ false,
1304*82d56013Sjoerg                           /*AddNewLine*/ true, TII));
1305*82d56013Sjoerg       OpenRanges.erase(EntryVL);
1306*82d56013Sjoerg     }
1307*82d56013Sjoerg   }
1308*82d56013Sjoerg 
1309*82d56013Sjoerg   if (all_of(MI.debug_operands(), [](const MachineOperand &MO) {
1310*82d56013Sjoerg         return (MO.isReg() && MO.getReg()) || MO.isImm() || MO.isFPImm() ||
1311*82d56013Sjoerg                MO.isCImm();
1312*82d56013Sjoerg       })) {
1313*82d56013Sjoerg     // Use normal VarLoc constructor for registers and immediates.
1314*82d56013Sjoerg     VarLoc VL(MI, LS);
1315*82d56013Sjoerg     // End all previous ranges of VL.Var.
1316*82d56013Sjoerg     OpenRanges.erase(VL);
1317*82d56013Sjoerg 
1318*82d56013Sjoerg     LocIndices IDs = VarLocIDs.insert(VL);
1319*82d56013Sjoerg     // Add the VarLoc to OpenRanges from this DBG_VALUE.
1320*82d56013Sjoerg     OpenRanges.insert(IDs, VL);
1321*82d56013Sjoerg   } else if (MI.memoperands().size() > 0) {
1322*82d56013Sjoerg     llvm_unreachable("DBG_VALUE with mem operand encountered after regalloc?");
1323*82d56013Sjoerg   } else {
1324*82d56013Sjoerg     // This must be an undefined location. If it has an open range, erase it.
1325*82d56013Sjoerg     assert(MI.isUndefDebugValue() &&
1326*82d56013Sjoerg            "Unexpected non-undef DBG_VALUE encountered");
1327*82d56013Sjoerg     VarLoc VL(MI, LS);
1328*82d56013Sjoerg     OpenRanges.erase(VL);
1329*82d56013Sjoerg   }
1330*82d56013Sjoerg }
1331*82d56013Sjoerg 
1332*82d56013Sjoerg // This should be removed later, doesn't fit the new design.
collectAllVarLocs(SmallVectorImpl<VarLoc> & Collected,const VarLocSet & CollectFrom,const VarLocMap & VarLocIDs)1333*82d56013Sjoerg void VarLocBasedLDV::collectAllVarLocs(SmallVectorImpl<VarLoc> &Collected,
1334*82d56013Sjoerg                                        const VarLocSet &CollectFrom,
1335*82d56013Sjoerg                                        const VarLocMap &VarLocIDs) {
1336*82d56013Sjoerg   // The half-open interval [FirstIndexForReg, FirstInvalidIndex) contains all
1337*82d56013Sjoerg   // possible VarLoc IDs for VarLocs with MLs of kind RegisterKind which live
1338*82d56013Sjoerg   // in Reg.
1339*82d56013Sjoerg   uint64_t FirstIndex = LocIndex::rawIndexForReg(LocIndex::kUniversalLocation);
1340*82d56013Sjoerg   uint64_t FirstInvalidIndex =
1341*82d56013Sjoerg       LocIndex::rawIndexForReg(LocIndex::kUniversalLocation + 1);
1342*82d56013Sjoerg   // Iterate through that half-open interval and collect all the set IDs.
1343*82d56013Sjoerg   for (auto It = CollectFrom.find(FirstIndex), End = CollectFrom.end();
1344*82d56013Sjoerg        It != End && *It < FirstInvalidIndex; ++It) {
1345*82d56013Sjoerg     LocIndex RegIdx = LocIndex::fromRawInteger(*It);
1346*82d56013Sjoerg     Collected.push_back(VarLocIDs[RegIdx]);
1347*82d56013Sjoerg   }
1348*82d56013Sjoerg }
1349*82d56013Sjoerg 
1350*82d56013Sjoerg /// Turn the entry value backup locations into primary locations.
emitEntryValues(MachineInstr & MI,OpenRangesSet & OpenRanges,VarLocMap & VarLocIDs,TransferMap & Transfers,VarLocsInRange & KillSet)1351*82d56013Sjoerg void VarLocBasedLDV::emitEntryValues(MachineInstr &MI,
1352*82d56013Sjoerg                                      OpenRangesSet &OpenRanges,
1353*82d56013Sjoerg                                      VarLocMap &VarLocIDs,
1354*82d56013Sjoerg                                      TransferMap &Transfers,
1355*82d56013Sjoerg                                      VarLocsInRange &KillSet) {
1356*82d56013Sjoerg   // Do not insert entry value locations after a terminator.
1357*82d56013Sjoerg   if (MI.isTerminator())
1358*82d56013Sjoerg     return;
1359*82d56013Sjoerg 
1360*82d56013Sjoerg   for (uint32_t ID : KillSet) {
1361*82d56013Sjoerg     // The KillSet IDs are indices for the universal location bucket.
1362*82d56013Sjoerg     LocIndex Idx = LocIndex(LocIndex::kUniversalLocation, ID);
1363*82d56013Sjoerg     const VarLoc &VL = VarLocIDs[Idx];
1364*82d56013Sjoerg     if (!VL.Var.getVariable()->isParameter())
1365*82d56013Sjoerg       continue;
1366*82d56013Sjoerg 
1367*82d56013Sjoerg     auto DebugVar = VL.Var;
1368*82d56013Sjoerg     Optional<LocIndices> EntryValBackupIDs =
1369*82d56013Sjoerg         OpenRanges.getEntryValueBackup(DebugVar);
1370*82d56013Sjoerg 
1371*82d56013Sjoerg     // If the parameter has the entry value backup, it means we should
1372*82d56013Sjoerg     // be able to use its entry value.
1373*82d56013Sjoerg     if (!EntryValBackupIDs)
1374*82d56013Sjoerg       continue;
1375*82d56013Sjoerg 
1376*82d56013Sjoerg     const VarLoc &EntryVL = VarLocIDs[EntryValBackupIDs->back()];
1377*82d56013Sjoerg     VarLoc EntryLoc = VarLoc::CreateEntryLoc(EntryVL.MI, LS, EntryVL.Expr,
1378*82d56013Sjoerg                                              EntryVL.Locs[0].Value.RegNo);
1379*82d56013Sjoerg     LocIndices EntryValueIDs = VarLocIDs.insert(EntryLoc);
1380*82d56013Sjoerg     Transfers.push_back({&MI, EntryValueIDs.back()});
1381*82d56013Sjoerg     OpenRanges.insert(EntryValueIDs, EntryLoc);
1382*82d56013Sjoerg   }
1383*82d56013Sjoerg }
1384*82d56013Sjoerg 
1385*82d56013Sjoerg /// Create new TransferDebugPair and insert it in \p Transfers. The VarLoc
1386*82d56013Sjoerg /// with \p OldVarID should be deleted form \p OpenRanges and replaced with
1387*82d56013Sjoerg /// new VarLoc. If \p NewReg is different than default zero value then the
1388*82d56013Sjoerg /// new location will be register location created by the copy like instruction,
1389*82d56013Sjoerg /// otherwise it is variable's location on the stack.
insertTransferDebugPair(MachineInstr & MI,OpenRangesSet & OpenRanges,TransferMap & Transfers,VarLocMap & VarLocIDs,LocIndex OldVarID,TransferKind Kind,const VarLoc::MachineLoc & OldLoc,Register NewReg)1390*82d56013Sjoerg void VarLocBasedLDV::insertTransferDebugPair(
1391*82d56013Sjoerg     MachineInstr &MI, OpenRangesSet &OpenRanges, TransferMap &Transfers,
1392*82d56013Sjoerg     VarLocMap &VarLocIDs, LocIndex OldVarID, TransferKind Kind,
1393*82d56013Sjoerg     const VarLoc::MachineLoc &OldLoc, Register NewReg) {
1394*82d56013Sjoerg   const VarLoc &OldVarLoc = VarLocIDs[OldVarID];
1395*82d56013Sjoerg 
1396*82d56013Sjoerg   auto ProcessVarLoc = [&MI, &OpenRanges, &Transfers, &VarLocIDs](VarLoc &VL) {
1397*82d56013Sjoerg     LocIndices LocIds = VarLocIDs.insert(VL);
1398*82d56013Sjoerg 
1399*82d56013Sjoerg     // Close this variable's previous location range.
1400*82d56013Sjoerg     OpenRanges.erase(VL);
1401*82d56013Sjoerg 
1402*82d56013Sjoerg     // Record the new location as an open range, and a postponed transfer
1403*82d56013Sjoerg     // inserting a DBG_VALUE for this location.
1404*82d56013Sjoerg     OpenRanges.insert(LocIds, VL);
1405*82d56013Sjoerg     assert(!MI.isTerminator() && "Cannot insert DBG_VALUE after terminator");
1406*82d56013Sjoerg     TransferDebugPair MIP = {&MI, LocIds.back()};
1407*82d56013Sjoerg     Transfers.push_back(MIP);
1408*82d56013Sjoerg   };
1409*82d56013Sjoerg 
1410*82d56013Sjoerg   // End all previous ranges of VL.Var.
1411*82d56013Sjoerg   OpenRanges.erase(VarLocIDs[OldVarID]);
1412*82d56013Sjoerg   switch (Kind) {
1413*82d56013Sjoerg   case TransferKind::TransferCopy: {
1414*82d56013Sjoerg     assert(NewReg &&
1415*82d56013Sjoerg            "No register supplied when handling a copy of a debug value");
1416*82d56013Sjoerg     // Create a DBG_VALUE instruction to describe the Var in its new
1417*82d56013Sjoerg     // register location.
1418*82d56013Sjoerg     VarLoc VL = VarLoc::CreateCopyLoc(OldVarLoc, OldLoc, NewReg);
1419*82d56013Sjoerg     ProcessVarLoc(VL);
1420*82d56013Sjoerg     LLVM_DEBUG({
1421*82d56013Sjoerg       dbgs() << "Creating VarLoc for register copy:";
1422*82d56013Sjoerg       VL.dump(TRI);
1423*82d56013Sjoerg     });
1424*82d56013Sjoerg     return;
1425*82d56013Sjoerg   }
1426*82d56013Sjoerg   case TransferKind::TransferSpill: {
1427*82d56013Sjoerg     // Create a DBG_VALUE instruction to describe the Var in its spilled
1428*82d56013Sjoerg     // location.
1429*82d56013Sjoerg     VarLoc::SpillLoc SpillLocation = extractSpillBaseRegAndOffset(MI);
1430*82d56013Sjoerg     VarLoc VL = VarLoc::CreateSpillLoc(
1431*82d56013Sjoerg         OldVarLoc, OldLoc, SpillLocation.SpillBase, SpillLocation.SpillOffset);
1432*82d56013Sjoerg     ProcessVarLoc(VL);
1433*82d56013Sjoerg     LLVM_DEBUG({
1434*82d56013Sjoerg       dbgs() << "Creating VarLoc for spill:";
1435*82d56013Sjoerg       VL.dump(TRI);
1436*82d56013Sjoerg     });
1437*82d56013Sjoerg     return;
1438*82d56013Sjoerg   }
1439*82d56013Sjoerg   case TransferKind::TransferRestore: {
1440*82d56013Sjoerg     assert(NewReg &&
1441*82d56013Sjoerg            "No register supplied when handling a restore of a debug value");
1442*82d56013Sjoerg     // DebugInstr refers to the pre-spill location, therefore we can reuse
1443*82d56013Sjoerg     // its expression.
1444*82d56013Sjoerg     VarLoc VL = VarLoc::CreateCopyLoc(OldVarLoc, OldLoc, NewReg);
1445*82d56013Sjoerg     ProcessVarLoc(VL);
1446*82d56013Sjoerg     LLVM_DEBUG({
1447*82d56013Sjoerg       dbgs() << "Creating VarLoc for restore:";
1448*82d56013Sjoerg       VL.dump(TRI);
1449*82d56013Sjoerg     });
1450*82d56013Sjoerg     return;
1451*82d56013Sjoerg   }
1452*82d56013Sjoerg   }
1453*82d56013Sjoerg   llvm_unreachable("Invalid transfer kind");
1454*82d56013Sjoerg }
1455*82d56013Sjoerg 
1456*82d56013Sjoerg /// A definition of a register may mark the end of a range.
transferRegisterDef(MachineInstr & MI,OpenRangesSet & OpenRanges,VarLocMap & VarLocIDs,TransferMap & Transfers)1457*82d56013Sjoerg void VarLocBasedLDV::transferRegisterDef(
1458*82d56013Sjoerg     MachineInstr &MI, OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs,
1459*82d56013Sjoerg     TransferMap &Transfers) {
1460*82d56013Sjoerg 
1461*82d56013Sjoerg   // Meta Instructions do not affect the debug liveness of any register they
1462*82d56013Sjoerg   // define.
1463*82d56013Sjoerg   if (MI.isMetaInstruction())
1464*82d56013Sjoerg     return;
1465*82d56013Sjoerg 
1466*82d56013Sjoerg   MachineFunction *MF = MI.getMF();
1467*82d56013Sjoerg   const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1468*82d56013Sjoerg   Register SP = TLI->getStackPointerRegisterToSaveRestore();
1469*82d56013Sjoerg 
1470*82d56013Sjoerg   // Find the regs killed by MI, and find regmasks of preserved regs.
1471*82d56013Sjoerg   DefinedRegsSet DeadRegs;
1472*82d56013Sjoerg   SmallVector<const uint32_t *, 4> RegMasks;
1473*82d56013Sjoerg   for (const MachineOperand &MO : MI.operands()) {
1474*82d56013Sjoerg     // Determine whether the operand is a register def.
1475*82d56013Sjoerg     if (MO.isReg() && MO.isDef() && MO.getReg() &&
1476*82d56013Sjoerg         Register::isPhysicalRegister(MO.getReg()) &&
1477*82d56013Sjoerg         !(MI.isCall() && MO.getReg() == SP)) {
1478*82d56013Sjoerg       // Remove ranges of all aliased registers.
1479*82d56013Sjoerg       for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1480*82d56013Sjoerg         // FIXME: Can we break out of this loop early if no insertion occurs?
1481*82d56013Sjoerg         DeadRegs.insert(*RAI);
1482*82d56013Sjoerg     } else if (MO.isRegMask()) {
1483*82d56013Sjoerg       RegMasks.push_back(MO.getRegMask());
1484*82d56013Sjoerg     }
1485*82d56013Sjoerg   }
1486*82d56013Sjoerg 
1487*82d56013Sjoerg   // Erase VarLocs which reside in one of the dead registers. For performance
1488*82d56013Sjoerg   // reasons, it's critical to not iterate over the full set of open VarLocs.
1489*82d56013Sjoerg   // Iterate over the set of dying/used regs instead.
1490*82d56013Sjoerg   if (!RegMasks.empty()) {
1491*82d56013Sjoerg     SmallVector<Register, 32> UsedRegs;
1492*82d56013Sjoerg     getUsedRegs(OpenRanges.getVarLocs(), UsedRegs);
1493*82d56013Sjoerg     for (Register Reg : UsedRegs) {
1494*82d56013Sjoerg       // Remove ranges of all clobbered registers. Register masks don't usually
1495*82d56013Sjoerg       // list SP as preserved. Assume that call instructions never clobber SP,
1496*82d56013Sjoerg       // because some backends (e.g., AArch64) never list SP in the regmask.
1497*82d56013Sjoerg       // While the debug info may be off for an instruction or two around
1498*82d56013Sjoerg       // callee-cleanup calls, transferring the DEBUG_VALUE across the call is
1499*82d56013Sjoerg       // still a better user experience.
1500*82d56013Sjoerg       if (Reg == SP)
1501*82d56013Sjoerg         continue;
1502*82d56013Sjoerg       bool AnyRegMaskKillsReg =
1503*82d56013Sjoerg           any_of(RegMasks, [Reg](const uint32_t *RegMask) {
1504*82d56013Sjoerg             return MachineOperand::clobbersPhysReg(RegMask, Reg);
1505*82d56013Sjoerg           });
1506*82d56013Sjoerg       if (AnyRegMaskKillsReg)
1507*82d56013Sjoerg         DeadRegs.insert(Reg);
1508*82d56013Sjoerg     }
1509*82d56013Sjoerg   }
1510*82d56013Sjoerg 
1511*82d56013Sjoerg   if (DeadRegs.empty())
1512*82d56013Sjoerg     return;
1513*82d56013Sjoerg 
1514*82d56013Sjoerg   VarLocsInRange KillSet;
1515*82d56013Sjoerg   collectIDsForRegs(KillSet, DeadRegs, OpenRanges.getVarLocs(), VarLocIDs);
1516*82d56013Sjoerg   OpenRanges.erase(KillSet, VarLocIDs, LocIndex::kUniversalLocation);
1517*82d56013Sjoerg 
1518*82d56013Sjoerg   if (TPC) {
1519*82d56013Sjoerg     auto &TM = TPC->getTM<TargetMachine>();
1520*82d56013Sjoerg     if (TM.Options.ShouldEmitDebugEntryValues())
1521*82d56013Sjoerg       emitEntryValues(MI, OpenRanges, VarLocIDs, Transfers, KillSet);
1522*82d56013Sjoerg   }
1523*82d56013Sjoerg }
1524*82d56013Sjoerg 
isSpillInstruction(const MachineInstr & MI,MachineFunction * MF)1525*82d56013Sjoerg bool VarLocBasedLDV::isSpillInstruction(const MachineInstr &MI,
1526*82d56013Sjoerg                                          MachineFunction *MF) {
1527*82d56013Sjoerg   // TODO: Handle multiple stores folded into one.
1528*82d56013Sjoerg   if (!MI.hasOneMemOperand())
1529*82d56013Sjoerg     return false;
1530*82d56013Sjoerg 
1531*82d56013Sjoerg   if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
1532*82d56013Sjoerg     return false; // This is not a spill instruction, since no valid size was
1533*82d56013Sjoerg                   // returned from either function.
1534*82d56013Sjoerg 
1535*82d56013Sjoerg   return true;
1536*82d56013Sjoerg }
1537*82d56013Sjoerg 
isLocationSpill(const MachineInstr & MI,MachineFunction * MF,Register & Reg)1538*82d56013Sjoerg bool VarLocBasedLDV::isLocationSpill(const MachineInstr &MI,
1539*82d56013Sjoerg                                       MachineFunction *MF, Register &Reg) {
1540*82d56013Sjoerg   if (!isSpillInstruction(MI, MF))
1541*82d56013Sjoerg     return false;
1542*82d56013Sjoerg 
1543*82d56013Sjoerg   auto isKilledReg = [&](const MachineOperand MO, Register &Reg) {
1544*82d56013Sjoerg     if (!MO.isReg() || !MO.isUse()) {
1545*82d56013Sjoerg       Reg = 0;
1546*82d56013Sjoerg       return false;
1547*82d56013Sjoerg     }
1548*82d56013Sjoerg     Reg = MO.getReg();
1549*82d56013Sjoerg     return MO.isKill();
1550*82d56013Sjoerg   };
1551*82d56013Sjoerg 
1552*82d56013Sjoerg   for (const MachineOperand &MO : MI.operands()) {
1553*82d56013Sjoerg     // In a spill instruction generated by the InlineSpiller the spilled
1554*82d56013Sjoerg     // register has its kill flag set.
1555*82d56013Sjoerg     if (isKilledReg(MO, Reg))
1556*82d56013Sjoerg       return true;
1557*82d56013Sjoerg     if (Reg != 0) {
1558*82d56013Sjoerg       // Check whether next instruction kills the spilled register.
1559*82d56013Sjoerg       // FIXME: Current solution does not cover search for killed register in
1560*82d56013Sjoerg       // bundles and instructions further down the chain.
1561*82d56013Sjoerg       auto NextI = std::next(MI.getIterator());
1562*82d56013Sjoerg       // Skip next instruction that points to basic block end iterator.
1563*82d56013Sjoerg       if (MI.getParent()->end() == NextI)
1564*82d56013Sjoerg         continue;
1565*82d56013Sjoerg       Register RegNext;
1566*82d56013Sjoerg       for (const MachineOperand &MONext : NextI->operands()) {
1567*82d56013Sjoerg         // Return true if we came across the register from the
1568*82d56013Sjoerg         // previous spill instruction that is killed in NextI.
1569*82d56013Sjoerg         if (isKilledReg(MONext, RegNext) && RegNext == Reg)
1570*82d56013Sjoerg           return true;
1571*82d56013Sjoerg       }
1572*82d56013Sjoerg     }
1573*82d56013Sjoerg   }
1574*82d56013Sjoerg   // Return false if we didn't find spilled register.
1575*82d56013Sjoerg   return false;
1576*82d56013Sjoerg }
1577*82d56013Sjoerg 
1578*82d56013Sjoerg Optional<VarLocBasedLDV::VarLoc::SpillLoc>
isRestoreInstruction(const MachineInstr & MI,MachineFunction * MF,Register & Reg)1579*82d56013Sjoerg VarLocBasedLDV::isRestoreInstruction(const MachineInstr &MI,
1580*82d56013Sjoerg                                       MachineFunction *MF, Register &Reg) {
1581*82d56013Sjoerg   if (!MI.hasOneMemOperand())
1582*82d56013Sjoerg     return None;
1583*82d56013Sjoerg 
1584*82d56013Sjoerg   // FIXME: Handle folded restore instructions with more than one memory
1585*82d56013Sjoerg   // operand.
1586*82d56013Sjoerg   if (MI.getRestoreSize(TII)) {
1587*82d56013Sjoerg     Reg = MI.getOperand(0).getReg();
1588*82d56013Sjoerg     return extractSpillBaseRegAndOffset(MI);
1589*82d56013Sjoerg   }
1590*82d56013Sjoerg   return None;
1591*82d56013Sjoerg }
1592*82d56013Sjoerg 
1593*82d56013Sjoerg /// A spilled register may indicate that we have to end the current range of
1594*82d56013Sjoerg /// a variable and create a new one for the spill location.
1595*82d56013Sjoerg /// A restored register may indicate the reverse situation.
1596*82d56013Sjoerg /// We don't want to insert any instructions in process(), so we just create
1597*82d56013Sjoerg /// the DBG_VALUE without inserting it and keep track of it in \p Transfers.
1598*82d56013Sjoerg /// It will be inserted into the BB when we're done iterating over the
1599*82d56013Sjoerg /// instructions.
transferSpillOrRestoreInst(MachineInstr & MI,OpenRangesSet & OpenRanges,VarLocMap & VarLocIDs,TransferMap & Transfers)1600*82d56013Sjoerg void VarLocBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI,
1601*82d56013Sjoerg                                                  OpenRangesSet &OpenRanges,
1602*82d56013Sjoerg                                                  VarLocMap &VarLocIDs,
1603*82d56013Sjoerg                                                  TransferMap &Transfers) {
1604*82d56013Sjoerg   MachineFunction *MF = MI.getMF();
1605*82d56013Sjoerg   TransferKind TKind;
1606*82d56013Sjoerg   Register Reg;
1607*82d56013Sjoerg   Optional<VarLoc::SpillLoc> Loc;
1608*82d56013Sjoerg 
1609*82d56013Sjoerg   LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
1610*82d56013Sjoerg 
1611*82d56013Sjoerg   // First, if there are any DBG_VALUEs pointing at a spill slot that is
1612*82d56013Sjoerg   // written to, then close the variable location. The value in memory
1613*82d56013Sjoerg   // will have changed.
1614*82d56013Sjoerg   VarLocsInRange KillSet;
1615*82d56013Sjoerg   if (isSpillInstruction(MI, MF)) {
1616*82d56013Sjoerg     Loc = extractSpillBaseRegAndOffset(MI);
1617*82d56013Sjoerg     for (uint64_t ID : OpenRanges.getSpillVarLocs()) {
1618*82d56013Sjoerg       LocIndex Idx = LocIndex::fromRawInteger(ID);
1619*82d56013Sjoerg       const VarLoc &VL = VarLocIDs[Idx];
1620*82d56013Sjoerg       assert(VL.containsSpillLocs() && "Broken VarLocSet?");
1621*82d56013Sjoerg       if (VL.usesSpillLoc(*Loc)) {
1622*82d56013Sjoerg         // This location is overwritten by the current instruction -- terminate
1623*82d56013Sjoerg         // the open range, and insert an explicit DBG_VALUE $noreg.
1624*82d56013Sjoerg         //
1625*82d56013Sjoerg         // Doing this at a later stage would require re-interpreting all
1626*82d56013Sjoerg         // DBG_VALUes and DIExpressions to identify whether they point at
1627*82d56013Sjoerg         // memory, and then analysing all memory writes to see if they
1628*82d56013Sjoerg         // overwrite that memory, which is expensive.
1629*82d56013Sjoerg         //
1630*82d56013Sjoerg         // At this stage, we already know which DBG_VALUEs are for spills and
1631*82d56013Sjoerg         // where they are located; it's best to fix handle overwrites now.
1632*82d56013Sjoerg         KillSet.insert(ID);
1633*82d56013Sjoerg         unsigned SpillLocIdx = VL.getSpillLocIdx(*Loc);
1634*82d56013Sjoerg         VarLoc::MachineLoc OldLoc = VL.Locs[SpillLocIdx];
1635*82d56013Sjoerg         VarLoc UndefVL = VarLoc::CreateCopyLoc(VL, OldLoc, 0);
1636*82d56013Sjoerg         LocIndices UndefLocIDs = VarLocIDs.insert(UndefVL);
1637*82d56013Sjoerg         Transfers.push_back({&MI, UndefLocIDs.back()});
1638*82d56013Sjoerg       }
1639*82d56013Sjoerg     }
1640*82d56013Sjoerg     OpenRanges.erase(KillSet, VarLocIDs, LocIndex::kSpillLocation);
1641*82d56013Sjoerg   }
1642*82d56013Sjoerg 
1643*82d56013Sjoerg   // Try to recognise spill and restore instructions that may create a new
1644*82d56013Sjoerg   // variable location.
1645*82d56013Sjoerg   if (isLocationSpill(MI, MF, Reg)) {
1646*82d56013Sjoerg     TKind = TransferKind::TransferSpill;
1647*82d56013Sjoerg     LLVM_DEBUG(dbgs() << "Recognized as spill: "; MI.dump(););
1648*82d56013Sjoerg     LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
1649*82d56013Sjoerg                       << "\n");
1650*82d56013Sjoerg   } else {
1651*82d56013Sjoerg     if (!(Loc = isRestoreInstruction(MI, MF, Reg)))
1652*82d56013Sjoerg       return;
1653*82d56013Sjoerg     TKind = TransferKind::TransferRestore;
1654*82d56013Sjoerg     LLVM_DEBUG(dbgs() << "Recognized as restore: "; MI.dump(););
1655*82d56013Sjoerg     LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
1656*82d56013Sjoerg                       << "\n");
1657*82d56013Sjoerg   }
1658*82d56013Sjoerg   // Check if the register or spill location is the location of a debug value.
1659*82d56013Sjoerg   auto TransferCandidates = OpenRanges.getEmptyVarLocRange();
1660*82d56013Sjoerg   if (TKind == TransferKind::TransferSpill)
1661*82d56013Sjoerg     TransferCandidates = OpenRanges.getRegisterVarLocs(Reg);
1662*82d56013Sjoerg   else if (TKind == TransferKind::TransferRestore)
1663*82d56013Sjoerg     TransferCandidates = OpenRanges.getSpillVarLocs();
1664*82d56013Sjoerg   for (uint64_t ID : TransferCandidates) {
1665*82d56013Sjoerg     LocIndex Idx = LocIndex::fromRawInteger(ID);
1666*82d56013Sjoerg     const VarLoc &VL = VarLocIDs[Idx];
1667*82d56013Sjoerg     unsigned LocIdx;
1668*82d56013Sjoerg     if (TKind == TransferKind::TransferSpill) {
1669*82d56013Sjoerg       assert(VL.usesReg(Reg) && "Broken VarLocSet?");
1670*82d56013Sjoerg       LLVM_DEBUG(dbgs() << "Spilling Register " << printReg(Reg, TRI) << '('
1671*82d56013Sjoerg                         << VL.Var.getVariable()->getName() << ")\n");
1672*82d56013Sjoerg       LocIdx = VL.getRegIdx(Reg);
1673*82d56013Sjoerg     } else {
1674*82d56013Sjoerg       assert(TKind == TransferKind::TransferRestore && VL.containsSpillLocs() &&
1675*82d56013Sjoerg              "Broken VarLocSet?");
1676*82d56013Sjoerg       if (!VL.usesSpillLoc(*Loc))
1677*82d56013Sjoerg         // The spill location is not the location of a debug value.
1678*82d56013Sjoerg         continue;
1679*82d56013Sjoerg       LLVM_DEBUG(dbgs() << "Restoring Register " << printReg(Reg, TRI) << '('
1680*82d56013Sjoerg                         << VL.Var.getVariable()->getName() << ")\n");
1681*82d56013Sjoerg       LocIdx = VL.getSpillLocIdx(*Loc);
1682*82d56013Sjoerg     }
1683*82d56013Sjoerg     VarLoc::MachineLoc MLoc = VL.Locs[LocIdx];
1684*82d56013Sjoerg     insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, Idx, TKind,
1685*82d56013Sjoerg                             MLoc, Reg);
1686*82d56013Sjoerg     // FIXME: A comment should explain why it's correct to return early here,
1687*82d56013Sjoerg     // if that is in fact correct.
1688*82d56013Sjoerg     return;
1689*82d56013Sjoerg   }
1690*82d56013Sjoerg }
1691*82d56013Sjoerg 
1692*82d56013Sjoerg /// If \p MI is a register copy instruction, that copies a previously tracked
1693*82d56013Sjoerg /// value from one register to another register that is callee saved, we
1694*82d56013Sjoerg /// create new DBG_VALUE instruction  described with copy destination register.
transferRegisterCopy(MachineInstr & MI,OpenRangesSet & OpenRanges,VarLocMap & VarLocIDs,TransferMap & Transfers)1695*82d56013Sjoerg void VarLocBasedLDV::transferRegisterCopy(MachineInstr &MI,
1696*82d56013Sjoerg                                            OpenRangesSet &OpenRanges,
1697*82d56013Sjoerg                                            VarLocMap &VarLocIDs,
1698*82d56013Sjoerg                                            TransferMap &Transfers) {
1699*82d56013Sjoerg   auto DestSrc = TII->isCopyInstr(MI);
1700*82d56013Sjoerg   if (!DestSrc)
1701*82d56013Sjoerg     return;
1702*82d56013Sjoerg 
1703*82d56013Sjoerg   const MachineOperand *DestRegOp = DestSrc->Destination;
1704*82d56013Sjoerg   const MachineOperand *SrcRegOp = DestSrc->Source;
1705*82d56013Sjoerg 
1706*82d56013Sjoerg   if (!DestRegOp->isDef())
1707*82d56013Sjoerg     return;
1708*82d56013Sjoerg 
1709*82d56013Sjoerg   auto isCalleeSavedReg = [&](Register Reg) {
1710*82d56013Sjoerg     for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1711*82d56013Sjoerg       if (CalleeSavedRegs.test(*RAI))
1712*82d56013Sjoerg         return true;
1713*82d56013Sjoerg     return false;
1714*82d56013Sjoerg   };
1715*82d56013Sjoerg 
1716*82d56013Sjoerg   Register SrcReg = SrcRegOp->getReg();
1717*82d56013Sjoerg   Register DestReg = DestRegOp->getReg();
1718*82d56013Sjoerg 
1719*82d56013Sjoerg   // We want to recognize instructions where destination register is callee
1720*82d56013Sjoerg   // saved register. If register that could be clobbered by the call is
1721*82d56013Sjoerg   // included, there would be a great chance that it is going to be clobbered
1722*82d56013Sjoerg   // soon. It is more likely that previous register location, which is callee
1723*82d56013Sjoerg   // saved, is going to stay unclobbered longer, even if it is killed.
1724*82d56013Sjoerg   if (!isCalleeSavedReg(DestReg))
1725*82d56013Sjoerg     return;
1726*82d56013Sjoerg 
1727*82d56013Sjoerg   // Remember an entry value movement. If we encounter a new debug value of
1728*82d56013Sjoerg   // a parameter describing only a moving of the value around, rather then
1729*82d56013Sjoerg   // modifying it, we are still able to use the entry value if needed.
1730*82d56013Sjoerg   if (isRegOtherThanSPAndFP(*DestRegOp, MI, TRI)) {
1731*82d56013Sjoerg     for (uint64_t ID : OpenRanges.getEntryValueBackupVarLocs()) {
1732*82d56013Sjoerg       LocIndex Idx = LocIndex::fromRawInteger(ID);
1733*82d56013Sjoerg       const VarLoc &VL = VarLocIDs[Idx];
1734*82d56013Sjoerg       if (VL.isEntryValueBackupReg(SrcReg)) {
1735*82d56013Sjoerg         LLVM_DEBUG(dbgs() << "Copy of the entry value: "; MI.dump(););
1736*82d56013Sjoerg         VarLoc EntryValLocCopyBackup =
1737*82d56013Sjoerg             VarLoc::CreateEntryCopyBackupLoc(VL.MI, LS, VL.Expr, DestReg);
1738*82d56013Sjoerg         // Stop tracking the original entry value.
1739*82d56013Sjoerg         OpenRanges.erase(VL);
1740*82d56013Sjoerg 
1741*82d56013Sjoerg         // Start tracking the entry value copy.
1742*82d56013Sjoerg         LocIndices EntryValCopyLocIDs = VarLocIDs.insert(EntryValLocCopyBackup);
1743*82d56013Sjoerg         OpenRanges.insert(EntryValCopyLocIDs, EntryValLocCopyBackup);
1744*82d56013Sjoerg         break;
1745*82d56013Sjoerg       }
1746*82d56013Sjoerg     }
1747*82d56013Sjoerg   }
1748*82d56013Sjoerg 
1749*82d56013Sjoerg   if (!SrcRegOp->isKill())
1750*82d56013Sjoerg     return;
1751*82d56013Sjoerg 
1752*82d56013Sjoerg   for (uint64_t ID : OpenRanges.getRegisterVarLocs(SrcReg)) {
1753*82d56013Sjoerg     LocIndex Idx = LocIndex::fromRawInteger(ID);
1754*82d56013Sjoerg     assert(VarLocIDs[Idx].usesReg(SrcReg) && "Broken VarLocSet?");
1755*82d56013Sjoerg     VarLoc::MachineLocValue Loc;
1756*82d56013Sjoerg     Loc.RegNo = SrcReg;
1757*82d56013Sjoerg     VarLoc::MachineLoc MLoc{VarLoc::MachineLocKind::RegisterKind, Loc};
1758*82d56013Sjoerg     insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, Idx,
1759*82d56013Sjoerg                             TransferKind::TransferCopy, MLoc, DestReg);
1760*82d56013Sjoerg     // FIXME: A comment should explain why it's correct to return early here,
1761*82d56013Sjoerg     // if that is in fact correct.
1762*82d56013Sjoerg     return;
1763*82d56013Sjoerg   }
1764*82d56013Sjoerg }
1765*82d56013Sjoerg 
1766*82d56013Sjoerg /// Terminate all open ranges at the end of the current basic block.
transferTerminator(MachineBasicBlock * CurMBB,OpenRangesSet & OpenRanges,VarLocInMBB & OutLocs,const VarLocMap & VarLocIDs)1767*82d56013Sjoerg bool VarLocBasedLDV::transferTerminator(MachineBasicBlock *CurMBB,
1768*82d56013Sjoerg                                          OpenRangesSet &OpenRanges,
1769*82d56013Sjoerg                                          VarLocInMBB &OutLocs,
1770*82d56013Sjoerg                                          const VarLocMap &VarLocIDs) {
1771*82d56013Sjoerg   bool Changed = false;
1772*82d56013Sjoerg   LLVM_DEBUG({
1773*82d56013Sjoerg     VarVec VarLocs;
1774*82d56013Sjoerg     OpenRanges.getUniqueVarLocs(VarLocs, VarLocIDs);
1775*82d56013Sjoerg     for (VarLoc &VL : VarLocs) {
1776*82d56013Sjoerg       // Copy OpenRanges to OutLocs, if not already present.
1777*82d56013Sjoerg       dbgs() << "Add to OutLocs in MBB #" << CurMBB->getNumber() << ":  ";
1778*82d56013Sjoerg       VL.dump(TRI);
1779*82d56013Sjoerg     }
1780*82d56013Sjoerg   });
1781*82d56013Sjoerg   VarLocSet &VLS = getVarLocsInMBB(CurMBB, OutLocs);
1782*82d56013Sjoerg   Changed = VLS != OpenRanges.getVarLocs();
1783*82d56013Sjoerg   // New OutLocs set may be different due to spill, restore or register
1784*82d56013Sjoerg   // copy instruction processing.
1785*82d56013Sjoerg   if (Changed)
1786*82d56013Sjoerg     VLS = OpenRanges.getVarLocs();
1787*82d56013Sjoerg   OpenRanges.clear();
1788*82d56013Sjoerg   return Changed;
1789*82d56013Sjoerg }
1790*82d56013Sjoerg 
1791*82d56013Sjoerg /// Accumulate a mapping between each DILocalVariable fragment and other
1792*82d56013Sjoerg /// fragments of that DILocalVariable which overlap. This reduces work during
1793*82d56013Sjoerg /// the data-flow stage from "Find any overlapping fragments" to "Check if the
1794*82d56013Sjoerg /// known-to-overlap fragments are present".
1795*82d56013Sjoerg /// \param MI A previously unprocessed DEBUG_VALUE instruction to analyze for
1796*82d56013Sjoerg ///           fragment usage.
1797*82d56013Sjoerg /// \param SeenFragments Map from DILocalVariable to all fragments of that
1798*82d56013Sjoerg ///           Variable which are known to exist.
1799*82d56013Sjoerg /// \param OverlappingFragments The overlap map being constructed, from one
1800*82d56013Sjoerg ///           Var/Fragment pair to a vector of fragments known to overlap.
accumulateFragmentMap(MachineInstr & MI,VarToFragments & SeenFragments,OverlapMap & OverlappingFragments)1801*82d56013Sjoerg void VarLocBasedLDV::accumulateFragmentMap(MachineInstr &MI,
1802*82d56013Sjoerg                                             VarToFragments &SeenFragments,
1803*82d56013Sjoerg                                             OverlapMap &OverlappingFragments) {
1804*82d56013Sjoerg   DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(),
1805*82d56013Sjoerg                       MI.getDebugLoc()->getInlinedAt());
1806*82d56013Sjoerg   FragmentInfo ThisFragment = MIVar.getFragmentOrDefault();
1807*82d56013Sjoerg 
1808*82d56013Sjoerg   // If this is the first sighting of this variable, then we are guaranteed
1809*82d56013Sjoerg   // there are currently no overlapping fragments either. Initialize the set
1810*82d56013Sjoerg   // of seen fragments, record no overlaps for the current one, and return.
1811*82d56013Sjoerg   auto SeenIt = SeenFragments.find(MIVar.getVariable());
1812*82d56013Sjoerg   if (SeenIt == SeenFragments.end()) {
1813*82d56013Sjoerg     SmallSet<FragmentInfo, 4> OneFragment;
1814*82d56013Sjoerg     OneFragment.insert(ThisFragment);
1815*82d56013Sjoerg     SeenFragments.insert({MIVar.getVariable(), OneFragment});
1816*82d56013Sjoerg 
1817*82d56013Sjoerg     OverlappingFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
1818*82d56013Sjoerg     return;
1819*82d56013Sjoerg   }
1820*82d56013Sjoerg 
1821*82d56013Sjoerg   // If this particular Variable/Fragment pair already exists in the overlap
1822*82d56013Sjoerg   // map, it has already been accounted for.
1823*82d56013Sjoerg   auto IsInOLapMap =
1824*82d56013Sjoerg       OverlappingFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
1825*82d56013Sjoerg   if (!IsInOLapMap.second)
1826*82d56013Sjoerg     return;
1827*82d56013Sjoerg 
1828*82d56013Sjoerg   auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
1829*82d56013Sjoerg   auto &AllSeenFragments = SeenIt->second;
1830*82d56013Sjoerg 
1831*82d56013Sjoerg   // Otherwise, examine all other seen fragments for this variable, with "this"
1832*82d56013Sjoerg   // fragment being a previously unseen fragment. Record any pair of
1833*82d56013Sjoerg   // overlapping fragments.
1834*82d56013Sjoerg   for (auto &ASeenFragment : AllSeenFragments) {
1835*82d56013Sjoerg     // Does this previously seen fragment overlap?
1836*82d56013Sjoerg     if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
1837*82d56013Sjoerg       // Yes: Mark the current fragment as being overlapped.
1838*82d56013Sjoerg       ThisFragmentsOverlaps.push_back(ASeenFragment);
1839*82d56013Sjoerg       // Mark the previously seen fragment as being overlapped by the current
1840*82d56013Sjoerg       // one.
1841*82d56013Sjoerg       auto ASeenFragmentsOverlaps =
1842*82d56013Sjoerg           OverlappingFragments.find({MIVar.getVariable(), ASeenFragment});
1843*82d56013Sjoerg       assert(ASeenFragmentsOverlaps != OverlappingFragments.end() &&
1844*82d56013Sjoerg              "Previously seen var fragment has no vector of overlaps");
1845*82d56013Sjoerg       ASeenFragmentsOverlaps->second.push_back(ThisFragment);
1846*82d56013Sjoerg     }
1847*82d56013Sjoerg   }
1848*82d56013Sjoerg 
1849*82d56013Sjoerg   AllSeenFragments.insert(ThisFragment);
1850*82d56013Sjoerg }
1851*82d56013Sjoerg 
1852*82d56013Sjoerg /// This routine creates OpenRanges.
process(MachineInstr & MI,OpenRangesSet & OpenRanges,VarLocMap & VarLocIDs,TransferMap & Transfers)1853*82d56013Sjoerg void VarLocBasedLDV::process(MachineInstr &MI, OpenRangesSet &OpenRanges,
1854*82d56013Sjoerg                               VarLocMap &VarLocIDs, TransferMap &Transfers) {
1855*82d56013Sjoerg   transferDebugValue(MI, OpenRanges, VarLocIDs);
1856*82d56013Sjoerg   transferRegisterDef(MI, OpenRanges, VarLocIDs, Transfers);
1857*82d56013Sjoerg   transferRegisterCopy(MI, OpenRanges, VarLocIDs, Transfers);
1858*82d56013Sjoerg   transferSpillOrRestoreInst(MI, OpenRanges, VarLocIDs, Transfers);
1859*82d56013Sjoerg }
1860*82d56013Sjoerg 
1861*82d56013Sjoerg /// This routine joins the analysis results of all incoming edges in @MBB by
1862*82d56013Sjoerg /// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
1863*82d56013Sjoerg /// source variable in all the predecessors of @MBB reside in the same location.
join(MachineBasicBlock & MBB,VarLocInMBB & OutLocs,VarLocInMBB & InLocs,const VarLocMap & VarLocIDs,SmallPtrSet<const MachineBasicBlock *,16> & Visited,SmallPtrSetImpl<const MachineBasicBlock * > & ArtificialBlocks)1864*82d56013Sjoerg bool VarLocBasedLDV::join(
1865*82d56013Sjoerg     MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
1866*82d56013Sjoerg     const VarLocMap &VarLocIDs,
1867*82d56013Sjoerg     SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
1868*82d56013Sjoerg     SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks) {
1869*82d56013Sjoerg   LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
1870*82d56013Sjoerg 
1871*82d56013Sjoerg   VarLocSet InLocsT(Alloc); // Temporary incoming locations.
1872*82d56013Sjoerg 
1873*82d56013Sjoerg   // For all predecessors of this MBB, find the set of VarLocs that
1874*82d56013Sjoerg   // can be joined.
1875*82d56013Sjoerg   int NumVisited = 0;
1876*82d56013Sjoerg   for (auto p : MBB.predecessors()) {
1877*82d56013Sjoerg     // Ignore backedges if we have not visited the predecessor yet. As the
1878*82d56013Sjoerg     // predecessor hasn't yet had locations propagated into it, most locations
1879*82d56013Sjoerg     // will not yet be valid, so treat them as all being uninitialized and
1880*82d56013Sjoerg     // potentially valid. If a location guessed to be correct here is
1881*82d56013Sjoerg     // invalidated later, we will remove it when we revisit this block.
1882*82d56013Sjoerg     if (!Visited.count(p)) {
1883*82d56013Sjoerg       LLVM_DEBUG(dbgs() << "  ignoring unvisited pred MBB: " << p->getNumber()
1884*82d56013Sjoerg                         << "\n");
1885*82d56013Sjoerg       continue;
1886*82d56013Sjoerg     }
1887*82d56013Sjoerg     auto OL = OutLocs.find(p);
1888*82d56013Sjoerg     // Join is null in case of empty OutLocs from any of the pred.
1889*82d56013Sjoerg     if (OL == OutLocs.end())
1890*82d56013Sjoerg       return false;
1891*82d56013Sjoerg 
1892*82d56013Sjoerg     // Just copy over the Out locs to incoming locs for the first visited
1893*82d56013Sjoerg     // predecessor, and for all other predecessors join the Out locs.
1894*82d56013Sjoerg     VarLocSet &OutLocVLS = *OL->second.get();
1895*82d56013Sjoerg     if (!NumVisited)
1896*82d56013Sjoerg       InLocsT = OutLocVLS;
1897*82d56013Sjoerg     else
1898*82d56013Sjoerg       InLocsT &= OutLocVLS;
1899*82d56013Sjoerg 
1900*82d56013Sjoerg     LLVM_DEBUG({
1901*82d56013Sjoerg       if (!InLocsT.empty()) {
1902*82d56013Sjoerg         VarVec VarLocs;
1903*82d56013Sjoerg         collectAllVarLocs(VarLocs, InLocsT, VarLocIDs);
1904*82d56013Sjoerg         for (const VarLoc &VL : VarLocs)
1905*82d56013Sjoerg           dbgs() << "  gathered candidate incoming var: "
1906*82d56013Sjoerg                  << VL.Var.getVariable()->getName() << "\n";
1907*82d56013Sjoerg       }
1908*82d56013Sjoerg     });
1909*82d56013Sjoerg 
1910*82d56013Sjoerg     NumVisited++;
1911*82d56013Sjoerg   }
1912*82d56013Sjoerg 
1913*82d56013Sjoerg   // Filter out DBG_VALUES that are out of scope.
1914*82d56013Sjoerg   VarLocSet KillSet(Alloc);
1915*82d56013Sjoerg   bool IsArtificial = ArtificialBlocks.count(&MBB);
1916*82d56013Sjoerg   if (!IsArtificial) {
1917*82d56013Sjoerg     for (uint64_t ID : InLocsT) {
1918*82d56013Sjoerg       LocIndex Idx = LocIndex::fromRawInteger(ID);
1919*82d56013Sjoerg       if (!VarLocIDs[Idx].dominates(LS, MBB)) {
1920*82d56013Sjoerg         KillSet.set(ID);
1921*82d56013Sjoerg         LLVM_DEBUG({
1922*82d56013Sjoerg           auto Name = VarLocIDs[Idx].Var.getVariable()->getName();
1923*82d56013Sjoerg           dbgs() << "  killing " << Name << ", it doesn't dominate MBB\n";
1924*82d56013Sjoerg         });
1925*82d56013Sjoerg       }
1926*82d56013Sjoerg     }
1927*82d56013Sjoerg   }
1928*82d56013Sjoerg   InLocsT.intersectWithComplement(KillSet);
1929*82d56013Sjoerg 
1930*82d56013Sjoerg   // As we are processing blocks in reverse post-order we
1931*82d56013Sjoerg   // should have processed at least one predecessor, unless it
1932*82d56013Sjoerg   // is the entry block which has no predecessor.
1933*82d56013Sjoerg   assert((NumVisited || MBB.pred_empty()) &&
1934*82d56013Sjoerg          "Should have processed at least one predecessor");
1935*82d56013Sjoerg 
1936*82d56013Sjoerg   VarLocSet &ILS = getVarLocsInMBB(&MBB, InLocs);
1937*82d56013Sjoerg   bool Changed = false;
1938*82d56013Sjoerg   if (ILS != InLocsT) {
1939*82d56013Sjoerg     ILS = InLocsT;
1940*82d56013Sjoerg     Changed = true;
1941*82d56013Sjoerg   }
1942*82d56013Sjoerg 
1943*82d56013Sjoerg   return Changed;
1944*82d56013Sjoerg }
1945*82d56013Sjoerg 
flushPendingLocs(VarLocInMBB & PendingInLocs,VarLocMap & VarLocIDs)1946*82d56013Sjoerg void VarLocBasedLDV::flushPendingLocs(VarLocInMBB &PendingInLocs,
1947*82d56013Sjoerg                                        VarLocMap &VarLocIDs) {
1948*82d56013Sjoerg   // PendingInLocs records all locations propagated into blocks, which have
1949*82d56013Sjoerg   // not had DBG_VALUE insts created. Go through and create those insts now.
1950*82d56013Sjoerg   for (auto &Iter : PendingInLocs) {
1951*82d56013Sjoerg     // Map is keyed on a constant pointer, unwrap it so we can insert insts.
1952*82d56013Sjoerg     auto &MBB = const_cast<MachineBasicBlock &>(*Iter.first);
1953*82d56013Sjoerg     VarLocSet &Pending = *Iter.second.get();
1954*82d56013Sjoerg 
1955*82d56013Sjoerg     SmallVector<VarLoc, 32> VarLocs;
1956*82d56013Sjoerg     collectAllVarLocs(VarLocs, Pending, VarLocIDs);
1957*82d56013Sjoerg 
1958*82d56013Sjoerg     for (VarLoc DiffIt : VarLocs) {
1959*82d56013Sjoerg       // The ID location is live-in to MBB -- work out what kind of machine
1960*82d56013Sjoerg       // location it is and create a DBG_VALUE.
1961*82d56013Sjoerg       if (DiffIt.isEntryBackupLoc())
1962*82d56013Sjoerg         continue;
1963*82d56013Sjoerg       MachineInstr *MI = DiffIt.BuildDbgValue(*MBB.getParent());
1964*82d56013Sjoerg       MBB.insert(MBB.instr_begin(), MI);
1965*82d56013Sjoerg 
1966*82d56013Sjoerg       (void)MI;
1967*82d56013Sjoerg       LLVM_DEBUG(dbgs() << "Inserted: "; MI->dump(););
1968*82d56013Sjoerg     }
1969*82d56013Sjoerg   }
1970*82d56013Sjoerg }
1971*82d56013Sjoerg 
isEntryValueCandidate(const MachineInstr & MI,const DefinedRegsSet & DefinedRegs) const1972*82d56013Sjoerg bool VarLocBasedLDV::isEntryValueCandidate(
1973*82d56013Sjoerg     const MachineInstr &MI, const DefinedRegsSet &DefinedRegs) const {
1974*82d56013Sjoerg   assert(MI.isDebugValue() && "This must be DBG_VALUE.");
1975*82d56013Sjoerg 
1976*82d56013Sjoerg   // TODO: Add support for local variables that are expressed in terms of
1977*82d56013Sjoerg   // parameters entry values.
1978*82d56013Sjoerg   // TODO: Add support for modified arguments that can be expressed
1979*82d56013Sjoerg   // by using its entry value.
1980*82d56013Sjoerg   auto *DIVar = MI.getDebugVariable();
1981*82d56013Sjoerg   if (!DIVar->isParameter())
1982*82d56013Sjoerg     return false;
1983*82d56013Sjoerg 
1984*82d56013Sjoerg   // Do not consider parameters that belong to an inlined function.
1985*82d56013Sjoerg   if (MI.getDebugLoc()->getInlinedAt())
1986*82d56013Sjoerg     return false;
1987*82d56013Sjoerg 
1988*82d56013Sjoerg   // Only consider parameters that are described using registers. Parameters
1989*82d56013Sjoerg   // that are passed on the stack are not yet supported, so ignore debug
1990*82d56013Sjoerg   // values that are described by the frame or stack pointer.
1991*82d56013Sjoerg   if (!isRegOtherThanSPAndFP(MI.getDebugOperand(0), MI, TRI))
1992*82d56013Sjoerg     return false;
1993*82d56013Sjoerg 
1994*82d56013Sjoerg   // If a parameter's value has been propagated from the caller, then the
1995*82d56013Sjoerg   // parameter's DBG_VALUE may be described using a register defined by some
1996*82d56013Sjoerg   // instruction in the entry block, in which case we shouldn't create an
1997*82d56013Sjoerg   // entry value.
1998*82d56013Sjoerg   if (DefinedRegs.count(MI.getDebugOperand(0).getReg()))
1999*82d56013Sjoerg     return false;
2000*82d56013Sjoerg 
2001*82d56013Sjoerg   // TODO: Add support for parameters that have a pre-existing debug expressions
2002*82d56013Sjoerg   // (e.g. fragments).
2003*82d56013Sjoerg   if (MI.getDebugExpression()->getNumElements() > 0)
2004*82d56013Sjoerg     return false;
2005*82d56013Sjoerg 
2006*82d56013Sjoerg   return true;
2007*82d56013Sjoerg }
2008*82d56013Sjoerg 
2009*82d56013Sjoerg /// Collect all register defines (including aliases) for the given instruction.
collectRegDefs(const MachineInstr & MI,DefinedRegsSet & Regs,const TargetRegisterInfo * TRI)2010*82d56013Sjoerg static void collectRegDefs(const MachineInstr &MI, DefinedRegsSet &Regs,
2011*82d56013Sjoerg                            const TargetRegisterInfo *TRI) {
2012*82d56013Sjoerg   for (const MachineOperand &MO : MI.operands())
2013*82d56013Sjoerg     if (MO.isReg() && MO.isDef() && MO.getReg())
2014*82d56013Sjoerg       for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
2015*82d56013Sjoerg         Regs.insert(*AI);
2016*82d56013Sjoerg }
2017*82d56013Sjoerg 
2018*82d56013Sjoerg /// This routine records the entry values of function parameters. The values
2019*82d56013Sjoerg /// could be used as backup values. If we loose the track of some unmodified
2020*82d56013Sjoerg /// parameters, the backup values will be used as a primary locations.
recordEntryValue(const MachineInstr & MI,const DefinedRegsSet & DefinedRegs,OpenRangesSet & OpenRanges,VarLocMap & VarLocIDs)2021*82d56013Sjoerg void VarLocBasedLDV::recordEntryValue(const MachineInstr &MI,
2022*82d56013Sjoerg                                        const DefinedRegsSet &DefinedRegs,
2023*82d56013Sjoerg                                        OpenRangesSet &OpenRanges,
2024*82d56013Sjoerg                                        VarLocMap &VarLocIDs) {
2025*82d56013Sjoerg   if (TPC) {
2026*82d56013Sjoerg     auto &TM = TPC->getTM<TargetMachine>();
2027*82d56013Sjoerg     if (!TM.Options.ShouldEmitDebugEntryValues())
2028*82d56013Sjoerg       return;
2029*82d56013Sjoerg   }
2030*82d56013Sjoerg 
2031*82d56013Sjoerg   DebugVariable V(MI.getDebugVariable(), MI.getDebugExpression(),
2032*82d56013Sjoerg                   MI.getDebugLoc()->getInlinedAt());
2033*82d56013Sjoerg 
2034*82d56013Sjoerg   if (!isEntryValueCandidate(MI, DefinedRegs) ||
2035*82d56013Sjoerg       OpenRanges.getEntryValueBackup(V))
2036*82d56013Sjoerg     return;
2037*82d56013Sjoerg 
2038*82d56013Sjoerg   LLVM_DEBUG(dbgs() << "Creating the backup entry location: "; MI.dump(););
2039*82d56013Sjoerg 
2040*82d56013Sjoerg   // Create the entry value and use it as a backup location until it is
2041*82d56013Sjoerg   // valid. It is valid until a parameter is not changed.
2042*82d56013Sjoerg   DIExpression *NewExpr =
2043*82d56013Sjoerg       DIExpression::prepend(MI.getDebugExpression(), DIExpression::EntryValue);
2044*82d56013Sjoerg   VarLoc EntryValLocAsBackup = VarLoc::CreateEntryBackupLoc(MI, LS, NewExpr);
2045*82d56013Sjoerg   LocIndices EntryValLocIDs = VarLocIDs.insert(EntryValLocAsBackup);
2046*82d56013Sjoerg   OpenRanges.insert(EntryValLocIDs, EntryValLocAsBackup);
2047*82d56013Sjoerg }
2048*82d56013Sjoerg 
2049*82d56013Sjoerg /// Calculate the liveness information for the given machine function and
2050*82d56013Sjoerg /// extend ranges across basic blocks.
ExtendRanges(MachineFunction & MF,TargetPassConfig * TPC)2051*82d56013Sjoerg bool VarLocBasedLDV::ExtendRanges(MachineFunction &MF, TargetPassConfig *TPC) {
2052*82d56013Sjoerg   LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
2053*82d56013Sjoerg 
2054*82d56013Sjoerg   if (!MF.getFunction().getSubprogram())
2055*82d56013Sjoerg     // VarLocBaseLDV will already have removed all DBG_VALUEs.
2056*82d56013Sjoerg     return false;
2057*82d56013Sjoerg 
2058*82d56013Sjoerg   // Skip functions from NoDebug compilation units.
2059*82d56013Sjoerg   if (MF.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
2060*82d56013Sjoerg       DICompileUnit::NoDebug)
2061*82d56013Sjoerg     return false;
2062*82d56013Sjoerg 
2063*82d56013Sjoerg   TRI = MF.getSubtarget().getRegisterInfo();
2064*82d56013Sjoerg   TII = MF.getSubtarget().getInstrInfo();
2065*82d56013Sjoerg   TFI = MF.getSubtarget().getFrameLowering();
2066*82d56013Sjoerg   TFI->getCalleeSaves(MF, CalleeSavedRegs);
2067*82d56013Sjoerg   this->TPC = TPC;
2068*82d56013Sjoerg   LS.initialize(MF);
2069*82d56013Sjoerg 
2070*82d56013Sjoerg   bool Changed = false;
2071*82d56013Sjoerg   bool OLChanged = false;
2072*82d56013Sjoerg   bool MBBJoined = false;
2073*82d56013Sjoerg 
2074*82d56013Sjoerg   VarLocMap VarLocIDs;         // Map VarLoc<>unique ID for use in bitvectors.
2075*82d56013Sjoerg   OverlapMap OverlapFragments; // Map of overlapping variable fragments.
2076*82d56013Sjoerg   OpenRangesSet OpenRanges(Alloc, OverlapFragments);
2077*82d56013Sjoerg                               // Ranges that are open until end of bb.
2078*82d56013Sjoerg   VarLocInMBB OutLocs;        // Ranges that exist beyond bb.
2079*82d56013Sjoerg   VarLocInMBB InLocs;         // Ranges that are incoming after joining.
2080*82d56013Sjoerg   TransferMap Transfers;      // DBG_VALUEs associated with transfers (such as
2081*82d56013Sjoerg                               // spills, copies and restores).
2082*82d56013Sjoerg 
2083*82d56013Sjoerg   VarToFragments SeenFragments;
2084*82d56013Sjoerg 
2085*82d56013Sjoerg   // Blocks which are artificial, i.e. blocks which exclusively contain
2086*82d56013Sjoerg   // instructions without locations, or with line 0 locations.
2087*82d56013Sjoerg   SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
2088*82d56013Sjoerg 
2089*82d56013Sjoerg   DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
2090*82d56013Sjoerg   DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
2091*82d56013Sjoerg   std::priority_queue<unsigned int, std::vector<unsigned int>,
2092*82d56013Sjoerg                       std::greater<unsigned int>>
2093*82d56013Sjoerg       Worklist;
2094*82d56013Sjoerg   std::priority_queue<unsigned int, std::vector<unsigned int>,
2095*82d56013Sjoerg                       std::greater<unsigned int>>
2096*82d56013Sjoerg       Pending;
2097*82d56013Sjoerg 
2098*82d56013Sjoerg   // Set of register defines that are seen when traversing the entry block
2099*82d56013Sjoerg   // looking for debug entry value candidates.
2100*82d56013Sjoerg   DefinedRegsSet DefinedRegs;
2101*82d56013Sjoerg 
2102*82d56013Sjoerg   // Only in the case of entry MBB collect DBG_VALUEs representing
2103*82d56013Sjoerg   // function parameters in order to generate debug entry values for them.
2104*82d56013Sjoerg   MachineBasicBlock &First_MBB = *(MF.begin());
2105*82d56013Sjoerg   for (auto &MI : First_MBB) {
2106*82d56013Sjoerg     collectRegDefs(MI, DefinedRegs, TRI);
2107*82d56013Sjoerg     if (MI.isDebugValue())
2108*82d56013Sjoerg       recordEntryValue(MI, DefinedRegs, OpenRanges, VarLocIDs);
2109*82d56013Sjoerg   }
2110*82d56013Sjoerg 
2111*82d56013Sjoerg   // Initialize per-block structures and scan for fragment overlaps.
2112*82d56013Sjoerg   for (auto &MBB : MF)
2113*82d56013Sjoerg     for (auto &MI : MBB)
2114*82d56013Sjoerg       if (MI.isDebugValue())
2115*82d56013Sjoerg         accumulateFragmentMap(MI, SeenFragments, OverlapFragments);
2116*82d56013Sjoerg 
2117*82d56013Sjoerg   auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
2118*82d56013Sjoerg     if (const DebugLoc &DL = MI.getDebugLoc())
2119*82d56013Sjoerg       return DL.getLine() != 0;
2120*82d56013Sjoerg     return false;
2121*82d56013Sjoerg   };
2122*82d56013Sjoerg   for (auto &MBB : MF)
2123*82d56013Sjoerg     if (none_of(MBB.instrs(), hasNonArtificialLocation))
2124*82d56013Sjoerg       ArtificialBlocks.insert(&MBB);
2125*82d56013Sjoerg 
2126*82d56013Sjoerg   LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
2127*82d56013Sjoerg                               "OutLocs after initialization", dbgs()));
2128*82d56013Sjoerg 
2129*82d56013Sjoerg   ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
2130*82d56013Sjoerg   unsigned int RPONumber = 0;
2131*82d56013Sjoerg   for (MachineBasicBlock *MBB : RPOT) {
2132*82d56013Sjoerg     OrderToBB[RPONumber] = MBB;
2133*82d56013Sjoerg     BBToOrder[MBB] = RPONumber;
2134*82d56013Sjoerg     Worklist.push(RPONumber);
2135*82d56013Sjoerg     ++RPONumber;
2136*82d56013Sjoerg   }
2137*82d56013Sjoerg 
2138*82d56013Sjoerg   if (RPONumber > InputBBLimit) {
2139*82d56013Sjoerg     unsigned NumInputDbgValues = 0;
2140*82d56013Sjoerg     for (auto &MBB : MF)
2141*82d56013Sjoerg       for (auto &MI : MBB)
2142*82d56013Sjoerg         if (MI.isDebugValue())
2143*82d56013Sjoerg           ++NumInputDbgValues;
2144*82d56013Sjoerg     if (NumInputDbgValues > InputDbgValueLimit) {
2145*82d56013Sjoerg       LLVM_DEBUG(dbgs() << "Disabling VarLocBasedLDV: " << MF.getName()
2146*82d56013Sjoerg                         << " has " << RPONumber << " basic blocks and "
2147*82d56013Sjoerg                         << NumInputDbgValues
2148*82d56013Sjoerg                         << " input DBG_VALUEs, exceeding limits.\n");
2149*82d56013Sjoerg       return false;
2150*82d56013Sjoerg     }
2151*82d56013Sjoerg   }
2152*82d56013Sjoerg 
2153*82d56013Sjoerg   // This is a standard "union of predecessor outs" dataflow problem.
2154*82d56013Sjoerg   // To solve it, we perform join() and process() using the two worklist method
2155*82d56013Sjoerg   // until the ranges converge.
2156*82d56013Sjoerg   // Ranges have converged when both worklists are empty.
2157*82d56013Sjoerg   SmallPtrSet<const MachineBasicBlock *, 16> Visited;
2158*82d56013Sjoerg   while (!Worklist.empty() || !Pending.empty()) {
2159*82d56013Sjoerg     // We track what is on the pending worklist to avoid inserting the same
2160*82d56013Sjoerg     // thing twice.  We could avoid this with a custom priority queue, but this
2161*82d56013Sjoerg     // is probably not worth it.
2162*82d56013Sjoerg     SmallPtrSet<MachineBasicBlock *, 16> OnPending;
2163*82d56013Sjoerg     LLVM_DEBUG(dbgs() << "Processing Worklist\n");
2164*82d56013Sjoerg     while (!Worklist.empty()) {
2165*82d56013Sjoerg       MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
2166*82d56013Sjoerg       Worklist.pop();
2167*82d56013Sjoerg       MBBJoined = join(*MBB, OutLocs, InLocs, VarLocIDs, Visited,
2168*82d56013Sjoerg                        ArtificialBlocks);
2169*82d56013Sjoerg       MBBJoined |= Visited.insert(MBB).second;
2170*82d56013Sjoerg       if (MBBJoined) {
2171*82d56013Sjoerg         MBBJoined = false;
2172*82d56013Sjoerg         Changed = true;
2173*82d56013Sjoerg         // Now that we have started to extend ranges across BBs we need to
2174*82d56013Sjoerg         // examine spill, copy and restore instructions to see whether they
2175*82d56013Sjoerg         // operate with registers that correspond to user variables.
2176*82d56013Sjoerg         // First load any pending inlocs.
2177*82d56013Sjoerg         OpenRanges.insertFromLocSet(getVarLocsInMBB(MBB, InLocs), VarLocIDs);
2178*82d56013Sjoerg         for (auto &MI : *MBB)
2179*82d56013Sjoerg           process(MI, OpenRanges, VarLocIDs, Transfers);
2180*82d56013Sjoerg         OLChanged |= transferTerminator(MBB, OpenRanges, OutLocs, VarLocIDs);
2181*82d56013Sjoerg 
2182*82d56013Sjoerg         LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
2183*82d56013Sjoerg                                     "OutLocs after propagating", dbgs()));
2184*82d56013Sjoerg         LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
2185*82d56013Sjoerg                                     "InLocs after propagating", dbgs()));
2186*82d56013Sjoerg 
2187*82d56013Sjoerg         if (OLChanged) {
2188*82d56013Sjoerg           OLChanged = false;
2189*82d56013Sjoerg           for (auto s : MBB->successors())
2190*82d56013Sjoerg             if (OnPending.insert(s).second) {
2191*82d56013Sjoerg               Pending.push(BBToOrder[s]);
2192*82d56013Sjoerg             }
2193*82d56013Sjoerg         }
2194*82d56013Sjoerg       }
2195*82d56013Sjoerg     }
2196*82d56013Sjoerg     Worklist.swap(Pending);
2197*82d56013Sjoerg     // At this point, pending must be empty, since it was just the empty
2198*82d56013Sjoerg     // worklist
2199*82d56013Sjoerg     assert(Pending.empty() && "Pending should be empty");
2200*82d56013Sjoerg   }
2201*82d56013Sjoerg 
2202*82d56013Sjoerg   // Add any DBG_VALUE instructions created by location transfers.
2203*82d56013Sjoerg   for (auto &TR : Transfers) {
2204*82d56013Sjoerg     assert(!TR.TransferInst->isTerminator() &&
2205*82d56013Sjoerg            "Cannot insert DBG_VALUE after terminator");
2206*82d56013Sjoerg     MachineBasicBlock *MBB = TR.TransferInst->getParent();
2207*82d56013Sjoerg     const VarLoc &VL = VarLocIDs[TR.LocationID];
2208*82d56013Sjoerg     MachineInstr *MI = VL.BuildDbgValue(MF);
2209*82d56013Sjoerg     MBB->insertAfterBundle(TR.TransferInst->getIterator(), MI);
2210*82d56013Sjoerg   }
2211*82d56013Sjoerg   Transfers.clear();
2212*82d56013Sjoerg 
2213*82d56013Sjoerg   // Deferred inlocs will not have had any DBG_VALUE insts created; do
2214*82d56013Sjoerg   // that now.
2215*82d56013Sjoerg   flushPendingLocs(InLocs, VarLocIDs);
2216*82d56013Sjoerg 
2217*82d56013Sjoerg   LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
2218*82d56013Sjoerg   LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
2219*82d56013Sjoerg   return Changed;
2220*82d56013Sjoerg }
2221*82d56013Sjoerg 
2222*82d56013Sjoerg LDVImpl *
makeVarLocBasedLiveDebugValues()2223*82d56013Sjoerg llvm::makeVarLocBasedLiveDebugValues()
2224*82d56013Sjoerg {
2225*82d56013Sjoerg   return new VarLocBasedLDV();
2226*82d56013Sjoerg }
2227