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