1b60736ecSDimitry Andric //===- InstrRefBasedImpl.cpp - Tracking Debug Value MIs -------------------===//
2b60736ecSDimitry Andric //
3b60736ecSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4b60736ecSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5b60736ecSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6b60736ecSDimitry Andric //
7b60736ecSDimitry Andric //===----------------------------------------------------------------------===//
8b60736ecSDimitry Andric /// \file InstrRefBasedImpl.cpp
9b60736ecSDimitry Andric ///
10b60736ecSDimitry Andric /// This is a separate implementation of LiveDebugValues, see
11b60736ecSDimitry Andric /// LiveDebugValues.cpp and VarLocBasedImpl.cpp for more information.
12b60736ecSDimitry Andric ///
13b60736ecSDimitry Andric /// This pass propagates variable locations between basic blocks, resolving
14c0981da4SDimitry Andric /// control flow conflicts between them. The problem is SSA construction, where
15c0981da4SDimitry Andric /// each debug instruction assigns the *value* that a variable has, and every
16c0981da4SDimitry Andric /// instruction where the variable is in scope uses that variable. The resulting
17c0981da4SDimitry Andric /// map of instruction-to-value is then translated into a register (or spill)
18c0981da4SDimitry Andric /// location for each variable over each instruction.
19b60736ecSDimitry Andric ///
20c0981da4SDimitry Andric /// The primary difference from normal SSA construction is that we cannot
21c0981da4SDimitry Andric /// _create_ PHI values that contain variable values. CodeGen has already
22c0981da4SDimitry Andric /// completed, and we can't alter it just to make debug-info complete. Thus:
23c0981da4SDimitry Andric /// we can identify function positions where we would like a PHI value for a
24c0981da4SDimitry Andric /// variable, but must search the MachineFunction to see whether such a PHI is
25c0981da4SDimitry Andric /// available. If no such PHI exists, the variable location must be dropped.
26b60736ecSDimitry Andric ///
27c0981da4SDimitry Andric /// To achieve this, we perform two kinds of analysis. First, we identify
28b60736ecSDimitry Andric /// every value defined by every instruction (ignoring those that only move
29c0981da4SDimitry Andric /// another value), then re-compute an SSA-form representation of the
30c0981da4SDimitry Andric /// MachineFunction, using value propagation to eliminate any un-necessary
31c0981da4SDimitry Andric /// PHI values. This gives us a map of every value computed in the function,
32c0981da4SDimitry Andric /// and its location within the register file / stack.
33b60736ecSDimitry Andric ///
34c0981da4SDimitry Andric /// Secondly, for each variable we perform the same analysis, where each debug
35c0981da4SDimitry Andric /// instruction is considered a def, and every instruction where the variable
36c0981da4SDimitry Andric /// is in lexical scope as a use. Value propagation is used again to eliminate
37c0981da4SDimitry Andric /// any un-necessary PHIs. This gives us a map of each variable to the value
38c0981da4SDimitry Andric /// it should have in a block.
39b60736ecSDimitry Andric ///
40c0981da4SDimitry Andric /// Once both are complete, we have two maps for each block:
41c0981da4SDimitry Andric /// * Variables to the values they should have,
42c0981da4SDimitry Andric /// * Values to the register / spill slot they are located in.
43c0981da4SDimitry Andric /// After which we can marry-up variable values with a location, and emit
44c0981da4SDimitry Andric /// DBG_VALUE instructions specifying those locations. Variable locations may
45c0981da4SDimitry Andric /// be dropped in this process due to the desired variable value not being
46c0981da4SDimitry Andric /// resident in any machine location, or because there is no PHI value in any
47c0981da4SDimitry Andric /// location that accurately represents the desired value. The building of
48c0981da4SDimitry Andric /// location lists for each block is left to DbgEntityHistoryCalculator.
49b60736ecSDimitry Andric ///
50c0981da4SDimitry Andric /// This pass is kept efficient because the size of the first SSA problem
51c0981da4SDimitry Andric /// is proportional to the working-set size of the function, which the compiler
52c0981da4SDimitry Andric /// tries to keep small. (It's also proportional to the number of blocks).
53c0981da4SDimitry Andric /// Additionally, we repeatedly perform the second SSA problem analysis with
54c0981da4SDimitry Andric /// only the variables and blocks in a single lexical scope, exploiting their
55c0981da4SDimitry Andric /// locality.
56b60736ecSDimitry Andric ///
57b60736ecSDimitry Andric /// ### Terminology
58b60736ecSDimitry Andric ///
59b60736ecSDimitry Andric /// A machine location is a register or spill slot, a value is something that's
60b60736ecSDimitry Andric /// defined by an instruction or PHI node, while a variable value is the value
61b60736ecSDimitry Andric /// assigned to a variable. A variable location is a machine location, that must
62b60736ecSDimitry Andric /// contain the appropriate variable value. A value that is a PHI node is
63b60736ecSDimitry Andric /// occasionally called an mphi.
64b60736ecSDimitry Andric ///
65c0981da4SDimitry Andric /// The first SSA problem is the "machine value location" problem,
66b60736ecSDimitry Andric /// because we're determining which machine locations contain which values.
67b60736ecSDimitry Andric /// The "locations" are constant: what's unknown is what value they contain.
68b60736ecSDimitry Andric ///
69c0981da4SDimitry Andric /// The second SSA problem (the one for variables) is the "variable value
70b60736ecSDimitry Andric /// problem", because it's determining what values a variable has, rather than
71c0981da4SDimitry Andric /// what location those values are placed in.
72b60736ecSDimitry Andric ///
73b60736ecSDimitry Andric /// TODO:
74b60736ecSDimitry Andric /// Overlapping fragments
75b60736ecSDimitry Andric /// Entry values
76b60736ecSDimitry Andric /// Add back DEBUG statements for debugging this
77b60736ecSDimitry Andric /// Collect statistics
78b60736ecSDimitry Andric ///
79b60736ecSDimitry Andric //===----------------------------------------------------------------------===//
80b60736ecSDimitry Andric
81b60736ecSDimitry Andric #include "llvm/ADT/DenseMap.h"
82b60736ecSDimitry Andric #include "llvm/ADT/PostOrderIterator.h"
83344a3780SDimitry Andric #include "llvm/ADT/STLExtras.h"
84b60736ecSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
85b60736ecSDimitry Andric #include "llvm/ADT/SmallSet.h"
86b60736ecSDimitry Andric #include "llvm/ADT/SmallVector.h"
87145449b1SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
88b60736ecSDimitry Andric #include "llvm/CodeGen/LexicalScopes.h"
89b60736ecSDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
90c0981da4SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
91b60736ecSDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
92b60736ecSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
93b60736ecSDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
94b60736ecSDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
95344a3780SDimitry Andric #include "llvm/CodeGen/MachineInstrBundle.h"
96b60736ecSDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
97b60736ecSDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
98b60736ecSDimitry Andric #include "llvm/CodeGen/PseudoSourceValue.h"
99b60736ecSDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
100b60736ecSDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
101b60736ecSDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
102b60736ecSDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
103b60736ecSDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
104b60736ecSDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
105b60736ecSDimitry Andric #include "llvm/Config/llvm-config.h"
106b60736ecSDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
107b60736ecSDimitry Andric #include "llvm/IR/DebugLoc.h"
108b60736ecSDimitry Andric #include "llvm/IR/Function.h"
109b60736ecSDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
110b60736ecSDimitry Andric #include "llvm/Support/Casting.h"
111b60736ecSDimitry Andric #include "llvm/Support/Compiler.h"
112b60736ecSDimitry Andric #include "llvm/Support/Debug.h"
113145449b1SDimitry Andric #include "llvm/Support/GenericIteratedDominanceFrontier.h"
114b60736ecSDimitry Andric #include "llvm/Support/TypeSize.h"
115b60736ecSDimitry Andric #include "llvm/Support/raw_ostream.h"
116344a3780SDimitry Andric #include "llvm/Target/TargetMachine.h"
117344a3780SDimitry Andric #include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
118b60736ecSDimitry Andric #include <algorithm>
119b60736ecSDimitry Andric #include <cassert>
120145449b1SDimitry Andric #include <climits>
121b60736ecSDimitry Andric #include <cstdint>
122b60736ecSDimitry Andric #include <functional>
123b60736ecSDimitry Andric #include <queue>
124b60736ecSDimitry Andric #include <tuple>
125b60736ecSDimitry Andric #include <utility>
126b60736ecSDimitry Andric #include <vector>
127b60736ecSDimitry Andric
128c0981da4SDimitry Andric #include "InstrRefBasedImpl.h"
129b60736ecSDimitry Andric #include "LiveDebugValues.h"
130e3b55780SDimitry Andric #include <optional>
131b60736ecSDimitry Andric
132b60736ecSDimitry Andric using namespace llvm;
133c0981da4SDimitry Andric using namespace LiveDebugValues;
134b60736ecSDimitry Andric
135344a3780SDimitry Andric // SSAUpdaterImple sets DEBUG_TYPE, change it.
136344a3780SDimitry Andric #undef DEBUG_TYPE
137b60736ecSDimitry Andric #define DEBUG_TYPE "livedebugvalues"
138b60736ecSDimitry Andric
139b60736ecSDimitry Andric // Act more like the VarLoc implementation, by propagating some locations too
140b60736ecSDimitry Andric // far and ignoring some transfers.
141b60736ecSDimitry Andric static cl::opt<bool> EmulateOldLDV("emulate-old-livedebugvalues", cl::Hidden,
142b60736ecSDimitry Andric cl::desc("Act like old LiveDebugValues did"),
143b60736ecSDimitry Andric cl::init(false));
144b60736ecSDimitry Andric
145145449b1SDimitry Andric // Limit for the maximum number of stack slots we should track, past which we
146145449b1SDimitry Andric // will ignore any spills. InstrRefBasedLDV gathers detailed information on all
147145449b1SDimitry Andric // stack slots which leads to high memory consumption, and in some scenarios
148145449b1SDimitry Andric // (such as asan with very many locals) the working set of the function can be
149145449b1SDimitry Andric // very large, causing many spills. In these scenarios, it is very unlikely that
150145449b1SDimitry Andric // the developer has hundreds of variables live at the same time that they're
151145449b1SDimitry Andric // carefully thinking about -- instead, they probably autogenerated the code.
152145449b1SDimitry Andric // When this happens, gracefully stop tracking excess spill slots, rather than
153145449b1SDimitry Andric // consuming all the developer's memory.
154145449b1SDimitry Andric static cl::opt<unsigned>
155145449b1SDimitry Andric StackWorkingSetLimit("livedebugvalues-max-stack-slots", cl::Hidden,
156145449b1SDimitry Andric cl::desc("livedebugvalues-stack-ws-limit"),
157145449b1SDimitry Andric cl::init(250));
158145449b1SDimitry Andric
159e3b55780SDimitry Andric DbgOpID DbgOpID::UndefID = DbgOpID(0xffffffff);
160e3b55780SDimitry Andric
161b60736ecSDimitry Andric /// Tracker for converting machine value locations and variable values into
162b60736ecSDimitry Andric /// variable locations (the output of LiveDebugValues), recorded as DBG_VALUEs
163b60736ecSDimitry Andric /// specifying block live-in locations and transfers within blocks.
164b60736ecSDimitry Andric ///
165b60736ecSDimitry Andric /// Operating on a per-block basis, this class takes a (pre-loaded) MLocTracker
166b60736ecSDimitry Andric /// and must be initialized with the set of variable values that are live-in to
167b60736ecSDimitry Andric /// the block. The caller then repeatedly calls process(). TransferTracker picks
168b60736ecSDimitry Andric /// out variable locations for the live-in variable values (if there _is_ a
169b60736ecSDimitry Andric /// location) and creates the corresponding DBG_VALUEs. Then, as the block is
170b60736ecSDimitry Andric /// stepped through, transfers of values between machine locations are
171b60736ecSDimitry Andric /// identified and if profitable, a DBG_VALUE created.
172b60736ecSDimitry Andric ///
173b60736ecSDimitry Andric /// This is where debug use-before-defs would be resolved: a variable with an
174b60736ecSDimitry Andric /// unavailable value could materialize in the middle of a block, when the
175b60736ecSDimitry Andric /// value becomes available. Or, we could detect clobbers and re-specify the
176b60736ecSDimitry Andric /// variable in a backup location. (XXX these are unimplemented).
177b60736ecSDimitry Andric class TransferTracker {
178b60736ecSDimitry Andric public:
179b60736ecSDimitry Andric const TargetInstrInfo *TII;
180344a3780SDimitry Andric const TargetLowering *TLI;
181b60736ecSDimitry Andric /// This machine location tracker is assumed to always contain the up-to-date
182b60736ecSDimitry Andric /// value mapping for all machine locations. TransferTracker only reads
183b60736ecSDimitry Andric /// information from it. (XXX make it const?)
184b60736ecSDimitry Andric MLocTracker *MTracker;
185b60736ecSDimitry Andric MachineFunction &MF;
186ac9a064cSDimitry Andric const DebugVariableMap &DVMap;
187344a3780SDimitry Andric bool ShouldEmitDebugEntryValues;
188b60736ecSDimitry Andric
189b60736ecSDimitry Andric /// Record of all changes in variable locations at a block position. Awkwardly
190b60736ecSDimitry Andric /// we allow inserting either before or after the point: MBB != nullptr
191b60736ecSDimitry Andric /// indicates it's before, otherwise after.
192b60736ecSDimitry Andric struct Transfer {
193344a3780SDimitry Andric MachineBasicBlock::instr_iterator Pos; /// Position to insert DBG_VALUes
194b60736ecSDimitry Andric MachineBasicBlock *MBB; /// non-null if we should insert after.
195ac9a064cSDimitry Andric /// Vector of DBG_VALUEs to insert. Store with their DebugVariableID so that
196ac9a064cSDimitry Andric /// they can be sorted into a stable order for emission at a later time.
197ac9a064cSDimitry Andric SmallVector<std::pair<DebugVariableID, MachineInstr *>, 4> Insts;
198b60736ecSDimitry Andric };
199b60736ecSDimitry Andric
200e3b55780SDimitry Andric /// Stores the resolved operands (machine locations and constants) and
201e3b55780SDimitry Andric /// qualifying meta-information needed to construct a concrete DBG_VALUE-like
202e3b55780SDimitry Andric /// instruction.
203e3b55780SDimitry Andric struct ResolvedDbgValue {
204e3b55780SDimitry Andric SmallVector<ResolvedDbgOp> Ops;
205b60736ecSDimitry Andric DbgValueProperties Properties;
206e3b55780SDimitry Andric
ResolvedDbgValueTransferTracker::ResolvedDbgValue207e3b55780SDimitry Andric ResolvedDbgValue(SmallVectorImpl<ResolvedDbgOp> &Ops,
208e3b55780SDimitry Andric DbgValueProperties Properties)
209e3b55780SDimitry Andric : Ops(Ops.begin(), Ops.end()), Properties(Properties) {}
210e3b55780SDimitry Andric
211e3b55780SDimitry Andric /// Returns all the LocIdx values used in this struct, in the order in which
212e3b55780SDimitry Andric /// they appear as operands in the debug value; may contain duplicates.
loc_indicesTransferTracker::ResolvedDbgValue213e3b55780SDimitry Andric auto loc_indices() const {
214e3b55780SDimitry Andric return map_range(
215e3b55780SDimitry Andric make_filter_range(
216e3b55780SDimitry Andric Ops, [](const ResolvedDbgOp &Op) { return !Op.IsConst; }),
217e3b55780SDimitry Andric [](const ResolvedDbgOp &Op) { return Op.Loc; });
218e3b55780SDimitry Andric }
219344a3780SDimitry Andric };
220b60736ecSDimitry Andric
221b60736ecSDimitry Andric /// Collection of transfers (DBG_VALUEs) to be inserted.
222b60736ecSDimitry Andric SmallVector<Transfer, 32> Transfers;
223b60736ecSDimitry Andric
224b60736ecSDimitry Andric /// Local cache of what-value-is-in-what-LocIdx. Used to identify differences
225b60736ecSDimitry Andric /// between TransferTrackers view of variable locations and MLocTrackers. For
226b60736ecSDimitry Andric /// example, MLocTracker observes all clobbers, but TransferTracker lazily
227b60736ecSDimitry Andric /// does not.
228c0981da4SDimitry Andric SmallVector<ValueIDNum, 32> VarLocs;
229b60736ecSDimitry Andric
230b60736ecSDimitry Andric /// Map from LocIdxes to which DebugVariables are based that location.
231b60736ecSDimitry Andric /// Mantained while stepping through the block. Not accurate if
232b60736ecSDimitry Andric /// VarLocs[Idx] != MTracker->LocIdxToIDNum[Idx].
233ac9a064cSDimitry Andric DenseMap<LocIdx, SmallSet<DebugVariableID, 4>> ActiveMLocs;
234b60736ecSDimitry Andric
235b60736ecSDimitry Andric /// Map from DebugVariable to it's current location and qualifying meta
236b60736ecSDimitry Andric /// information. To be used in conjunction with ActiveMLocs to construct
237b60736ecSDimitry Andric /// enough information for the DBG_VALUEs for a particular LocIdx.
238ac9a064cSDimitry Andric DenseMap<DebugVariableID, ResolvedDbgValue> ActiveVLocs;
239b60736ecSDimitry Andric
240b60736ecSDimitry Andric /// Temporary cache of DBG_VALUEs to be entered into the Transfers collection.
241ac9a064cSDimitry Andric SmallVector<std::pair<DebugVariableID, MachineInstr *>, 4> PendingDbgValues;
242b60736ecSDimitry Andric
243b60736ecSDimitry Andric /// Record of a use-before-def: created when a value that's live-in to the
244b60736ecSDimitry Andric /// current block isn't available in any machine location, but it will be
245b60736ecSDimitry Andric /// defined in this block.
246b60736ecSDimitry Andric struct UseBeforeDef {
247b60736ecSDimitry Andric /// Value of this variable, def'd in block.
248e3b55780SDimitry Andric SmallVector<DbgOp> Values;
249b60736ecSDimitry Andric /// Identity of this variable.
250ac9a064cSDimitry Andric DebugVariableID VarID;
251b60736ecSDimitry Andric /// Additional variable properties.
252b60736ecSDimitry Andric DbgValueProperties Properties;
UseBeforeDefTransferTracker::UseBeforeDef253ac9a064cSDimitry Andric UseBeforeDef(ArrayRef<DbgOp> Values, DebugVariableID VarID,
254e3b55780SDimitry Andric const DbgValueProperties &Properties)
255ac9a064cSDimitry Andric : Values(Values.begin(), Values.end()), VarID(VarID),
256e3b55780SDimitry Andric Properties(Properties) {}
257b60736ecSDimitry Andric };
258b60736ecSDimitry Andric
259b60736ecSDimitry Andric /// Map from instruction index (within the block) to the set of UseBeforeDefs
260b60736ecSDimitry Andric /// that become defined at that instruction.
261b60736ecSDimitry Andric DenseMap<unsigned, SmallVector<UseBeforeDef, 1>> UseBeforeDefs;
262b60736ecSDimitry Andric
263b60736ecSDimitry Andric /// The set of variables that are in UseBeforeDefs and can become a location
264b60736ecSDimitry Andric /// once the relevant value is defined. An element being erased from this
265b60736ecSDimitry Andric /// collection prevents the use-before-def materializing.
266ac9a064cSDimitry Andric DenseSet<DebugVariableID> UseBeforeDefVariables;
267b60736ecSDimitry Andric
268b60736ecSDimitry Andric const TargetRegisterInfo &TRI;
269b60736ecSDimitry Andric const BitVector &CalleeSavedRegs;
270b60736ecSDimitry Andric
TransferTracker(const TargetInstrInfo * TII,MLocTracker * MTracker,MachineFunction & MF,const DebugVariableMap & DVMap,const TargetRegisterInfo & TRI,const BitVector & CalleeSavedRegs,const TargetPassConfig & TPC)271b60736ecSDimitry Andric TransferTracker(const TargetInstrInfo *TII, MLocTracker *MTracker,
272ac9a064cSDimitry Andric MachineFunction &MF, const DebugVariableMap &DVMap,
273ac9a064cSDimitry Andric const TargetRegisterInfo &TRI,
274344a3780SDimitry Andric const BitVector &CalleeSavedRegs, const TargetPassConfig &TPC)
275ac9a064cSDimitry Andric : TII(TII), MTracker(MTracker), MF(MF), DVMap(DVMap), TRI(TRI),
276344a3780SDimitry Andric CalleeSavedRegs(CalleeSavedRegs) {
277344a3780SDimitry Andric TLI = MF.getSubtarget().getTargetLowering();
278344a3780SDimitry Andric auto &TM = TPC.getTM<TargetMachine>();
279344a3780SDimitry Andric ShouldEmitDebugEntryValues = TM.Options.ShouldEmitDebugEntryValues();
280344a3780SDimitry Andric }
281b60736ecSDimitry Andric
isCalleeSaved(LocIdx L) const282e3b55780SDimitry Andric bool isCalleeSaved(LocIdx L) const {
283b60736ecSDimitry Andric unsigned Reg = MTracker->LocIdxToLocID[L];
284b60736ecSDimitry Andric if (Reg >= MTracker->NumRegs)
285b60736ecSDimitry Andric return false;
286b60736ecSDimitry Andric for (MCRegAliasIterator RAI(Reg, &TRI, true); RAI.isValid(); ++RAI)
287b60736ecSDimitry Andric if (CalleeSavedRegs.test(*RAI))
288b60736ecSDimitry Andric return true;
289b60736ecSDimitry Andric return false;
290b60736ecSDimitry Andric };
291b60736ecSDimitry Andric
292e3b55780SDimitry Andric // An estimate of the expected lifespan of values at a machine location, with
293e3b55780SDimitry Andric // a greater value corresponding to a longer expected lifespan, i.e. spill
294e3b55780SDimitry Andric // slots generally live longer than callee-saved registers which generally
295e3b55780SDimitry Andric // live longer than non-callee-saved registers. The minimum value of 0
296e3b55780SDimitry Andric // corresponds to an illegal location that cannot have a "lifespan" at all.
297e3b55780SDimitry Andric enum class LocationQuality : unsigned char {
298e3b55780SDimitry Andric Illegal = 0,
299e3b55780SDimitry Andric Register,
300e3b55780SDimitry Andric CalleeSavedRegister,
301e3b55780SDimitry Andric SpillSlot,
302e3b55780SDimitry Andric Best = SpillSlot
303e3b55780SDimitry Andric };
304e3b55780SDimitry Andric
305e3b55780SDimitry Andric class LocationAndQuality {
306e3b55780SDimitry Andric unsigned Location : 24;
307e3b55780SDimitry Andric unsigned Quality : 8;
308e3b55780SDimitry Andric
309e3b55780SDimitry Andric public:
LocationAndQuality()310e3b55780SDimitry Andric LocationAndQuality() : Location(0), Quality(0) {}
LocationAndQuality(LocIdx L,LocationQuality Q)311e3b55780SDimitry Andric LocationAndQuality(LocIdx L, LocationQuality Q)
312e3b55780SDimitry Andric : Location(L.asU64()), Quality(static_cast<unsigned>(Q)) {}
getLoc() const313e3b55780SDimitry Andric LocIdx getLoc() const {
314e3b55780SDimitry Andric if (!Quality)
315e3b55780SDimitry Andric return LocIdx::MakeIllegalLoc();
316e3b55780SDimitry Andric return LocIdx(Location);
317e3b55780SDimitry Andric }
getQuality() const318e3b55780SDimitry Andric LocationQuality getQuality() const { return LocationQuality(Quality); }
isIllegal() const319e3b55780SDimitry Andric bool isIllegal() const { return !Quality; }
isBest() const320e3b55780SDimitry Andric bool isBest() const { return getQuality() == LocationQuality::Best; }
321e3b55780SDimitry Andric };
322e3b55780SDimitry Andric
323ac9a064cSDimitry Andric using ValueLocPair = std::pair<ValueIDNum, LocationAndQuality>;
324ac9a064cSDimitry Andric
ValueToLocSort(const ValueLocPair & A,const ValueLocPair & B)325ac9a064cSDimitry Andric static inline bool ValueToLocSort(const ValueLocPair &A,
326ac9a064cSDimitry Andric const ValueLocPair &B) {
327ac9a064cSDimitry Andric return A.first < B.first;
328ac9a064cSDimitry Andric };
329ac9a064cSDimitry Andric
330e3b55780SDimitry Andric // Returns the LocationQuality for the location L iff the quality of L is
331e3b55780SDimitry Andric // is strictly greater than the provided minimum quality.
332e3b55780SDimitry Andric std::optional<LocationQuality>
getLocQualityIfBetter(LocIdx L,LocationQuality Min) const333e3b55780SDimitry Andric getLocQualityIfBetter(LocIdx L, LocationQuality Min) const {
334e3b55780SDimitry Andric if (L.isIllegal())
335e3b55780SDimitry Andric return std::nullopt;
336e3b55780SDimitry Andric if (Min >= LocationQuality::SpillSlot)
337e3b55780SDimitry Andric return std::nullopt;
338e3b55780SDimitry Andric if (MTracker->isSpill(L))
339e3b55780SDimitry Andric return LocationQuality::SpillSlot;
340e3b55780SDimitry Andric if (Min >= LocationQuality::CalleeSavedRegister)
341e3b55780SDimitry Andric return std::nullopt;
342e3b55780SDimitry Andric if (isCalleeSaved(L))
343e3b55780SDimitry Andric return LocationQuality::CalleeSavedRegister;
344e3b55780SDimitry Andric if (Min >= LocationQuality::Register)
345e3b55780SDimitry Andric return std::nullopt;
346e3b55780SDimitry Andric return LocationQuality::Register;
347e3b55780SDimitry Andric }
348e3b55780SDimitry Andric
349e3b55780SDimitry Andric /// For a variable \p Var with the live-in value \p Value, attempts to resolve
350e3b55780SDimitry Andric /// the DbgValue to a concrete DBG_VALUE, emitting that value and loading the
351e3b55780SDimitry Andric /// tracking information to track Var throughout the block.
352e3b55780SDimitry Andric /// \p ValueToLoc is a map containing the best known location for every
353e3b55780SDimitry Andric /// ValueIDNum that Value may use.
354e3b55780SDimitry Andric /// \p MBB is the basic block that we are loading the live-in value for.
355e3b55780SDimitry Andric /// \p DbgOpStore is the map containing the DbgOpID->DbgOp mapping needed to
356e3b55780SDimitry Andric /// determine the values used by Value.
loadVarInloc(MachineBasicBlock & MBB,DbgOpIDMap & DbgOpStore,const SmallVectorImpl<ValueLocPair> & ValueToLoc,DebugVariableID VarID,DbgValue Value)357e3b55780SDimitry Andric void loadVarInloc(MachineBasicBlock &MBB, DbgOpIDMap &DbgOpStore,
358ac9a064cSDimitry Andric const SmallVectorImpl<ValueLocPair> &ValueToLoc,
359ac9a064cSDimitry Andric DebugVariableID VarID, DbgValue Value) {
360e3b55780SDimitry Andric SmallVector<DbgOp> DbgOps;
361e3b55780SDimitry Andric SmallVector<ResolvedDbgOp> ResolvedDbgOps;
362e3b55780SDimitry Andric bool IsValueValid = true;
363e3b55780SDimitry Andric unsigned LastUseBeforeDef = 0;
364e3b55780SDimitry Andric
365e3b55780SDimitry Andric // If every value used by the incoming DbgValue is available at block
366e3b55780SDimitry Andric // entry, ResolvedDbgOps will contain the machine locations/constants for
367e3b55780SDimitry Andric // those values and will be used to emit a debug location.
368e3b55780SDimitry Andric // If one or more values are not yet available, but will all be defined in
369e3b55780SDimitry Andric // this block, then LastUseBeforeDef will track the instruction index in
370e3b55780SDimitry Andric // this BB at which the last of those values is defined, DbgOps will
371e3b55780SDimitry Andric // contain the values that we will emit when we reach that instruction.
372e3b55780SDimitry Andric // If one or more values are undef or not available throughout this block,
373e3b55780SDimitry Andric // and we can't recover as an entry value, we set IsValueValid=false and
374e3b55780SDimitry Andric // skip this variable.
375e3b55780SDimitry Andric for (DbgOpID ID : Value.getDbgOpIDs()) {
376e3b55780SDimitry Andric DbgOp Op = DbgOpStore.find(ID);
377e3b55780SDimitry Andric DbgOps.push_back(Op);
378e3b55780SDimitry Andric if (ID.isUndef()) {
379e3b55780SDimitry Andric IsValueValid = false;
380e3b55780SDimitry Andric break;
381e3b55780SDimitry Andric }
382e3b55780SDimitry Andric if (ID.isConst()) {
383e3b55780SDimitry Andric ResolvedDbgOps.push_back(Op.MO);
384e3b55780SDimitry Andric continue;
385e3b55780SDimitry Andric }
386e3b55780SDimitry Andric
387ac9a064cSDimitry Andric // Search for the desired ValueIDNum, to examine the best location found
388ac9a064cSDimitry Andric // for it. Use an empty ValueLocPair to search for an entry in ValueToLoc.
389e3b55780SDimitry Andric const ValueIDNum &Num = Op.ID;
390ac9a064cSDimitry Andric ValueLocPair Probe(Num, LocationAndQuality());
391ac9a064cSDimitry Andric auto ValuesPreferredLoc = std::lower_bound(
392ac9a064cSDimitry Andric ValueToLoc.begin(), ValueToLoc.end(), Probe, ValueToLocSort);
393ac9a064cSDimitry Andric
394ac9a064cSDimitry Andric // There must be a legitimate entry found for Num.
395ac9a064cSDimitry Andric assert(ValuesPreferredLoc != ValueToLoc.end() &&
396ac9a064cSDimitry Andric ValuesPreferredLoc->first == Num);
397ac9a064cSDimitry Andric
398e3b55780SDimitry Andric if (ValuesPreferredLoc->second.isIllegal()) {
399e3b55780SDimitry Andric // If it's a def that occurs in this block, register it as a
400e3b55780SDimitry Andric // use-before-def to be resolved as we step through the block.
401e3b55780SDimitry Andric // Continue processing values so that we add any other UseBeforeDef
402e3b55780SDimitry Andric // entries needed for later.
403e3b55780SDimitry Andric if (Num.getBlock() == (unsigned)MBB.getNumber() && !Num.isPHI()) {
404e3b55780SDimitry Andric LastUseBeforeDef = std::max(LastUseBeforeDef,
405e3b55780SDimitry Andric static_cast<unsigned>(Num.getInst()));
406e3b55780SDimitry Andric continue;
407e3b55780SDimitry Andric }
408ac9a064cSDimitry Andric recoverAsEntryValue(VarID, Value.Properties, Num);
409e3b55780SDimitry Andric IsValueValid = false;
410e3b55780SDimitry Andric break;
411e3b55780SDimitry Andric }
412e3b55780SDimitry Andric
413e3b55780SDimitry Andric // Defer modifying ActiveVLocs until after we've confirmed we have a
414e3b55780SDimitry Andric // live range.
415e3b55780SDimitry Andric LocIdx M = ValuesPreferredLoc->second.getLoc();
416e3b55780SDimitry Andric ResolvedDbgOps.push_back(M);
417e3b55780SDimitry Andric }
418e3b55780SDimitry Andric
419e3b55780SDimitry Andric // If we cannot produce a valid value for the LiveIn value within this
420e3b55780SDimitry Andric // block, skip this variable.
421e3b55780SDimitry Andric if (!IsValueValid)
422e3b55780SDimitry Andric return;
423e3b55780SDimitry Andric
424e3b55780SDimitry Andric // Add UseBeforeDef entry for the last value to be defined in this block.
425e3b55780SDimitry Andric if (LastUseBeforeDef) {
426ac9a064cSDimitry Andric addUseBeforeDef(VarID, Value.Properties, DbgOps, LastUseBeforeDef);
427e3b55780SDimitry Andric return;
428e3b55780SDimitry Andric }
429e3b55780SDimitry Andric
430e3b55780SDimitry Andric // The LiveIn value is available at block entry, begin tracking and record
431e3b55780SDimitry Andric // the transfer.
432e3b55780SDimitry Andric for (const ResolvedDbgOp &Op : ResolvedDbgOps)
433e3b55780SDimitry Andric if (!Op.IsConst)
434ac9a064cSDimitry Andric ActiveMLocs[Op.Loc].insert(VarID);
435e3b55780SDimitry Andric auto NewValue = ResolvedDbgValue{ResolvedDbgOps, Value.Properties};
436ac9a064cSDimitry Andric auto Result = ActiveVLocs.insert(std::make_pair(VarID, NewValue));
437e3b55780SDimitry Andric if (!Result.second)
438e3b55780SDimitry Andric Result.first->second = NewValue;
439ac9a064cSDimitry Andric auto &[Var, DILoc] = DVMap.lookupDVID(VarID);
440e3b55780SDimitry Andric PendingDbgValues.push_back(
441ac9a064cSDimitry Andric std::make_pair(VarID, &*MTracker->emitLoc(ResolvedDbgOps, Var, DILoc,
442ac9a064cSDimitry Andric Value.Properties)));
443e3b55780SDimitry Andric }
444e3b55780SDimitry Andric
445e3b55780SDimitry Andric /// Load object with live-in variable values. \p mlocs contains the live-in
446e3b55780SDimitry Andric /// values in each machine location, while \p vlocs the live-in variable
447e3b55780SDimitry Andric /// values. This method picks variable locations for the live-in variables,
448e3b55780SDimitry Andric /// creates DBG_VALUEs and puts them in #Transfers, then prepares the other
449e3b55780SDimitry Andric /// object fields to track variable locations as we step through the block.
450e3b55780SDimitry Andric /// FIXME: could just examine mloctracker instead of passing in \p mlocs?
451e3b55780SDimitry Andric void
loadInlocs(MachineBasicBlock & MBB,ValueTable & MLocs,DbgOpIDMap & DbgOpStore,const SmallVectorImpl<std::pair<DebugVariableID,DbgValue>> & VLocs,unsigned NumLocs)452e3b55780SDimitry Andric loadInlocs(MachineBasicBlock &MBB, ValueTable &MLocs, DbgOpIDMap &DbgOpStore,
453ac9a064cSDimitry Andric const SmallVectorImpl<std::pair<DebugVariableID, DbgValue>> &VLocs,
454e3b55780SDimitry Andric unsigned NumLocs) {
455e3b55780SDimitry Andric ActiveMLocs.clear();
456e3b55780SDimitry Andric ActiveVLocs.clear();
457e3b55780SDimitry Andric VarLocs.clear();
458e3b55780SDimitry Andric VarLocs.reserve(NumLocs);
459e3b55780SDimitry Andric UseBeforeDefs.clear();
460e3b55780SDimitry Andric UseBeforeDefVariables.clear();
461e3b55780SDimitry Andric
462ac9a064cSDimitry Andric // Mapping of the preferred locations for each value. Collected into this
463ac9a064cSDimitry Andric // vector then sorted for easy searching.
464ac9a064cSDimitry Andric SmallVector<ValueLocPair, 16> ValueToLoc;
465ecbca9f5SDimitry Andric
466ecbca9f5SDimitry Andric // Initialized the preferred-location map with illegal locations, to be
467ecbca9f5SDimitry Andric // filled in later.
4684b4fe385SDimitry Andric for (const auto &VLoc : VLocs)
469ecbca9f5SDimitry Andric if (VLoc.second.Kind == DbgValue::Def)
470e3b55780SDimitry Andric for (DbgOpID OpID : VLoc.second.getDbgOpIDs())
471e3b55780SDimitry Andric if (!OpID.ID.IsConst)
472ac9a064cSDimitry Andric ValueToLoc.push_back(
473ac9a064cSDimitry Andric {DbgOpStore.find(OpID).ID, LocationAndQuality()});
474ecbca9f5SDimitry Andric
475ac9a064cSDimitry Andric llvm::sort(ValueToLoc, ValueToLocSort);
476c0981da4SDimitry Andric ActiveMLocs.reserve(VLocs.size());
477c0981da4SDimitry Andric ActiveVLocs.reserve(VLocs.size());
478b60736ecSDimitry Andric
479b60736ecSDimitry Andric // Produce a map of value numbers to the current machine locs they live
480b60736ecSDimitry Andric // in. When emulating VarLocBasedImpl, there should only be one
481b60736ecSDimitry Andric // location; when not, we get to pick.
482b60736ecSDimitry Andric for (auto Location : MTracker->locations()) {
483b60736ecSDimitry Andric LocIdx Idx = Location.Idx;
484b60736ecSDimitry Andric ValueIDNum &VNum = MLocs[Idx.asU64()];
485e3b55780SDimitry Andric if (VNum == ValueIDNum::EmptyValue)
486e3b55780SDimitry Andric continue;
487b60736ecSDimitry Andric VarLocs.push_back(VNum);
4886f8fc217SDimitry Andric
489ecbca9f5SDimitry Andric // Is there a variable that wants a location for this value? If not, skip.
490ac9a064cSDimitry Andric ValueLocPair Probe(VNum, LocationAndQuality());
491ac9a064cSDimitry Andric auto VIt = std::lower_bound(ValueToLoc.begin(), ValueToLoc.end(), Probe,
492ac9a064cSDimitry Andric ValueToLocSort);
493ac9a064cSDimitry Andric if (VIt == ValueToLoc.end() || VIt->first != VNum)
4946f8fc217SDimitry Andric continue;
4956f8fc217SDimitry Andric
496e3b55780SDimitry Andric auto &Previous = VIt->second;
497e3b55780SDimitry Andric // If this is the first location with that value, pick it. Otherwise,
498e3b55780SDimitry Andric // consider whether it's a "longer term" location.
499e3b55780SDimitry Andric std::optional<LocationQuality> ReplacementQuality =
500e3b55780SDimitry Andric getLocQualityIfBetter(Idx, Previous.getQuality());
501e3b55780SDimitry Andric if (ReplacementQuality)
502e3b55780SDimitry Andric Previous = LocationAndQuality(Idx, *ReplacementQuality);
503b60736ecSDimitry Andric }
504b60736ecSDimitry Andric
505b60736ecSDimitry Andric // Now map variables to their picked LocIdxes.
5066f8fc217SDimitry Andric for (const auto &Var : VLocs) {
507e3b55780SDimitry Andric loadVarInloc(MBB, DbgOpStore, ValueToLoc, Var.first, Var.second);
508b60736ecSDimitry Andric }
509b60736ecSDimitry Andric flushDbgValues(MBB.begin(), &MBB);
510b60736ecSDimitry Andric }
511b60736ecSDimitry Andric
512b60736ecSDimitry Andric /// Record that \p Var has value \p ID, a value that becomes available
513b60736ecSDimitry Andric /// later in the function.
addUseBeforeDef(DebugVariableID VarID,const DbgValueProperties & Properties,const SmallVectorImpl<DbgOp> & DbgOps,unsigned Inst)514ac9a064cSDimitry Andric void addUseBeforeDef(DebugVariableID VarID,
515e3b55780SDimitry Andric const DbgValueProperties &Properties,
516e3b55780SDimitry Andric const SmallVectorImpl<DbgOp> &DbgOps, unsigned Inst) {
517ac9a064cSDimitry Andric UseBeforeDefs[Inst].emplace_back(DbgOps, VarID, Properties);
518ac9a064cSDimitry Andric UseBeforeDefVariables.insert(VarID);
519b60736ecSDimitry Andric }
520b60736ecSDimitry Andric
521b60736ecSDimitry Andric /// After the instruction at index \p Inst and position \p pos has been
522b60736ecSDimitry Andric /// processed, check whether it defines a variable value in a use-before-def.
523b60736ecSDimitry Andric /// If so, and the variable value hasn't changed since the start of the
524b60736ecSDimitry Andric /// block, create a DBG_VALUE.
checkInstForNewValues(unsigned Inst,MachineBasicBlock::iterator pos)525b60736ecSDimitry Andric void checkInstForNewValues(unsigned Inst, MachineBasicBlock::iterator pos) {
526b60736ecSDimitry Andric auto MIt = UseBeforeDefs.find(Inst);
527b60736ecSDimitry Andric if (MIt == UseBeforeDefs.end())
528b60736ecSDimitry Andric return;
529b60736ecSDimitry Andric
530e3b55780SDimitry Andric // Map of values to the locations that store them for every value used by
531e3b55780SDimitry Andric // the variables that may have become available.
532e3b55780SDimitry Andric SmallDenseMap<ValueIDNum, LocationAndQuality> ValueToLoc;
533e3b55780SDimitry Andric
534e3b55780SDimitry Andric // Populate ValueToLoc with illegal default mappings for every value used by
535e3b55780SDimitry Andric // any UseBeforeDef variables for this instruction.
536b60736ecSDimitry Andric for (auto &Use : MIt->second) {
537ac9a064cSDimitry Andric if (!UseBeforeDefVariables.count(Use.VarID))
538b60736ecSDimitry Andric continue;
539b60736ecSDimitry Andric
540e3b55780SDimitry Andric for (DbgOp &Op : Use.Values) {
541e3b55780SDimitry Andric assert(!Op.isUndef() && "UseBeforeDef erroneously created for a "
542e3b55780SDimitry Andric "DbgValue with undef values.");
543e3b55780SDimitry Andric if (Op.IsConst)
544e3b55780SDimitry Andric continue;
545e3b55780SDimitry Andric
546e3b55780SDimitry Andric ValueToLoc.insert({Op.ID, LocationAndQuality()});
547e3b55780SDimitry Andric }
548e3b55780SDimitry Andric }
549e3b55780SDimitry Andric
550e3b55780SDimitry Andric // Exit early if we have no DbgValues to produce.
551e3b55780SDimitry Andric if (ValueToLoc.empty())
552e3b55780SDimitry Andric return;
553e3b55780SDimitry Andric
554e3b55780SDimitry Andric // Determine the best location for each desired value.
555e3b55780SDimitry Andric for (auto Location : MTracker->locations()) {
556e3b55780SDimitry Andric LocIdx Idx = Location.Idx;
557e3b55780SDimitry Andric ValueIDNum &LocValueID = Location.Value;
558e3b55780SDimitry Andric
559e3b55780SDimitry Andric // Is there a variable that wants a location for this value? If not, skip.
560e3b55780SDimitry Andric auto VIt = ValueToLoc.find(LocValueID);
561e3b55780SDimitry Andric if (VIt == ValueToLoc.end())
562e3b55780SDimitry Andric continue;
563e3b55780SDimitry Andric
564e3b55780SDimitry Andric auto &Previous = VIt->second;
565e3b55780SDimitry Andric // If this is the first location with that value, pick it. Otherwise,
566e3b55780SDimitry Andric // consider whether it's a "longer term" location.
567e3b55780SDimitry Andric std::optional<LocationQuality> ReplacementQuality =
568e3b55780SDimitry Andric getLocQualityIfBetter(Idx, Previous.getQuality());
569e3b55780SDimitry Andric if (ReplacementQuality)
570e3b55780SDimitry Andric Previous = LocationAndQuality(Idx, *ReplacementQuality);
571e3b55780SDimitry Andric }
572e3b55780SDimitry Andric
573e3b55780SDimitry Andric // Using the map of values to locations, produce a final set of values for
574e3b55780SDimitry Andric // this variable.
575e3b55780SDimitry Andric for (auto &Use : MIt->second) {
576ac9a064cSDimitry Andric if (!UseBeforeDefVariables.count(Use.VarID))
577e3b55780SDimitry Andric continue;
578e3b55780SDimitry Andric
579e3b55780SDimitry Andric SmallVector<ResolvedDbgOp> DbgOps;
580e3b55780SDimitry Andric
581e3b55780SDimitry Andric for (DbgOp &Op : Use.Values) {
582e3b55780SDimitry Andric if (Op.IsConst) {
583e3b55780SDimitry Andric DbgOps.push_back(Op.MO);
584e3b55780SDimitry Andric continue;
585e3b55780SDimitry Andric }
586e3b55780SDimitry Andric LocIdx NewLoc = ValueToLoc.find(Op.ID)->second.getLoc();
587e3b55780SDimitry Andric if (NewLoc.isIllegal())
588e3b55780SDimitry Andric break;
589e3b55780SDimitry Andric DbgOps.push_back(NewLoc);
590e3b55780SDimitry Andric }
591e3b55780SDimitry Andric
592e3b55780SDimitry Andric // If at least one value used by this debug value is no longer available,
593e3b55780SDimitry Andric // i.e. one of the values was killed before we finished defining all of
594e3b55780SDimitry Andric // the values used by this variable, discard.
595e3b55780SDimitry Andric if (DbgOps.size() != Use.Values.size())
596e3b55780SDimitry Andric continue;
597e3b55780SDimitry Andric
598e3b55780SDimitry Andric // Otherwise, we're good to go.
599ac9a064cSDimitry Andric auto &[Var, DILoc] = DVMap.lookupDVID(Use.VarID);
600ac9a064cSDimitry Andric PendingDbgValues.push_back(std::make_pair(
601ac9a064cSDimitry Andric Use.VarID, MTracker->emitLoc(DbgOps, Var, DILoc, Use.Properties)));
602b60736ecSDimitry Andric }
603b60736ecSDimitry Andric flushDbgValues(pos, nullptr);
604b60736ecSDimitry Andric }
605b60736ecSDimitry Andric
606b60736ecSDimitry Andric /// Helper to move created DBG_VALUEs into Transfers collection.
flushDbgValues(MachineBasicBlock::iterator Pos,MachineBasicBlock * MBB)607b60736ecSDimitry Andric void flushDbgValues(MachineBasicBlock::iterator Pos, MachineBasicBlock *MBB) {
608344a3780SDimitry Andric if (PendingDbgValues.size() == 0)
609344a3780SDimitry Andric return;
610344a3780SDimitry Andric
611344a3780SDimitry Andric // Pick out the instruction start position.
612344a3780SDimitry Andric MachineBasicBlock::instr_iterator BundleStart;
613344a3780SDimitry Andric if (MBB && Pos == MBB->begin())
614344a3780SDimitry Andric BundleStart = MBB->instr_begin();
615344a3780SDimitry Andric else
616344a3780SDimitry Andric BundleStart = getBundleStart(Pos->getIterator());
617344a3780SDimitry Andric
618344a3780SDimitry Andric Transfers.push_back({BundleStart, MBB, PendingDbgValues});
619b60736ecSDimitry Andric PendingDbgValues.clear();
620b60736ecSDimitry Andric }
621344a3780SDimitry Andric
isEntryValueVariable(const DebugVariable & Var,const DIExpression * Expr) const622344a3780SDimitry Andric bool isEntryValueVariable(const DebugVariable &Var,
623344a3780SDimitry Andric const DIExpression *Expr) const {
624344a3780SDimitry Andric if (!Var.getVariable()->isParameter())
625344a3780SDimitry Andric return false;
626344a3780SDimitry Andric
627344a3780SDimitry Andric if (Var.getInlinedAt())
628344a3780SDimitry Andric return false;
629344a3780SDimitry Andric
6307fa27ce4SDimitry Andric if (Expr->getNumElements() > 0 && !Expr->isDeref())
631344a3780SDimitry Andric return false;
632344a3780SDimitry Andric
633344a3780SDimitry Andric return true;
634344a3780SDimitry Andric }
635344a3780SDimitry Andric
isEntryValueValue(const ValueIDNum & Val) const636344a3780SDimitry Andric bool isEntryValueValue(const ValueIDNum &Val) const {
637344a3780SDimitry Andric // Must be in entry block (block number zero), and be a PHI / live-in value.
638344a3780SDimitry Andric if (Val.getBlock() || !Val.isPHI())
639344a3780SDimitry Andric return false;
640344a3780SDimitry Andric
641344a3780SDimitry Andric // Entry values must enter in a register.
642344a3780SDimitry Andric if (MTracker->isSpill(Val.getLoc()))
643344a3780SDimitry Andric return false;
644344a3780SDimitry Andric
645344a3780SDimitry Andric Register SP = TLI->getStackPointerRegisterToSaveRestore();
646344a3780SDimitry Andric Register FP = TRI.getFrameRegister(MF);
647344a3780SDimitry Andric Register Reg = MTracker->LocIdxToLocID[Val.getLoc()];
648344a3780SDimitry Andric return Reg != SP && Reg != FP;
649344a3780SDimitry Andric }
650344a3780SDimitry Andric
recoverAsEntryValue(DebugVariableID VarID,const DbgValueProperties & Prop,const ValueIDNum & Num)651ac9a064cSDimitry Andric bool recoverAsEntryValue(DebugVariableID VarID,
6526f8fc217SDimitry Andric const DbgValueProperties &Prop,
653344a3780SDimitry Andric const ValueIDNum &Num) {
654344a3780SDimitry Andric // Is this variable location a candidate to be an entry value. First,
655344a3780SDimitry Andric // should we be trying this at all?
656344a3780SDimitry Andric if (!ShouldEmitDebugEntryValues)
657344a3780SDimitry Andric return false;
658344a3780SDimitry Andric
659e3b55780SDimitry Andric const DIExpression *DIExpr = Prop.DIExpr;
660e3b55780SDimitry Andric
661e3b55780SDimitry Andric // We don't currently emit entry values for DBG_VALUE_LISTs.
662e3b55780SDimitry Andric if (Prop.IsVariadic) {
663e3b55780SDimitry Andric // If this debug value can be converted to be non-variadic, then do so;
664e3b55780SDimitry Andric // otherwise give up.
665e3b55780SDimitry Andric auto NonVariadicExpression =
666e3b55780SDimitry Andric DIExpression::convertToNonVariadicExpression(DIExpr);
667e3b55780SDimitry Andric if (!NonVariadicExpression)
668e3b55780SDimitry Andric return false;
669e3b55780SDimitry Andric DIExpr = *NonVariadicExpression;
670e3b55780SDimitry Andric }
671e3b55780SDimitry Andric
672ac9a064cSDimitry Andric auto &[Var, DILoc] = DVMap.lookupDVID(VarID);
673ac9a064cSDimitry Andric
674344a3780SDimitry Andric // Is the variable appropriate for entry values (i.e., is a parameter).
675e3b55780SDimitry Andric if (!isEntryValueVariable(Var, DIExpr))
676344a3780SDimitry Andric return false;
677344a3780SDimitry Andric
678344a3780SDimitry Andric // Is the value assigned to this variable still the entry value?
679344a3780SDimitry Andric if (!isEntryValueValue(Num))
680344a3780SDimitry Andric return false;
681344a3780SDimitry Andric
682344a3780SDimitry Andric // Emit a variable location using an entry value expression.
683344a3780SDimitry Andric DIExpression *NewExpr =
684e3b55780SDimitry Andric DIExpression::prepend(DIExpr, DIExpression::EntryValue);
685344a3780SDimitry Andric Register Reg = MTracker->LocIdxToLocID[Num.getLoc()];
686344a3780SDimitry Andric MachineOperand MO = MachineOperand::CreateReg(Reg, false);
687ac9a064cSDimitry Andric PendingDbgValues.push_back(std::make_pair(
688ac9a064cSDimitry Andric VarID, &*emitMOLoc(MO, Var, {NewExpr, Prop.Indirect, false})));
689344a3780SDimitry Andric return true;
690b60736ecSDimitry Andric }
691b60736ecSDimitry Andric
692b60736ecSDimitry Andric /// Change a variable value after encountering a DBG_VALUE inside a block.
redefVar(const MachineInstr & MI)693b60736ecSDimitry Andric void redefVar(const MachineInstr &MI) {
694b60736ecSDimitry Andric DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
695b60736ecSDimitry Andric MI.getDebugLoc()->getInlinedAt());
696b60736ecSDimitry Andric DbgValueProperties Properties(MI);
697ac9a064cSDimitry Andric DebugVariableID VarID = DVMap.getDVID(Var);
698b60736ecSDimitry Andric
699b60736ecSDimitry Andric // Ignore non-register locations, we don't transfer those.
700e3b55780SDimitry Andric if (MI.isUndefDebugValue() ||
701e3b55780SDimitry Andric all_of(MI.debug_operands(),
702e3b55780SDimitry Andric [](const MachineOperand &MO) { return !MO.isReg(); })) {
703ac9a064cSDimitry Andric auto It = ActiveVLocs.find(VarID);
704b60736ecSDimitry Andric if (It != ActiveVLocs.end()) {
705e3b55780SDimitry Andric for (LocIdx Loc : It->second.loc_indices())
706ac9a064cSDimitry Andric ActiveMLocs[Loc].erase(VarID);
707b60736ecSDimitry Andric ActiveVLocs.erase(It);
708b60736ecSDimitry Andric }
709b60736ecSDimitry Andric // Any use-before-defs no longer apply.
710ac9a064cSDimitry Andric UseBeforeDefVariables.erase(VarID);
711b60736ecSDimitry Andric return;
712b60736ecSDimitry Andric }
713b60736ecSDimitry Andric
714e3b55780SDimitry Andric SmallVector<ResolvedDbgOp> NewLocs;
715e3b55780SDimitry Andric for (const MachineOperand &MO : MI.debug_operands()) {
716e3b55780SDimitry Andric if (MO.isReg()) {
717e3b55780SDimitry Andric // Any undef regs have already been filtered out above.
718b60736ecSDimitry Andric Register Reg = MO.getReg();
719b60736ecSDimitry Andric LocIdx NewLoc = MTracker->getRegMLoc(Reg);
720e3b55780SDimitry Andric NewLocs.push_back(NewLoc);
721e3b55780SDimitry Andric } else {
722e3b55780SDimitry Andric NewLocs.push_back(MO);
723e3b55780SDimitry Andric }
724e3b55780SDimitry Andric }
725e3b55780SDimitry Andric
726e3b55780SDimitry Andric redefVar(MI, Properties, NewLocs);
727b60736ecSDimitry Andric }
728b60736ecSDimitry Andric
729b60736ecSDimitry Andric /// Handle a change in variable location within a block. Terminate the
730b60736ecSDimitry Andric /// variables current location, and record the value it now refers to, so
731b60736ecSDimitry Andric /// that we can detect location transfers later on.
redefVar(const MachineInstr & MI,const DbgValueProperties & Properties,SmallVectorImpl<ResolvedDbgOp> & NewLocs)732b60736ecSDimitry Andric void redefVar(const MachineInstr &MI, const DbgValueProperties &Properties,
733e3b55780SDimitry Andric SmallVectorImpl<ResolvedDbgOp> &NewLocs) {
734b60736ecSDimitry Andric DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
735b60736ecSDimitry Andric MI.getDebugLoc()->getInlinedAt());
736ac9a064cSDimitry Andric DebugVariableID VarID = DVMap.getDVID(Var);
737b60736ecSDimitry Andric // Any use-before-defs no longer apply.
738ac9a064cSDimitry Andric UseBeforeDefVariables.erase(VarID);
739b60736ecSDimitry Andric
740e3b55780SDimitry Andric // Erase any previous location.
741ac9a064cSDimitry Andric auto It = ActiveVLocs.find(VarID);
742e3b55780SDimitry Andric if (It != ActiveVLocs.end()) {
743e3b55780SDimitry Andric for (LocIdx Loc : It->second.loc_indices())
744ac9a064cSDimitry Andric ActiveMLocs[Loc].erase(VarID);
745e3b55780SDimitry Andric }
746b60736ecSDimitry Andric
747b60736ecSDimitry Andric // If there _is_ no new location, all we had to do was erase.
748e3b55780SDimitry Andric if (NewLocs.empty()) {
749e3b55780SDimitry Andric if (It != ActiveVLocs.end())
750e3b55780SDimitry Andric ActiveVLocs.erase(It);
751b60736ecSDimitry Andric return;
752e3b55780SDimitry Andric }
753b60736ecSDimitry Andric
754ac9a064cSDimitry Andric SmallVector<std::pair<LocIdx, DebugVariableID>> LostMLocs;
755e3b55780SDimitry Andric for (ResolvedDbgOp &Op : NewLocs) {
756e3b55780SDimitry Andric if (Op.IsConst)
757e3b55780SDimitry Andric continue;
758e3b55780SDimitry Andric
759e3b55780SDimitry Andric LocIdx NewLoc = Op.Loc;
760e3b55780SDimitry Andric
761e3b55780SDimitry Andric // Check whether our local copy of values-by-location in #VarLocs is out
762e3b55780SDimitry Andric // of date. Wipe old tracking data for the location if it's been clobbered
763e3b55780SDimitry Andric // in the meantime.
764c0981da4SDimitry Andric if (MTracker->readMLoc(NewLoc) != VarLocs[NewLoc.asU64()]) {
7654b4fe385SDimitry Andric for (const auto &P : ActiveMLocs[NewLoc]) {
766e3b55780SDimitry Andric auto LostVLocIt = ActiveVLocs.find(P);
767e3b55780SDimitry Andric if (LostVLocIt != ActiveVLocs.end()) {
768e3b55780SDimitry Andric for (LocIdx Loc : LostVLocIt->second.loc_indices()) {
769e3b55780SDimitry Andric // Every active variable mapping for NewLoc will be cleared, no
770e3b55780SDimitry Andric // need to track individual variables.
771e3b55780SDimitry Andric if (Loc == NewLoc)
772e3b55780SDimitry Andric continue;
773e3b55780SDimitry Andric LostMLocs.emplace_back(Loc, P);
774e3b55780SDimitry Andric }
775e3b55780SDimitry Andric }
776b60736ecSDimitry Andric ActiveVLocs.erase(P);
777b60736ecSDimitry Andric }
778e3b55780SDimitry Andric for (const auto &LostMLoc : LostMLocs)
779e3b55780SDimitry Andric ActiveMLocs[LostMLoc.first].erase(LostMLoc.second);
780e3b55780SDimitry Andric LostMLocs.clear();
781ac9a064cSDimitry Andric It = ActiveVLocs.find(VarID);
782b60736ecSDimitry Andric ActiveMLocs[NewLoc.asU64()].clear();
783c0981da4SDimitry Andric VarLocs[NewLoc.asU64()] = MTracker->readMLoc(NewLoc);
784b60736ecSDimitry Andric }
785b60736ecSDimitry Andric
786ac9a064cSDimitry Andric ActiveMLocs[NewLoc].insert(VarID);
787e3b55780SDimitry Andric }
788e3b55780SDimitry Andric
789b60736ecSDimitry Andric if (It == ActiveVLocs.end()) {
790b60736ecSDimitry Andric ActiveVLocs.insert(
791ac9a064cSDimitry Andric std::make_pair(VarID, ResolvedDbgValue(NewLocs, Properties)));
792b60736ecSDimitry Andric } else {
793e3b55780SDimitry Andric It->second.Ops.assign(NewLocs);
794b60736ecSDimitry Andric It->second.Properties = Properties;
795b60736ecSDimitry Andric }
796b60736ecSDimitry Andric }
797b60736ecSDimitry Andric
798344a3780SDimitry Andric /// Account for a location \p mloc being clobbered. Examine the variable
799344a3780SDimitry Andric /// locations that will be terminated: and try to recover them by using
800344a3780SDimitry Andric /// another location. Optionally, given \p MakeUndef, emit a DBG_VALUE to
801344a3780SDimitry Andric /// explicitly terminate a location if it can't be recovered.
clobberMloc(LocIdx MLoc,MachineBasicBlock::iterator Pos,bool MakeUndef=true)802344a3780SDimitry Andric void clobberMloc(LocIdx MLoc, MachineBasicBlock::iterator Pos,
803344a3780SDimitry Andric bool MakeUndef = true) {
804b60736ecSDimitry Andric auto ActiveMLocIt = ActiveMLocs.find(MLoc);
805b60736ecSDimitry Andric if (ActiveMLocIt == ActiveMLocs.end())
806b60736ecSDimitry Andric return;
807b60736ecSDimitry Andric
808344a3780SDimitry Andric // What was the old variable value?
809344a3780SDimitry Andric ValueIDNum OldValue = VarLocs[MLoc.asU64()];
8101f917f69SDimitry Andric clobberMloc(MLoc, OldValue, Pos, MakeUndef);
8111f917f69SDimitry Andric }
8121f917f69SDimitry Andric /// Overload that takes an explicit value \p OldValue for when the value in
8131f917f69SDimitry Andric /// \p MLoc has changed and the TransferTracker's locations have not been
8141f917f69SDimitry Andric /// updated yet.
clobberMloc(LocIdx MLoc,ValueIDNum OldValue,MachineBasicBlock::iterator Pos,bool MakeUndef=true)8151f917f69SDimitry Andric void clobberMloc(LocIdx MLoc, ValueIDNum OldValue,
8161f917f69SDimitry Andric MachineBasicBlock::iterator Pos, bool MakeUndef = true) {
8171f917f69SDimitry Andric auto ActiveMLocIt = ActiveMLocs.find(MLoc);
8181f917f69SDimitry Andric if (ActiveMLocIt == ActiveMLocs.end())
8191f917f69SDimitry Andric return;
8201f917f69SDimitry Andric
821b60736ecSDimitry Andric VarLocs[MLoc.asU64()] = ValueIDNum::EmptyValue;
822b60736ecSDimitry Andric
823344a3780SDimitry Andric // Examine the remaining variable locations: if we can find the same value
824344a3780SDimitry Andric // again, we can recover the location.
825e3b55780SDimitry Andric std::optional<LocIdx> NewLoc;
826344a3780SDimitry Andric for (auto Loc : MTracker->locations())
827344a3780SDimitry Andric if (Loc.Value == OldValue)
828344a3780SDimitry Andric NewLoc = Loc.Idx;
829344a3780SDimitry Andric
830344a3780SDimitry Andric // If there is no location, and we weren't asked to make the variable
831344a3780SDimitry Andric // explicitly undef, then stop here.
832344a3780SDimitry Andric if (!NewLoc && !MakeUndef) {
833344a3780SDimitry Andric // Try and recover a few more locations with entry values.
834ac9a064cSDimitry Andric for (DebugVariableID VarID : ActiveMLocIt->second) {
835ac9a064cSDimitry Andric auto &Prop = ActiveVLocs.find(VarID)->second.Properties;
836ac9a064cSDimitry Andric recoverAsEntryValue(VarID, Prop, OldValue);
837344a3780SDimitry Andric }
838344a3780SDimitry Andric flushDbgValues(Pos, nullptr);
839344a3780SDimitry Andric return;
840344a3780SDimitry Andric }
841344a3780SDimitry Andric
842344a3780SDimitry Andric // Examine all the variables based on this location.
843ac9a064cSDimitry Andric DenseSet<DebugVariableID> NewMLocs;
844e3b55780SDimitry Andric // If no new location has been found, every variable that depends on this
845e3b55780SDimitry Andric // MLoc is dead, so end their existing MLoc->Var mappings as well.
846ac9a064cSDimitry Andric SmallVector<std::pair<LocIdx, DebugVariableID>> LostMLocs;
847ac9a064cSDimitry Andric for (DebugVariableID VarID : ActiveMLocIt->second) {
848ac9a064cSDimitry Andric auto ActiveVLocIt = ActiveVLocs.find(VarID);
849344a3780SDimitry Andric // Re-state the variable location: if there's no replacement then NewLoc
850e3b55780SDimitry Andric // is std::nullopt and a $noreg DBG_VALUE will be created. Otherwise, a
851e3b55780SDimitry Andric // DBG_VALUE identifying the alternative location will be emitted.
852f65dcba8SDimitry Andric const DbgValueProperties &Properties = ActiveVLocIt->second.Properties;
853e3b55780SDimitry Andric
854e3b55780SDimitry Andric // Produce the new list of debug ops - an empty list if no new location
855e3b55780SDimitry Andric // was found, or the existing list with the substitution MLoc -> NewLoc
856e3b55780SDimitry Andric // otherwise.
857e3b55780SDimitry Andric SmallVector<ResolvedDbgOp> DbgOps;
858e3b55780SDimitry Andric if (NewLoc) {
859e3b55780SDimitry Andric ResolvedDbgOp OldOp(MLoc);
860e3b55780SDimitry Andric ResolvedDbgOp NewOp(*NewLoc);
861e3b55780SDimitry Andric // Insert illegal ops to overwrite afterwards.
862e3b55780SDimitry Andric DbgOps.insert(DbgOps.begin(), ActiveVLocIt->second.Ops.size(),
863e3b55780SDimitry Andric ResolvedDbgOp(LocIdx::MakeIllegalLoc()));
864e3b55780SDimitry Andric replace_copy(ActiveVLocIt->second.Ops, DbgOps.begin(), OldOp, NewOp);
865e3b55780SDimitry Andric }
866e3b55780SDimitry Andric
867ac9a064cSDimitry Andric auto &[Var, DILoc] = DVMap.lookupDVID(VarID);
868ac9a064cSDimitry Andric PendingDbgValues.push_back(std::make_pair(
869ac9a064cSDimitry Andric VarID, &*MTracker->emitLoc(DbgOps, Var, DILoc, Properties)));
870344a3780SDimitry Andric
871344a3780SDimitry Andric // Update machine locations <=> variable locations maps. Defer updating
872e3b55780SDimitry Andric // ActiveMLocs to avoid invalidating the ActiveMLocIt iterator.
873344a3780SDimitry Andric if (!NewLoc) {
874e3b55780SDimitry Andric for (LocIdx Loc : ActiveVLocIt->second.loc_indices()) {
875e3b55780SDimitry Andric if (Loc != MLoc)
876ac9a064cSDimitry Andric LostMLocs.emplace_back(Loc, VarID);
877e3b55780SDimitry Andric }
878b60736ecSDimitry Andric ActiveVLocs.erase(ActiveVLocIt);
879344a3780SDimitry Andric } else {
880e3b55780SDimitry Andric ActiveVLocIt->second.Ops = DbgOps;
881ac9a064cSDimitry Andric NewMLocs.insert(VarID);
882b60736ecSDimitry Andric }
883344a3780SDimitry Andric }
884344a3780SDimitry Andric
885e3b55780SDimitry Andric // Remove variables from ActiveMLocs if they no longer use any other MLocs
886e3b55780SDimitry Andric // due to being killed by this clobber.
887e3b55780SDimitry Andric for (auto &LocVarIt : LostMLocs) {
888e3b55780SDimitry Andric auto LostMLocIt = ActiveMLocs.find(LocVarIt.first);
889e3b55780SDimitry Andric assert(LostMLocIt != ActiveMLocs.end() &&
890e3b55780SDimitry Andric "Variable was using this MLoc, but ActiveMLocs[MLoc] has no "
891e3b55780SDimitry Andric "entries?");
892e3b55780SDimitry Andric LostMLocIt->second.erase(LocVarIt.second);
893e3b55780SDimitry Andric }
894344a3780SDimitry Andric
895344a3780SDimitry Andric // We lazily track what locations have which values; if we've found a new
896344a3780SDimitry Andric // location for the clobbered value, remember it.
897344a3780SDimitry Andric if (NewLoc)
898344a3780SDimitry Andric VarLocs[NewLoc->asU64()] = OldValue;
899344a3780SDimitry Andric
900b60736ecSDimitry Andric flushDbgValues(Pos, nullptr);
901b60736ecSDimitry Andric
902e3b55780SDimitry Andric // Commit ActiveMLoc changes.
903b60736ecSDimitry Andric ActiveMLocIt->second.clear();
904e3b55780SDimitry Andric if (!NewMLocs.empty())
905ac9a064cSDimitry Andric for (DebugVariableID VarID : NewMLocs)
906ac9a064cSDimitry Andric ActiveMLocs[*NewLoc].insert(VarID);
907b60736ecSDimitry Andric }
908b60736ecSDimitry Andric
909b60736ecSDimitry Andric /// Transfer variables based on \p Src to be based on \p Dst. This handles
910b60736ecSDimitry Andric /// both register copies as well as spills and restores. Creates DBG_VALUEs
911b60736ecSDimitry Andric /// describing the movement.
transferMlocs(LocIdx Src,LocIdx Dst,MachineBasicBlock::iterator Pos)912b60736ecSDimitry Andric void transferMlocs(LocIdx Src, LocIdx Dst, MachineBasicBlock::iterator Pos) {
913b60736ecSDimitry Andric // Does Src still contain the value num we expect? If not, it's been
914b60736ecSDimitry Andric // clobbered in the meantime, and our variable locations are stale.
915c0981da4SDimitry Andric if (VarLocs[Src.asU64()] != MTracker->readMLoc(Src))
916b60736ecSDimitry Andric return;
917b60736ecSDimitry Andric
918b60736ecSDimitry Andric // assert(ActiveMLocs[Dst].size() == 0);
919b60736ecSDimitry Andric //^^^ Legitimate scenario on account of un-clobbered slot being assigned to?
920c0981da4SDimitry Andric
921c0981da4SDimitry Andric // Move set of active variables from one location to another.
922c0981da4SDimitry Andric auto MovingVars = ActiveMLocs[Src];
923e3b55780SDimitry Andric ActiveMLocs[Dst].insert(MovingVars.begin(), MovingVars.end());
924b60736ecSDimitry Andric VarLocs[Dst.asU64()] = VarLocs[Src.asU64()];
925b60736ecSDimitry Andric
926b60736ecSDimitry Andric // For each variable based on Src; create a location at Dst.
927e3b55780SDimitry Andric ResolvedDbgOp SrcOp(Src);
928e3b55780SDimitry Andric ResolvedDbgOp DstOp(Dst);
929ac9a064cSDimitry Andric for (DebugVariableID VarID : MovingVars) {
930ac9a064cSDimitry Andric auto ActiveVLocIt = ActiveVLocs.find(VarID);
931b60736ecSDimitry Andric assert(ActiveVLocIt != ActiveVLocs.end());
932b60736ecSDimitry Andric
933e3b55780SDimitry Andric // Update all instances of Src in the variable's tracked values to Dst.
934e3b55780SDimitry Andric std::replace(ActiveVLocIt->second.Ops.begin(),
935e3b55780SDimitry Andric ActiveVLocIt->second.Ops.end(), SrcOp, DstOp);
936e3b55780SDimitry Andric
937ac9a064cSDimitry Andric auto &[Var, DILoc] = DVMap.lookupDVID(VarID);
938ac9a064cSDimitry Andric MachineInstr *MI = MTracker->emitLoc(ActiveVLocIt->second.Ops, Var, DILoc,
939e3b55780SDimitry Andric ActiveVLocIt->second.Properties);
940ac9a064cSDimitry Andric PendingDbgValues.push_back(std::make_pair(VarID, MI));
941b60736ecSDimitry Andric }
942b60736ecSDimitry Andric ActiveMLocs[Src].clear();
943b60736ecSDimitry Andric flushDbgValues(Pos, nullptr);
944b60736ecSDimitry Andric
945b60736ecSDimitry Andric // XXX XXX XXX "pretend to be old LDV" means dropping all tracking data
946b60736ecSDimitry Andric // about the old location.
947b60736ecSDimitry Andric if (EmulateOldLDV)
948b60736ecSDimitry Andric VarLocs[Src.asU64()] = ValueIDNum::EmptyValue;
949b60736ecSDimitry Andric }
950b60736ecSDimitry Andric
emitMOLoc(const MachineOperand & MO,const DebugVariable & Var,const DbgValueProperties & Properties)951b60736ecSDimitry Andric MachineInstrBuilder emitMOLoc(const MachineOperand &MO,
952b60736ecSDimitry Andric const DebugVariable &Var,
953b60736ecSDimitry Andric const DbgValueProperties &Properties) {
954b60736ecSDimitry Andric DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0,
955b60736ecSDimitry Andric Var.getVariable()->getScope(),
956b60736ecSDimitry Andric const_cast<DILocation *>(Var.getInlinedAt()));
957b60736ecSDimitry Andric auto MIB = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE));
958b60736ecSDimitry Andric MIB.add(MO);
959b60736ecSDimitry Andric if (Properties.Indirect)
960b60736ecSDimitry Andric MIB.addImm(0);
961b60736ecSDimitry Andric else
962b60736ecSDimitry Andric MIB.addReg(0);
963b60736ecSDimitry Andric MIB.addMetadata(Var.getVariable());
964b60736ecSDimitry Andric MIB.addMetadata(Properties.DIExpr);
965b60736ecSDimitry Andric return MIB;
966b60736ecSDimitry Andric }
967b60736ecSDimitry Andric };
968b60736ecSDimitry Andric
969c0981da4SDimitry Andric //===----------------------------------------------------------------------===//
970c0981da4SDimitry Andric // Implementation
971c0981da4SDimitry Andric //===----------------------------------------------------------------------===//
972b60736ecSDimitry Andric
973c0981da4SDimitry Andric ValueIDNum ValueIDNum::EmptyValue = {UINT_MAX, UINT_MAX, UINT_MAX};
974c0981da4SDimitry Andric ValueIDNum ValueIDNum::TombstoneValue = {UINT_MAX, UINT_MAX, UINT_MAX - 1};
975b60736ecSDimitry Andric
976c0981da4SDimitry Andric #ifndef NDEBUG
dump(const MLocTracker * MTrack) const977e3b55780SDimitry Andric void ResolvedDbgOp::dump(const MLocTracker *MTrack) const {
978e3b55780SDimitry Andric if (IsConst) {
979e3b55780SDimitry Andric dbgs() << MO;
980c0981da4SDimitry Andric } else {
981e3b55780SDimitry Andric dbgs() << MTrack->LocIdxToName(Loc);
982e3b55780SDimitry Andric }
983e3b55780SDimitry Andric }
dump(const MLocTracker * MTrack) const984e3b55780SDimitry Andric void DbgOp::dump(const MLocTracker *MTrack) const {
985e3b55780SDimitry Andric if (IsConst) {
986e3b55780SDimitry Andric dbgs() << MO;
987e3b55780SDimitry Andric } else if (!isUndef()) {
988c0981da4SDimitry Andric dbgs() << MTrack->IDAsString(ID);
989c0981da4SDimitry Andric }
990e3b55780SDimitry Andric }
dump(const MLocTracker * MTrack,const DbgOpIDMap * OpStore) const991e3b55780SDimitry Andric void DbgOpID::dump(const MLocTracker *MTrack, const DbgOpIDMap *OpStore) const {
992e3b55780SDimitry Andric if (!OpStore) {
993e3b55780SDimitry Andric dbgs() << "ID(" << asU32() << ")";
994e3b55780SDimitry Andric } else {
995e3b55780SDimitry Andric OpStore->find(*this).dump(MTrack);
996e3b55780SDimitry Andric }
997e3b55780SDimitry Andric }
dump(const MLocTracker * MTrack,const DbgOpIDMap * OpStore) const998e3b55780SDimitry Andric void DbgValue::dump(const MLocTracker *MTrack,
999e3b55780SDimitry Andric const DbgOpIDMap *OpStore) const {
1000e3b55780SDimitry Andric if (Kind == NoVal) {
1001e3b55780SDimitry Andric dbgs() << "NoVal(" << BlockNo << ")";
1002e3b55780SDimitry Andric } else if (Kind == VPHI || Kind == Def) {
1003e3b55780SDimitry Andric if (Kind == VPHI)
1004e3b55780SDimitry Andric dbgs() << "VPHI(" << BlockNo << ",";
1005e3b55780SDimitry Andric else
1006e3b55780SDimitry Andric dbgs() << "Def(";
1007e3b55780SDimitry Andric for (unsigned Idx = 0; Idx < getDbgOpIDs().size(); ++Idx) {
1008e3b55780SDimitry Andric getDbgOpID(Idx).dump(MTrack, OpStore);
1009e3b55780SDimitry Andric if (Idx != 0)
1010e3b55780SDimitry Andric dbgs() << ",";
1011e3b55780SDimitry Andric }
1012e3b55780SDimitry Andric dbgs() << ")";
1013e3b55780SDimitry Andric }
1014c0981da4SDimitry Andric if (Properties.Indirect)
1015c0981da4SDimitry Andric dbgs() << " indir";
1016c0981da4SDimitry Andric if (Properties.DIExpr)
1017c0981da4SDimitry Andric dbgs() << " " << *Properties.DIExpr;
1018c0981da4SDimitry Andric }
1019c0981da4SDimitry Andric #endif
1020b60736ecSDimitry Andric
MLocTracker(MachineFunction & MF,const TargetInstrInfo & TII,const TargetRegisterInfo & TRI,const TargetLowering & TLI)1021c0981da4SDimitry Andric MLocTracker::MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII,
1022c0981da4SDimitry Andric const TargetRegisterInfo &TRI,
1023c0981da4SDimitry Andric const TargetLowering &TLI)
1024c0981da4SDimitry Andric : MF(MF), TII(TII), TRI(TRI), TLI(TLI),
1025c0981da4SDimitry Andric LocIdxToIDNum(ValueIDNum::EmptyValue), LocIdxToLocID(0) {
1026c0981da4SDimitry Andric NumRegs = TRI.getNumRegs();
1027c0981da4SDimitry Andric reset();
1028c0981da4SDimitry Andric LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc());
1029c0981da4SDimitry Andric assert(NumRegs < (1u << NUM_LOC_BITS)); // Detect bit packing failure
1030b60736ecSDimitry Andric
1031c0981da4SDimitry Andric // Always track SP. This avoids the implicit clobbering caused by regmasks
1032c0981da4SDimitry Andric // from affectings its values. (LiveDebugValues disbelieves calls and
1033c0981da4SDimitry Andric // regmasks that claim to clobber SP).
1034c0981da4SDimitry Andric Register SP = TLI.getStackPointerRegisterToSaveRestore();
1035c0981da4SDimitry Andric if (SP) {
1036c0981da4SDimitry Andric unsigned ID = getLocID(SP);
1037c0981da4SDimitry Andric (void)lookupOrTrackRegister(ID);
1038b60736ecSDimitry Andric
1039c0981da4SDimitry Andric for (MCRegAliasIterator RAI(SP, &TRI, true); RAI.isValid(); ++RAI)
1040c0981da4SDimitry Andric SPAliases.insert(*RAI);
1041c0981da4SDimitry Andric }
1042b60736ecSDimitry Andric
1043c0981da4SDimitry Andric // Build some common stack positions -- full registers being spilt to the
1044c0981da4SDimitry Andric // stack.
1045c0981da4SDimitry Andric StackSlotIdxes.insert({{8, 0}, 0});
1046c0981da4SDimitry Andric StackSlotIdxes.insert({{16, 0}, 1});
1047c0981da4SDimitry Andric StackSlotIdxes.insert({{32, 0}, 2});
1048c0981da4SDimitry Andric StackSlotIdxes.insert({{64, 0}, 3});
1049c0981da4SDimitry Andric StackSlotIdxes.insert({{128, 0}, 4});
1050c0981da4SDimitry Andric StackSlotIdxes.insert({{256, 0}, 5});
1051c0981da4SDimitry Andric StackSlotIdxes.insert({{512, 0}, 6});
1052b60736ecSDimitry Andric
1053c0981da4SDimitry Andric // Traverse all the subregister idxes, and ensure there's an index for them.
1054c0981da4SDimitry Andric // Duplicates are no problem: we're interested in their position in the
1055c0981da4SDimitry Andric // stack slot, we don't want to type the slot.
1056c0981da4SDimitry Andric for (unsigned int I = 1; I < TRI.getNumSubRegIndices(); ++I) {
1057c0981da4SDimitry Andric unsigned Size = TRI.getSubRegIdxSize(I);
1058c0981da4SDimitry Andric unsigned Offs = TRI.getSubRegIdxOffset(I);
1059c0981da4SDimitry Andric unsigned Idx = StackSlotIdxes.size();
1060b60736ecSDimitry Andric
1061c0981da4SDimitry Andric // Some subregs have -1, -2 and so forth fed into their fields, to mean
1062c0981da4SDimitry Andric // special backend things. Ignore those.
1063c0981da4SDimitry Andric if (Size > 60000 || Offs > 60000)
1064c0981da4SDimitry Andric continue;
1065b60736ecSDimitry Andric
1066c0981da4SDimitry Andric StackSlotIdxes.insert({{Size, Offs}, Idx});
1067c0981da4SDimitry Andric }
1068b60736ecSDimitry Andric
1069145449b1SDimitry Andric // There may also be strange register class sizes (think x86 fp80s).
1070145449b1SDimitry Andric for (const TargetRegisterClass *RC : TRI.regclasses()) {
1071145449b1SDimitry Andric unsigned Size = TRI.getRegSizeInBits(*RC);
1072145449b1SDimitry Andric
1073145449b1SDimitry Andric // We might see special reserved values as sizes, and classes for other
1074145449b1SDimitry Andric // stuff the machine tries to model. If it's more than 512 bits, then it
1075145449b1SDimitry Andric // is very unlikely to be a register than can be spilt.
1076145449b1SDimitry Andric if (Size > 512)
1077145449b1SDimitry Andric continue;
1078145449b1SDimitry Andric
1079145449b1SDimitry Andric unsigned Idx = StackSlotIdxes.size();
1080145449b1SDimitry Andric StackSlotIdxes.insert({{Size, 0}, Idx});
1081145449b1SDimitry Andric }
1082145449b1SDimitry Andric
1083c0981da4SDimitry Andric for (auto &Idx : StackSlotIdxes)
1084c0981da4SDimitry Andric StackIdxesToPos[Idx.second] = Idx.first;
1085b60736ecSDimitry Andric
1086c0981da4SDimitry Andric NumSlotIdxes = StackSlotIdxes.size();
1087c0981da4SDimitry Andric }
1088b60736ecSDimitry Andric
trackRegister(unsigned ID)1089c0981da4SDimitry Andric LocIdx MLocTracker::trackRegister(unsigned ID) {
1090c0981da4SDimitry Andric assert(ID != 0);
1091c0981da4SDimitry Andric LocIdx NewIdx = LocIdx(LocIdxToIDNum.size());
1092c0981da4SDimitry Andric LocIdxToIDNum.grow(NewIdx);
1093c0981da4SDimitry Andric LocIdxToLocID.grow(NewIdx);
1094b60736ecSDimitry Andric
1095c0981da4SDimitry Andric // Default: it's an mphi.
1096c0981da4SDimitry Andric ValueIDNum ValNum = {CurBB, 0, NewIdx};
1097c0981da4SDimitry Andric // Was this reg ever touched by a regmask?
1098c0981da4SDimitry Andric for (const auto &MaskPair : reverse(Masks)) {
1099c0981da4SDimitry Andric if (MaskPair.first->clobbersPhysReg(ID)) {
1100c0981da4SDimitry Andric // There was an earlier def we skipped.
1101c0981da4SDimitry Andric ValNum = {CurBB, MaskPair.second, NewIdx};
1102c0981da4SDimitry Andric break;
1103c0981da4SDimitry Andric }
1104c0981da4SDimitry Andric }
1105b60736ecSDimitry Andric
1106c0981da4SDimitry Andric LocIdxToIDNum[NewIdx] = ValNum;
1107c0981da4SDimitry Andric LocIdxToLocID[NewIdx] = ID;
1108c0981da4SDimitry Andric return NewIdx;
1109c0981da4SDimitry Andric }
1110b60736ecSDimitry Andric
writeRegMask(const MachineOperand * MO,unsigned CurBB,unsigned InstID)1111c0981da4SDimitry Andric void MLocTracker::writeRegMask(const MachineOperand *MO, unsigned CurBB,
1112c0981da4SDimitry Andric unsigned InstID) {
1113c0981da4SDimitry Andric // Def any register we track have that isn't preserved. The regmask
1114c0981da4SDimitry Andric // terminates the liveness of a register, meaning its value can't be
1115c0981da4SDimitry Andric // relied upon -- we represent this by giving it a new value.
1116c0981da4SDimitry Andric for (auto Location : locations()) {
1117c0981da4SDimitry Andric unsigned ID = LocIdxToLocID[Location.Idx];
1118c0981da4SDimitry Andric // Don't clobber SP, even if the mask says it's clobbered.
1119c0981da4SDimitry Andric if (ID < NumRegs && !SPAliases.count(ID) && MO->clobbersPhysReg(ID))
1120c0981da4SDimitry Andric defReg(ID, CurBB, InstID);
1121c0981da4SDimitry Andric }
1122c0981da4SDimitry Andric Masks.push_back(std::make_pair(MO, InstID));
1123c0981da4SDimitry Andric }
1124b60736ecSDimitry Andric
getOrTrackSpillLoc(SpillLoc L)1125e3b55780SDimitry Andric std::optional<SpillLocationNo> MLocTracker::getOrTrackSpillLoc(SpillLoc L) {
1126c0981da4SDimitry Andric SpillLocationNo SpillID(SpillLocs.idFor(L));
1127145449b1SDimitry Andric
1128c0981da4SDimitry Andric if (SpillID.id() == 0) {
1129145449b1SDimitry Andric // If there is no location, and we have reached the limit of how many stack
1130145449b1SDimitry Andric // slots to track, then don't track this one.
1131145449b1SDimitry Andric if (SpillLocs.size() >= StackWorkingSetLimit)
1132e3b55780SDimitry Andric return std::nullopt;
1133145449b1SDimitry Andric
1134c0981da4SDimitry Andric // Spill location is untracked: create record for this one, and all
1135c0981da4SDimitry Andric // subregister slots too.
1136c0981da4SDimitry Andric SpillID = SpillLocationNo(SpillLocs.insert(L));
1137c0981da4SDimitry Andric for (unsigned StackIdx = 0; StackIdx < NumSlotIdxes; ++StackIdx) {
1138c0981da4SDimitry Andric unsigned L = getSpillIDWithIdx(SpillID, StackIdx);
1139c0981da4SDimitry Andric LocIdx Idx = LocIdx(LocIdxToIDNum.size()); // New idx
1140c0981da4SDimitry Andric LocIdxToIDNum.grow(Idx);
1141c0981da4SDimitry Andric LocIdxToLocID.grow(Idx);
1142c0981da4SDimitry Andric LocIDToLocIdx.push_back(Idx);
1143c0981da4SDimitry Andric LocIdxToLocID[Idx] = L;
1144c0981da4SDimitry Andric // Initialize to PHI value; corresponds to the location's live-in value
1145c0981da4SDimitry Andric // during transfer function construction.
1146c0981da4SDimitry Andric LocIdxToIDNum[Idx] = ValueIDNum(CurBB, 0, Idx);
1147c0981da4SDimitry Andric }
1148c0981da4SDimitry Andric }
1149c0981da4SDimitry Andric return SpillID;
1150c0981da4SDimitry Andric }
1151344a3780SDimitry Andric
LocIdxToName(LocIdx Idx) const1152c0981da4SDimitry Andric std::string MLocTracker::LocIdxToName(LocIdx Idx) const {
1153c0981da4SDimitry Andric unsigned ID = LocIdxToLocID[Idx];
1154c0981da4SDimitry Andric if (ID >= NumRegs) {
1155c0981da4SDimitry Andric StackSlotPos Pos = locIDToSpillIdx(ID);
1156c0981da4SDimitry Andric ID -= NumRegs;
1157c0981da4SDimitry Andric unsigned Slot = ID / NumSlotIdxes;
1158c0981da4SDimitry Andric return Twine("slot ")
1159c0981da4SDimitry Andric .concat(Twine(Slot).concat(Twine(" sz ").concat(Twine(Pos.first)
1160c0981da4SDimitry Andric .concat(Twine(" offs ").concat(Twine(Pos.second))))))
1161c0981da4SDimitry Andric .str();
1162c0981da4SDimitry Andric } else {
1163c0981da4SDimitry Andric return TRI.getRegAsmName(ID).str();
1164c0981da4SDimitry Andric }
1165c0981da4SDimitry Andric }
1166344a3780SDimitry Andric
IDAsString(const ValueIDNum & Num) const1167c0981da4SDimitry Andric std::string MLocTracker::IDAsString(const ValueIDNum &Num) const {
1168c0981da4SDimitry Andric std::string DefName = LocIdxToName(Num.getLoc());
1169c0981da4SDimitry Andric return Num.asString(DefName);
1170c0981da4SDimitry Andric }
1171344a3780SDimitry Andric
1172c0981da4SDimitry Andric #ifndef NDEBUG
dump()1173c0981da4SDimitry Andric LLVM_DUMP_METHOD void MLocTracker::dump() {
1174c0981da4SDimitry Andric for (auto Location : locations()) {
1175c0981da4SDimitry Andric std::string MLocName = LocIdxToName(Location.Value.getLoc());
1176c0981da4SDimitry Andric std::string DefName = Location.Value.asString(MLocName);
1177c0981da4SDimitry Andric dbgs() << LocIdxToName(Location.Idx) << " --> " << DefName << "\n";
1178c0981da4SDimitry Andric }
1179c0981da4SDimitry Andric }
1180b60736ecSDimitry Andric
dump_mloc_map()1181c0981da4SDimitry Andric LLVM_DUMP_METHOD void MLocTracker::dump_mloc_map() {
1182c0981da4SDimitry Andric for (auto Location : locations()) {
1183c0981da4SDimitry Andric std::string foo = LocIdxToName(Location.Idx);
1184c0981da4SDimitry Andric dbgs() << "Idx " << Location.Idx.asU64() << " " << foo << "\n";
1185c0981da4SDimitry Andric }
1186c0981da4SDimitry Andric }
1187c0981da4SDimitry Andric #endif
1188b60736ecSDimitry Andric
1189e3b55780SDimitry Andric MachineInstrBuilder
emitLoc(const SmallVectorImpl<ResolvedDbgOp> & DbgOps,const DebugVariable & Var,const DILocation * DILoc,const DbgValueProperties & Properties)1190e3b55780SDimitry Andric MLocTracker::emitLoc(const SmallVectorImpl<ResolvedDbgOp> &DbgOps,
1191ac9a064cSDimitry Andric const DebugVariable &Var, const DILocation *DILoc,
1192c0981da4SDimitry Andric const DbgValueProperties &Properties) {
1193ac9a064cSDimitry Andric DebugLoc DL = DebugLoc(DILoc);
1194e3b55780SDimitry Andric
1195e3b55780SDimitry Andric const MCInstrDesc &Desc = Properties.IsVariadic
1196e3b55780SDimitry Andric ? TII.get(TargetOpcode::DBG_VALUE_LIST)
1197e3b55780SDimitry Andric : TII.get(TargetOpcode::DBG_VALUE);
1198e3b55780SDimitry Andric
1199e3b55780SDimitry Andric #ifdef EXPENSIVE_CHECKS
1200e3b55780SDimitry Andric assert(all_of(DbgOps,
1201e3b55780SDimitry Andric [](const ResolvedDbgOp &Op) {
1202e3b55780SDimitry Andric return Op.IsConst || !Op.Loc.isIllegal();
1203e3b55780SDimitry Andric }) &&
1204e3b55780SDimitry Andric "Did not expect illegal ops in DbgOps.");
1205e3b55780SDimitry Andric assert((DbgOps.size() == 0 ||
1206e3b55780SDimitry Andric DbgOps.size() == Properties.getLocationOpCount()) &&
1207e3b55780SDimitry Andric "Expected to have either one DbgOp per MI LocationOp, or none.");
1208e3b55780SDimitry Andric #endif
1209e3b55780SDimitry Andric
1210e3b55780SDimitry Andric auto GetRegOp = [](unsigned Reg) -> MachineOperand {
1211e3b55780SDimitry Andric return MachineOperand::CreateReg(
1212e3b55780SDimitry Andric /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
1213e3b55780SDimitry Andric /* isKill */ false, /* isDead */ false,
1214e3b55780SDimitry Andric /* isUndef */ false, /* isEarlyClobber */ false,
1215e3b55780SDimitry Andric /* SubReg */ 0, /* isDebug */ true);
1216e3b55780SDimitry Andric };
1217e3b55780SDimitry Andric
1218e3b55780SDimitry Andric SmallVector<MachineOperand> MOs;
1219e3b55780SDimitry Andric
1220e3b55780SDimitry Andric auto EmitUndef = [&]() {
1221e3b55780SDimitry Andric MOs.clear();
1222e3b55780SDimitry Andric MOs.assign(Properties.getLocationOpCount(), GetRegOp(0));
1223e3b55780SDimitry Andric return BuildMI(MF, DL, Desc, false, MOs, Var.getVariable(),
1224e3b55780SDimitry Andric Properties.DIExpr);
1225e3b55780SDimitry Andric };
1226e3b55780SDimitry Andric
1227e3b55780SDimitry Andric // Don't bother passing any real operands to BuildMI if any of them would be
1228e3b55780SDimitry Andric // $noreg.
1229e3b55780SDimitry Andric if (DbgOps.empty())
1230e3b55780SDimitry Andric return EmitUndef();
1231e3b55780SDimitry Andric
1232e3b55780SDimitry Andric bool Indirect = Properties.Indirect;
1233b60736ecSDimitry Andric
1234c0981da4SDimitry Andric const DIExpression *Expr = Properties.DIExpr;
1235e3b55780SDimitry Andric
1236e3b55780SDimitry Andric assert(DbgOps.size() == Properties.getLocationOpCount());
1237e3b55780SDimitry Andric
1238e3b55780SDimitry Andric // If all locations are valid, accumulate them into our list of
1239e3b55780SDimitry Andric // MachineOperands. For any spilled locations, either update the indirectness
1240e3b55780SDimitry Andric // register or apply the appropriate transformations in the DIExpression.
1241e3b55780SDimitry Andric for (size_t Idx = 0; Idx < Properties.getLocationOpCount(); ++Idx) {
1242e3b55780SDimitry Andric const ResolvedDbgOp &Op = DbgOps[Idx];
1243e3b55780SDimitry Andric
1244e3b55780SDimitry Andric if (Op.IsConst) {
1245e3b55780SDimitry Andric MOs.push_back(Op.MO);
1246e3b55780SDimitry Andric continue;
1247e3b55780SDimitry Andric }
1248e3b55780SDimitry Andric
1249e3b55780SDimitry Andric LocIdx MLoc = Op.Loc;
1250e3b55780SDimitry Andric unsigned LocID = LocIdxToLocID[MLoc];
1251e3b55780SDimitry Andric if (LocID >= NumRegs) {
1252c0981da4SDimitry Andric SpillLocationNo SpillID = locIDToSpill(LocID);
1253c0981da4SDimitry Andric StackSlotPos StackIdx = locIDToSpillIdx(LocID);
1254c0981da4SDimitry Andric unsigned short Offset = StackIdx.second;
1255b60736ecSDimitry Andric
1256c0981da4SDimitry Andric // TODO: support variables that are located in spill slots, with non-zero
1257c0981da4SDimitry Andric // offsets from the start of the spill slot. It would require some more
1258c0981da4SDimitry Andric // complex DIExpression calculations. This doesn't seem to be produced by
1259c0981da4SDimitry Andric // LLVM right now, so don't try and support it.
1260c0981da4SDimitry Andric // Accept no-subregister slots and subregisters where the offset is zero.
1261c0981da4SDimitry Andric // The consumer should already have type information to work out how large
1262c0981da4SDimitry Andric // the variable is.
1263c0981da4SDimitry Andric if (Offset == 0) {
1264c0981da4SDimitry Andric const SpillLoc &Spill = SpillLocs[SpillID.id()];
1265c0981da4SDimitry Andric unsigned Base = Spill.SpillBase;
1266f65dcba8SDimitry Andric
1267145449b1SDimitry Andric // There are several ways we can dereference things, and several inputs
1268145449b1SDimitry Andric // to consider:
1269145449b1SDimitry Andric // * NRVO variables will appear with IsIndirect set, but should have
1270145449b1SDimitry Andric // nothing else in their DIExpressions,
1271145449b1SDimitry Andric // * Variables with DW_OP_stack_value in their expr already need an
1272145449b1SDimitry Andric // explicit dereference of the stack location,
1273145449b1SDimitry Andric // * Values that don't match the variable size need DW_OP_deref_size,
1274145449b1SDimitry Andric // * Everything else can just become a simple location expression.
1275145449b1SDimitry Andric
1276145449b1SDimitry Andric // We need to use deref_size whenever there's a mismatch between the
1277145449b1SDimitry Andric // size of value and the size of variable portion being read.
1278145449b1SDimitry Andric // Additionally, we should use it whenever dealing with stack_value
1279145449b1SDimitry Andric // fragments, to avoid the consumer having to determine the deref size
1280145449b1SDimitry Andric // from DW_OP_piece.
1281145449b1SDimitry Andric bool UseDerefSize = false;
1282e3b55780SDimitry Andric unsigned ValueSizeInBits = getLocSizeInBits(MLoc);
1283145449b1SDimitry Andric unsigned DerefSizeInBytes = ValueSizeInBits / 8;
1284145449b1SDimitry Andric if (auto Fragment = Var.getFragment()) {
1285145449b1SDimitry Andric unsigned VariableSizeInBits = Fragment->SizeInBits;
1286145449b1SDimitry Andric if (VariableSizeInBits != ValueSizeInBits || Expr->isComplex())
1287145449b1SDimitry Andric UseDerefSize = true;
1288145449b1SDimitry Andric } else if (auto Size = Var.getVariable()->getSizeInBits()) {
1289145449b1SDimitry Andric if (*Size != ValueSizeInBits) {
1290145449b1SDimitry Andric UseDerefSize = true;
1291145449b1SDimitry Andric }
1292145449b1SDimitry Andric }
1293145449b1SDimitry Andric
1294e3b55780SDimitry Andric SmallVector<uint64_t, 5> OffsetOps;
1295e3b55780SDimitry Andric TRI.getOffsetOpcodes(Spill.SpillOffset, OffsetOps);
1296e3b55780SDimitry Andric bool StackValue = false;
1297e3b55780SDimitry Andric
1298f65dcba8SDimitry Andric if (Properties.Indirect) {
1299145449b1SDimitry Andric // This is something like an NRVO variable, where the pointer has been
1300e3b55780SDimitry Andric // spilt to the stack. It should end up being a memory location, with
1301e3b55780SDimitry Andric // the pointer to the variable loaded off the stack with a deref:
1302145449b1SDimitry Andric assert(!Expr->isImplicit());
1303e3b55780SDimitry Andric OffsetOps.push_back(dwarf::DW_OP_deref);
1304e3b55780SDimitry Andric } else if (UseDerefSize && Expr->isSingleLocationExpression()) {
1305e3b55780SDimitry Andric // TODO: Figure out how to handle deref size issues for variadic
1306e3b55780SDimitry Andric // values.
1307145449b1SDimitry Andric // We're loading a value off the stack that's not the same size as the
1308e3b55780SDimitry Andric // variable. Add / subtract stack offset, explicitly deref with a
1309e3b55780SDimitry Andric // size, and add DW_OP_stack_value if not already present.
1310e3b55780SDimitry Andric OffsetOps.push_back(dwarf::DW_OP_deref_size);
1311e3b55780SDimitry Andric OffsetOps.push_back(DerefSizeInBytes);
1312e3b55780SDimitry Andric StackValue = true;
1313e3b55780SDimitry Andric } else if (Expr->isComplex() || Properties.IsVariadic) {
1314145449b1SDimitry Andric // A variable with no size ambiguity, but with extra elements in it's
1315145449b1SDimitry Andric // expression. Manually dereference the stack location.
1316e3b55780SDimitry Andric OffsetOps.push_back(dwarf::DW_OP_deref);
1317145449b1SDimitry Andric } else {
1318145449b1SDimitry Andric // A plain value that has been spilt to the stack, with no further
1319145449b1SDimitry Andric // context. Request a location expression, marking the DBG_VALUE as
1320145449b1SDimitry Andric // IsIndirect.
1321e3b55780SDimitry Andric Indirect = true;
1322f65dcba8SDimitry Andric }
1323e3b55780SDimitry Andric
1324e3b55780SDimitry Andric Expr = DIExpression::appendOpsToArg(Expr, OffsetOps, Idx, StackValue);
1325e3b55780SDimitry Andric MOs.push_back(GetRegOp(Base));
1326c0981da4SDimitry Andric } else {
1327e3b55780SDimitry Andric // This is a stack location with a weird subregister offset: emit an
1328e3b55780SDimitry Andric // undef DBG_VALUE instead.
1329e3b55780SDimitry Andric return EmitUndef();
1330c0981da4SDimitry Andric }
1331c0981da4SDimitry Andric } else {
1332c0981da4SDimitry Andric // Non-empty, non-stack slot, must be a plain register.
1333e3b55780SDimitry Andric MOs.push_back(GetRegOp(LocID));
1334e3b55780SDimitry Andric }
1335c0981da4SDimitry Andric }
1336b60736ecSDimitry Andric
1337e3b55780SDimitry Andric return BuildMI(MF, DL, Desc, Indirect, MOs, Var.getVariable(), Expr);
1338c0981da4SDimitry Andric }
1339b60736ecSDimitry Andric
1340b60736ecSDimitry Andric /// Default construct and initialize the pass.
1341145449b1SDimitry Andric InstrRefBasedLDV::InstrRefBasedLDV() = default;
1342b60736ecSDimitry Andric
isCalleeSaved(LocIdx L) const1343c0981da4SDimitry Andric bool InstrRefBasedLDV::isCalleeSaved(LocIdx L) const {
1344b60736ecSDimitry Andric unsigned Reg = MTracker->LocIdxToLocID[L];
1345e3b55780SDimitry Andric return isCalleeSavedReg(Reg);
1346e3b55780SDimitry Andric }
isCalleeSavedReg(Register R) const1347e3b55780SDimitry Andric bool InstrRefBasedLDV::isCalleeSavedReg(Register R) const {
1348e3b55780SDimitry Andric for (MCRegAliasIterator RAI(R, TRI, true); RAI.isValid(); ++RAI)
1349b60736ecSDimitry Andric if (CalleeSavedRegs.test(*RAI))
1350b60736ecSDimitry Andric return true;
1351b60736ecSDimitry Andric return false;
1352b60736ecSDimitry Andric }
1353b60736ecSDimitry Andric
1354b60736ecSDimitry Andric //===----------------------------------------------------------------------===//
1355b60736ecSDimitry Andric // Debug Range Extension Implementation
1356b60736ecSDimitry Andric //===----------------------------------------------------------------------===//
1357b60736ecSDimitry Andric
1358b60736ecSDimitry Andric #ifndef NDEBUG
1359b60736ecSDimitry Andric // Something to restore in the future.
1360b60736ecSDimitry Andric // void InstrRefBasedLDV::printVarLocInMBB(..)
1361b60736ecSDimitry Andric #endif
1362b60736ecSDimitry Andric
1363e3b55780SDimitry Andric std::optional<SpillLocationNo>
extractSpillBaseRegAndOffset(const MachineInstr & MI)1364b60736ecSDimitry Andric InstrRefBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
1365b60736ecSDimitry Andric assert(MI.hasOneMemOperand() &&
1366b60736ecSDimitry Andric "Spill instruction does not have exactly one memory operand?");
1367b60736ecSDimitry Andric auto MMOI = MI.memoperands_begin();
1368b60736ecSDimitry Andric const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
1369b60736ecSDimitry Andric assert(PVal->kind() == PseudoSourceValue::FixedStack &&
1370b60736ecSDimitry Andric "Inconsistent memory operand in spill instruction");
1371b60736ecSDimitry Andric int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
1372b60736ecSDimitry Andric const MachineBasicBlock *MBB = MI.getParent();
1373b60736ecSDimitry Andric Register Reg;
1374b60736ecSDimitry Andric StackOffset Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
1375c0981da4SDimitry Andric return MTracker->getOrTrackSpillLoc({Reg, Offset});
1376c0981da4SDimitry Andric }
1377c0981da4SDimitry Andric
1378e3b55780SDimitry Andric std::optional<LocIdx>
findLocationForMemOperand(const MachineInstr & MI)1379145449b1SDimitry Andric InstrRefBasedLDV::findLocationForMemOperand(const MachineInstr &MI) {
1380e3b55780SDimitry Andric std::optional<SpillLocationNo> SpillLoc = extractSpillBaseRegAndOffset(MI);
1381145449b1SDimitry Andric if (!SpillLoc)
1382e3b55780SDimitry Andric return std::nullopt;
1383c0981da4SDimitry Andric
1384c0981da4SDimitry Andric // Where in the stack slot is this value defined -- i.e., what size of value
1385c0981da4SDimitry Andric // is this? An important question, because it could be loaded into a register
1386c0981da4SDimitry Andric // from the stack at some point. Happily the memory operand will tell us
1387c0981da4SDimitry Andric // the size written to the stack.
1388c0981da4SDimitry Andric auto *MemOperand = *MI.memoperands_begin();
1389ac9a064cSDimitry Andric LocationSize SizeInBits = MemOperand->getSizeInBits();
1390ac9a064cSDimitry Andric assert(SizeInBits.hasValue() && "Expected to find a valid size!");
1391c0981da4SDimitry Andric
1392c0981da4SDimitry Andric // Find that position in the stack indexes we're tracking.
1393ac9a064cSDimitry Andric auto IdxIt = MTracker->StackSlotIdxes.find({SizeInBits.getValue(), 0});
1394c0981da4SDimitry Andric if (IdxIt == MTracker->StackSlotIdxes.end())
1395c0981da4SDimitry Andric // That index is not tracked. This is suprising, and unlikely to ever
1396c0981da4SDimitry Andric // occur, but the safe action is to indicate the variable is optimised out.
1397e3b55780SDimitry Andric return std::nullopt;
1398c0981da4SDimitry Andric
1399145449b1SDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillLoc, IdxIt->second);
1400c0981da4SDimitry Andric return MTracker->getSpillMLoc(SpillID);
1401b60736ecSDimitry Andric }
1402b60736ecSDimitry Andric
1403b60736ecSDimitry Andric /// End all previous ranges related to @MI and start a new range from @MI
1404b60736ecSDimitry Andric /// if it is a DBG_VALUE instr.
transferDebugValue(const MachineInstr & MI)1405b60736ecSDimitry Andric bool InstrRefBasedLDV::transferDebugValue(const MachineInstr &MI) {
1406b60736ecSDimitry Andric if (!MI.isDebugValue())
1407b60736ecSDimitry Andric return false;
1408b60736ecSDimitry Andric
140999aabd70SDimitry Andric assert(MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) &&
1410b60736ecSDimitry Andric "Expected inlined-at fields to agree");
1411b60736ecSDimitry Andric
1412b60736ecSDimitry Andric // If there are no instructions in this lexical scope, do no location tracking
1413b60736ecSDimitry Andric // at all, this variable shouldn't get a legitimate location range.
1414b60736ecSDimitry Andric auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
1415b60736ecSDimitry Andric if (Scope == nullptr)
1416b60736ecSDimitry Andric return true; // handled it; by doing nothing
1417b60736ecSDimitry Andric
1418b60736ecSDimitry Andric // MLocTracker needs to know that this register is read, even if it's only
1419b60736ecSDimitry Andric // read by a debug inst.
1420e3b55780SDimitry Andric for (const MachineOperand &MO : MI.debug_operands())
1421b60736ecSDimitry Andric if (MO.isReg() && MO.getReg() != 0)
1422b60736ecSDimitry Andric (void)MTracker->readReg(MO.getReg());
1423b60736ecSDimitry Andric
1424b60736ecSDimitry Andric // If we're preparing for the second analysis (variables), the machine value
1425b60736ecSDimitry Andric // locations are already solved, and we report this DBG_VALUE and the value
1426b60736ecSDimitry Andric // it refers to to VLocTracker.
1427b60736ecSDimitry Andric if (VTracker) {
1428e3b55780SDimitry Andric SmallVector<DbgOpID> DebugOps;
1429e3b55780SDimitry Andric // Feed defVar the new variable location, or if this is a DBG_VALUE $noreg,
1430e3b55780SDimitry Andric // feed defVar None.
1431e3b55780SDimitry Andric if (!MI.isUndefDebugValue()) {
1432e3b55780SDimitry Andric for (const MachineOperand &MO : MI.debug_operands()) {
1433e3b55780SDimitry Andric // There should be no undef registers here, as we've screened for undef
1434e3b55780SDimitry Andric // debug values.
1435b60736ecSDimitry Andric if (MO.isReg()) {
1436e3b55780SDimitry Andric DebugOps.push_back(DbgOpStore.insert(MTracker->readReg(MO.getReg())));
1437e3b55780SDimitry Andric } else if (MO.isImm() || MO.isFPImm() || MO.isCImm()) {
1438e3b55780SDimitry Andric DebugOps.push_back(DbgOpStore.insert(MO));
1439e3b55780SDimitry Andric } else {
1440e3b55780SDimitry Andric llvm_unreachable("Unexpected debug operand type.");
1441b60736ecSDimitry Andric }
1442b60736ecSDimitry Andric }
1443e3b55780SDimitry Andric }
144499aabd70SDimitry Andric VTracker->defVar(MI, DbgValueProperties(MI), DebugOps);
1445e3b55780SDimitry Andric }
1446b60736ecSDimitry Andric
1447b60736ecSDimitry Andric // If performing final tracking of transfers, report this variable definition
1448b60736ecSDimitry Andric // to the TransferTracker too.
1449b60736ecSDimitry Andric if (TTracker)
1450b60736ecSDimitry Andric TTracker->redefVar(MI);
1451b60736ecSDimitry Andric return true;
1452b60736ecSDimitry Andric }
1453b60736ecSDimitry Andric
getValueForInstrRef(unsigned InstNo,unsigned OpNo,MachineInstr & MI,const FuncValueTable * MLiveOuts,const FuncValueTable * MLiveIns)1454e3b55780SDimitry Andric std::optional<ValueIDNum> InstrRefBasedLDV::getValueForInstrRef(
1455e3b55780SDimitry Andric unsigned InstNo, unsigned OpNo, MachineInstr &MI,
1456312c0ed1SDimitry Andric const FuncValueTable *MLiveOuts, const FuncValueTable *MLiveIns) {
1457b60736ecSDimitry Andric // Various optimizations may have happened to the value during codegen,
1458b60736ecSDimitry Andric // recorded in the value substitution table. Apply any substitutions to
1459344a3780SDimitry Andric // the instruction / operand number in this DBG_INSTR_REF, and collect
1460344a3780SDimitry Andric // any subregister extractions performed during optimization.
1461e3b55780SDimitry Andric const MachineFunction &MF = *MI.getParent()->getParent();
1462344a3780SDimitry Andric
1463344a3780SDimitry Andric // Create dummy substitution with Src set, for lookup.
1464344a3780SDimitry Andric auto SoughtSub =
1465344a3780SDimitry Andric MachineFunction::DebugSubstitution({InstNo, OpNo}, {0, 0}, 0);
1466344a3780SDimitry Andric
1467344a3780SDimitry Andric SmallVector<unsigned, 4> SeenSubregs;
1468344a3780SDimitry Andric auto LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub);
1469344a3780SDimitry Andric while (LowerBoundIt != MF.DebugValueSubstitutions.end() &&
1470344a3780SDimitry Andric LowerBoundIt->Src == SoughtSub.Src) {
1471344a3780SDimitry Andric std::tie(InstNo, OpNo) = LowerBoundIt->Dest;
1472344a3780SDimitry Andric SoughtSub.Src = LowerBoundIt->Dest;
1473344a3780SDimitry Andric if (unsigned Subreg = LowerBoundIt->Subreg)
1474344a3780SDimitry Andric SeenSubregs.push_back(Subreg);
1475344a3780SDimitry Andric LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub);
1476b60736ecSDimitry Andric }
1477b60736ecSDimitry Andric
1478b60736ecSDimitry Andric // Default machine value number is <None> -- if no instruction defines
1479b60736ecSDimitry Andric // the corresponding value, it must have been optimized out.
1480e3b55780SDimitry Andric std::optional<ValueIDNum> NewID;
1481b60736ecSDimitry Andric
1482b60736ecSDimitry Andric // Try to lookup the instruction number, and find the machine value number
1483344a3780SDimitry Andric // that it defines. It could be an instruction, or a PHI.
1484b60736ecSDimitry Andric auto InstrIt = DebugInstrNumToInstr.find(InstNo);
1485e3b55780SDimitry Andric auto PHIIt = llvm::lower_bound(DebugPHINumToValue, InstNo);
1486b60736ecSDimitry Andric if (InstrIt != DebugInstrNumToInstr.end()) {
1487b60736ecSDimitry Andric const MachineInstr &TargetInstr = *InstrIt->second.first;
1488b60736ecSDimitry Andric uint64_t BlockNo = TargetInstr.getParent()->getNumber();
1489b60736ecSDimitry Andric
1490c0981da4SDimitry Andric // Pick out the designated operand. It might be a memory reference, if
1491c0981da4SDimitry Andric // a register def was folded into a stack store.
1492c0981da4SDimitry Andric if (OpNo == MachineFunction::DebugOperandMemNumber &&
1493c0981da4SDimitry Andric TargetInstr.hasOneMemOperand()) {
1494e3b55780SDimitry Andric std::optional<LocIdx> L = findLocationForMemOperand(TargetInstr);
1495c0981da4SDimitry Andric if (L)
1496c0981da4SDimitry Andric NewID = ValueIDNum(BlockNo, InstrIt->second.second, *L);
1497c0981da4SDimitry Andric } else if (OpNo != MachineFunction::DebugOperandMemNumber) {
1498145449b1SDimitry Andric // Permit the debug-info to be completely wrong: identifying a nonexistant
1499145449b1SDimitry Andric // operand, or one that is not a register definition, means something
1500145449b1SDimitry Andric // unexpected happened during optimisation. Broken debug-info, however,
1501145449b1SDimitry Andric // shouldn't crash the compiler -- instead leave the variable value as
1502145449b1SDimitry Andric // None, which will make it appear "optimised out".
1503145449b1SDimitry Andric if (OpNo < TargetInstr.getNumOperands()) {
1504b60736ecSDimitry Andric const MachineOperand &MO = TargetInstr.getOperand(OpNo);
1505b60736ecSDimitry Andric
1506145449b1SDimitry Andric if (MO.isReg() && MO.isDef() && MO.getReg()) {
1507c0981da4SDimitry Andric unsigned LocID = MTracker->getLocID(MO.getReg());
1508b60736ecSDimitry Andric LocIdx L = MTracker->LocIDToLocIdx[LocID];
1509b60736ecSDimitry Andric NewID = ValueIDNum(BlockNo, InstrIt->second.second, L);
1510c0981da4SDimitry Andric }
1511145449b1SDimitry Andric }
1512145449b1SDimitry Andric
1513145449b1SDimitry Andric if (!NewID) {
1514145449b1SDimitry Andric LLVM_DEBUG(
1515145449b1SDimitry Andric { dbgs() << "Seen instruction reference to illegal operand\n"; });
1516145449b1SDimitry Andric }
1517145449b1SDimitry Andric }
1518c0981da4SDimitry Andric // else: NewID is left as None.
1519344a3780SDimitry Andric } else if (PHIIt != DebugPHINumToValue.end() && PHIIt->InstrNum == InstNo) {
1520344a3780SDimitry Andric // It's actually a PHI value. Which value it is might not be obvious, use
1521344a3780SDimitry Andric // the resolver helper to find out.
1522312c0ed1SDimitry Andric assert(MLiveOuts && MLiveIns);
1523312c0ed1SDimitry Andric NewID = resolveDbgPHIs(*MI.getParent()->getParent(), *MLiveOuts, *MLiveIns,
1524344a3780SDimitry Andric MI, InstNo);
1525344a3780SDimitry Andric }
1526344a3780SDimitry Andric
1527344a3780SDimitry Andric // Apply any subregister extractions, in reverse. We might have seen code
1528344a3780SDimitry Andric // like this:
1529344a3780SDimitry Andric // CALL64 @foo, implicit-def $rax
1530344a3780SDimitry Andric // %0:gr64 = COPY $rax
1531344a3780SDimitry Andric // %1:gr32 = COPY %0.sub_32bit
1532344a3780SDimitry Andric // %2:gr16 = COPY %1.sub_16bit
1533344a3780SDimitry Andric // %3:gr8 = COPY %2.sub_8bit
1534344a3780SDimitry Andric // In which case each copy would have been recorded as a substitution with
1535344a3780SDimitry Andric // a subregister qualifier. Apply those qualifiers now.
1536344a3780SDimitry Andric if (NewID && !SeenSubregs.empty()) {
1537344a3780SDimitry Andric unsigned Offset = 0;
1538344a3780SDimitry Andric unsigned Size = 0;
1539344a3780SDimitry Andric
1540344a3780SDimitry Andric // Look at each subregister that we passed through, and progressively
1541344a3780SDimitry Andric // narrow in, accumulating any offsets that occur. Substitutions should
1542344a3780SDimitry Andric // only ever be the same or narrower width than what they read from;
1543344a3780SDimitry Andric // iterate in reverse order so that we go from wide to small.
1544344a3780SDimitry Andric for (unsigned Subreg : reverse(SeenSubregs)) {
1545344a3780SDimitry Andric unsigned ThisSize = TRI->getSubRegIdxSize(Subreg);
1546344a3780SDimitry Andric unsigned ThisOffset = TRI->getSubRegIdxOffset(Subreg);
1547344a3780SDimitry Andric Offset += ThisOffset;
1548344a3780SDimitry Andric Size = (Size == 0) ? ThisSize : std::min(Size, ThisSize);
1549344a3780SDimitry Andric }
1550344a3780SDimitry Andric
1551344a3780SDimitry Andric // If that worked, look for an appropriate subregister with the register
1552344a3780SDimitry Andric // where the define happens. Don't look at values that were defined during
1553344a3780SDimitry Andric // a stack write: we can't currently express register locations within
1554344a3780SDimitry Andric // spills.
1555344a3780SDimitry Andric LocIdx L = NewID->getLoc();
1556344a3780SDimitry Andric if (NewID && !MTracker->isSpill(L)) {
1557344a3780SDimitry Andric // Find the register class for the register where this def happened.
1558344a3780SDimitry Andric // FIXME: no index for this?
1559344a3780SDimitry Andric Register Reg = MTracker->LocIdxToLocID[L];
1560344a3780SDimitry Andric const TargetRegisterClass *TRC = nullptr;
15614b4fe385SDimitry Andric for (const auto *TRCI : TRI->regclasses())
1562344a3780SDimitry Andric if (TRCI->contains(Reg))
1563344a3780SDimitry Andric TRC = TRCI;
1564344a3780SDimitry Andric assert(TRC && "Couldn't find target register class?");
1565344a3780SDimitry Andric
1566344a3780SDimitry Andric // If the register we have isn't the right size or in the right place,
1567344a3780SDimitry Andric // Try to find a subregister inside it.
1568344a3780SDimitry Andric unsigned MainRegSize = TRI->getRegSizeInBits(*TRC);
1569344a3780SDimitry Andric if (Size != MainRegSize || Offset) {
1570344a3780SDimitry Andric // Enumerate all subregisters, searching.
1571344a3780SDimitry Andric Register NewReg = 0;
15727fa27ce4SDimitry Andric for (MCPhysReg SR : TRI->subregs(Reg)) {
15737fa27ce4SDimitry Andric unsigned Subreg = TRI->getSubRegIndex(Reg, SR);
1574344a3780SDimitry Andric unsigned SubregSize = TRI->getSubRegIdxSize(Subreg);
1575344a3780SDimitry Andric unsigned SubregOffset = TRI->getSubRegIdxOffset(Subreg);
1576344a3780SDimitry Andric if (SubregSize == Size && SubregOffset == Offset) {
15777fa27ce4SDimitry Andric NewReg = SR;
1578344a3780SDimitry Andric break;
1579344a3780SDimitry Andric }
1580344a3780SDimitry Andric }
1581344a3780SDimitry Andric
1582344a3780SDimitry Andric // If we didn't find anything: there's no way to express our value.
1583344a3780SDimitry Andric if (!NewReg) {
1584e3b55780SDimitry Andric NewID = std::nullopt;
1585344a3780SDimitry Andric } else {
1586344a3780SDimitry Andric // Re-state the value as being defined within the subregister
1587344a3780SDimitry Andric // that we found.
1588344a3780SDimitry Andric LocIdx NewLoc = MTracker->lookupOrTrackRegister(NewReg);
1589344a3780SDimitry Andric NewID = ValueIDNum(NewID->getBlock(), NewID->getInst(), NewLoc);
1590344a3780SDimitry Andric }
1591344a3780SDimitry Andric }
1592344a3780SDimitry Andric } else {
1593344a3780SDimitry Andric // If we can't handle subregisters, unset the new value.
1594e3b55780SDimitry Andric NewID = std::nullopt;
1595344a3780SDimitry Andric }
1596b60736ecSDimitry Andric }
1597b60736ecSDimitry Andric
1598e3b55780SDimitry Andric return NewID;
1599e3b55780SDimitry Andric }
1600e3b55780SDimitry Andric
transferDebugInstrRef(MachineInstr & MI,const FuncValueTable * MLiveOuts,const FuncValueTable * MLiveIns)1601e3b55780SDimitry Andric bool InstrRefBasedLDV::transferDebugInstrRef(MachineInstr &MI,
1602312c0ed1SDimitry Andric const FuncValueTable *MLiveOuts,
1603312c0ed1SDimitry Andric const FuncValueTable *MLiveIns) {
1604e3b55780SDimitry Andric if (!MI.isDebugRef())
1605e3b55780SDimitry Andric return false;
1606e3b55780SDimitry Andric
1607e3b55780SDimitry Andric // Only handle this instruction when we are building the variable value
1608e3b55780SDimitry Andric // transfer function.
1609e3b55780SDimitry Andric if (!VTracker && !TTracker)
1610e3b55780SDimitry Andric return false;
1611e3b55780SDimitry Andric
1612e3b55780SDimitry Andric const DILocalVariable *Var = MI.getDebugVariable();
1613e3b55780SDimitry Andric const DIExpression *Expr = MI.getDebugExpression();
1614e3b55780SDimitry Andric const DILocation *DebugLoc = MI.getDebugLoc();
1615e3b55780SDimitry Andric const DILocation *InlinedAt = DebugLoc->getInlinedAt();
1616e3b55780SDimitry Andric assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
1617e3b55780SDimitry Andric "Expected inlined-at fields to agree");
1618e3b55780SDimitry Andric
1619e3b55780SDimitry Andric DebugVariable V(Var, Expr, InlinedAt);
1620e3b55780SDimitry Andric
1621e3b55780SDimitry Andric auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
1622e3b55780SDimitry Andric if (Scope == nullptr)
1623e3b55780SDimitry Andric return true; // Handled by doing nothing. This variable is never in scope.
1624e3b55780SDimitry Andric
1625e3b55780SDimitry Andric SmallVector<DbgOpID> DbgOpIDs;
1626e3b55780SDimitry Andric for (const MachineOperand &MO : MI.debug_operands()) {
1627e3b55780SDimitry Andric if (!MO.isDbgInstrRef()) {
1628e3b55780SDimitry Andric assert(!MO.isReg() && "DBG_INSTR_REF should not contain registers");
1629e3b55780SDimitry Andric DbgOpID ConstOpID = DbgOpStore.insert(DbgOp(MO));
1630e3b55780SDimitry Andric DbgOpIDs.push_back(ConstOpID);
1631e3b55780SDimitry Andric continue;
1632e3b55780SDimitry Andric }
1633e3b55780SDimitry Andric
1634e3b55780SDimitry Andric unsigned InstNo = MO.getInstrRefInstrIndex();
1635e3b55780SDimitry Andric unsigned OpNo = MO.getInstrRefOpIndex();
1636e3b55780SDimitry Andric
1637e3b55780SDimitry Andric // Default machine value number is <None> -- if no instruction defines
1638e3b55780SDimitry Andric // the corresponding value, it must have been optimized out.
1639e3b55780SDimitry Andric std::optional<ValueIDNum> NewID =
1640e3b55780SDimitry Andric getValueForInstrRef(InstNo, OpNo, MI, MLiveOuts, MLiveIns);
1641e3b55780SDimitry Andric // We have a value number or std::nullopt. If the latter, then kill the
1642e3b55780SDimitry Andric // entire debug value.
1643e3b55780SDimitry Andric if (NewID) {
1644e3b55780SDimitry Andric DbgOpIDs.push_back(DbgOpStore.insert(*NewID));
1645e3b55780SDimitry Andric } else {
1646e3b55780SDimitry Andric DbgOpIDs.clear();
1647e3b55780SDimitry Andric break;
1648e3b55780SDimitry Andric }
1649e3b55780SDimitry Andric }
1650e3b55780SDimitry Andric
1651e3b55780SDimitry Andric // We have a DbgOpID for every value or for none. Tell the variable value
1652e3b55780SDimitry Andric // tracker about it. The rest of this LiveDebugValues implementation acts
1653e3b55780SDimitry Andric // exactly the same for DBG_INSTR_REFs as DBG_VALUEs (just, the former can
1654e3b55780SDimitry Andric // refer to values that aren't immediately available).
1655e3b55780SDimitry Andric DbgValueProperties Properties(Expr, false, true);
1656145449b1SDimitry Andric if (VTracker)
1657e3b55780SDimitry Andric VTracker->defVar(MI, Properties, DbgOpIDs);
1658b60736ecSDimitry Andric
1659b60736ecSDimitry Andric // If we're on the final pass through the function, decompose this INSTR_REF
1660b60736ecSDimitry Andric // into a plain DBG_VALUE.
1661b60736ecSDimitry Andric if (!TTracker)
1662b60736ecSDimitry Andric return true;
1663b60736ecSDimitry Andric
1664e3b55780SDimitry Andric // Fetch the concrete DbgOps now, as we will need them later.
1665e3b55780SDimitry Andric SmallVector<DbgOp> DbgOps;
1666e3b55780SDimitry Andric for (DbgOpID OpID : DbgOpIDs) {
1667e3b55780SDimitry Andric DbgOps.push_back(DbgOpStore.find(OpID));
1668e3b55780SDimitry Andric }
1669e3b55780SDimitry Andric
1670b60736ecSDimitry Andric // Pick a location for the machine value number, if such a location exists.
1671b60736ecSDimitry Andric // (This information could be stored in TransferTracker to make it faster).
1672e3b55780SDimitry Andric SmallDenseMap<ValueIDNum, TransferTracker::LocationAndQuality> FoundLocs;
1673e3b55780SDimitry Andric SmallVector<ValueIDNum> ValuesToFind;
1674e3b55780SDimitry Andric // Initialized the preferred-location map with illegal locations, to be
1675e3b55780SDimitry Andric // filled in later.
1676e3b55780SDimitry Andric for (const DbgOp &Op : DbgOps) {
1677e3b55780SDimitry Andric if (!Op.IsConst)
1678e3b55780SDimitry Andric if (FoundLocs.insert({Op.ID, TransferTracker::LocationAndQuality()})
1679e3b55780SDimitry Andric .second)
1680e3b55780SDimitry Andric ValuesToFind.push_back(Op.ID);
1681e3b55780SDimitry Andric }
1682e3b55780SDimitry Andric
1683b60736ecSDimitry Andric for (auto Location : MTracker->locations()) {
1684b60736ecSDimitry Andric LocIdx CurL = Location.Idx;
1685c0981da4SDimitry Andric ValueIDNum ID = MTracker->readMLoc(CurL);
1686e3b55780SDimitry Andric auto ValueToFindIt = find(ValuesToFind, ID);
1687e3b55780SDimitry Andric if (ValueToFindIt == ValuesToFind.end())
1688e3b55780SDimitry Andric continue;
1689e3b55780SDimitry Andric auto &Previous = FoundLocs.find(ID)->second;
1690b60736ecSDimitry Andric // If this is the first location with that value, pick it. Otherwise,
1691b60736ecSDimitry Andric // consider whether it's a "longer term" location.
1692e3b55780SDimitry Andric std::optional<TransferTracker::LocationQuality> ReplacementQuality =
1693e3b55780SDimitry Andric TTracker->getLocQualityIfBetter(CurL, Previous.getQuality());
1694e3b55780SDimitry Andric if (ReplacementQuality) {
1695e3b55780SDimitry Andric Previous = TransferTracker::LocationAndQuality(CurL, *ReplacementQuality);
1696e3b55780SDimitry Andric if (Previous.isBest()) {
1697e3b55780SDimitry Andric ValuesToFind.erase(ValueToFindIt);
1698e3b55780SDimitry Andric if (ValuesToFind.empty())
1699e3b55780SDimitry Andric break;
1700e3b55780SDimitry Andric }
1701e3b55780SDimitry Andric }
1702e3b55780SDimitry Andric }
1703e3b55780SDimitry Andric
1704e3b55780SDimitry Andric SmallVector<ResolvedDbgOp> NewLocs;
1705e3b55780SDimitry Andric for (const DbgOp &DbgOp : DbgOps) {
1706e3b55780SDimitry Andric if (DbgOp.IsConst) {
1707e3b55780SDimitry Andric NewLocs.push_back(DbgOp.MO);
1708b60736ecSDimitry Andric continue;
1709b60736ecSDimitry Andric }
1710e3b55780SDimitry Andric LocIdx FoundLoc = FoundLocs.find(DbgOp.ID)->second.getLoc();
1711e3b55780SDimitry Andric if (FoundLoc.isIllegal()) {
1712e3b55780SDimitry Andric NewLocs.clear();
1713e3b55780SDimitry Andric break;
1714b60736ecSDimitry Andric }
1715e3b55780SDimitry Andric NewLocs.push_back(FoundLoc);
1716b60736ecSDimitry Andric }
1717b60736ecSDimitry Andric // Tell transfer tracker that the variable value has changed.
1718e3b55780SDimitry Andric TTracker->redefVar(MI, Properties, NewLocs);
1719b60736ecSDimitry Andric
1720e3b55780SDimitry Andric // If there were values with no location, but all such values are defined in
1721e3b55780SDimitry Andric // later instructions in this block, this is a block-local use-before-def.
1722e3b55780SDimitry Andric if (!DbgOps.empty() && NewLocs.empty()) {
1723e3b55780SDimitry Andric bool IsValidUseBeforeDef = true;
1724e3b55780SDimitry Andric uint64_t LastUseBeforeDef = 0;
1725e3b55780SDimitry Andric for (auto ValueLoc : FoundLocs) {
1726e3b55780SDimitry Andric ValueIDNum NewID = ValueLoc.first;
1727e3b55780SDimitry Andric LocIdx FoundLoc = ValueLoc.second.getLoc();
1728e3b55780SDimitry Andric if (!FoundLoc.isIllegal())
1729e3b55780SDimitry Andric continue;
1730e3b55780SDimitry Andric // If we have an value with no location that is not defined in this block,
1731e3b55780SDimitry Andric // then it has no location in this block, leaving this value undefined.
1732e3b55780SDimitry Andric if (NewID.getBlock() != CurBB || NewID.getInst() <= CurInst) {
1733e3b55780SDimitry Andric IsValidUseBeforeDef = false;
1734e3b55780SDimitry Andric break;
1735e3b55780SDimitry Andric }
1736e3b55780SDimitry Andric LastUseBeforeDef = std::max(LastUseBeforeDef, NewID.getInst());
1737e3b55780SDimitry Andric }
1738e3b55780SDimitry Andric if (IsValidUseBeforeDef) {
1739ac9a064cSDimitry Andric DebugVariableID VID = DVMap.insertDVID(V, MI.getDebugLoc().get());
1740ac9a064cSDimitry Andric TTracker->addUseBeforeDef(VID, {MI.getDebugExpression(), false, true},
1741e3b55780SDimitry Andric DbgOps, LastUseBeforeDef);
1742e3b55780SDimitry Andric }
1743e3b55780SDimitry Andric }
1744b60736ecSDimitry Andric
1745b60736ecSDimitry Andric // Produce a DBG_VALUE representing what this DBG_INSTR_REF meant.
1746b60736ecSDimitry Andric // This DBG_VALUE is potentially a $noreg / undefined location, if
1747e3b55780SDimitry Andric // FoundLoc is illegal.
1748b60736ecSDimitry Andric // (XXX -- could morph the DBG_INSTR_REF in the future).
1749ac9a064cSDimitry Andric MachineInstr *DbgMI =
1750ac9a064cSDimitry Andric MTracker->emitLoc(NewLocs, V, MI.getDebugLoc().get(), Properties);
1751ac9a064cSDimitry Andric DebugVariableID ID = DVMap.getDVID(V);
1752e3b55780SDimitry Andric
1753ac9a064cSDimitry Andric TTracker->PendingDbgValues.push_back(std::make_pair(ID, DbgMI));
1754b60736ecSDimitry Andric TTracker->flushDbgValues(MI.getIterator(), nullptr);
1755344a3780SDimitry Andric return true;
1756344a3780SDimitry Andric }
1757344a3780SDimitry Andric
transferDebugPHI(MachineInstr & MI)1758344a3780SDimitry Andric bool InstrRefBasedLDV::transferDebugPHI(MachineInstr &MI) {
1759344a3780SDimitry Andric if (!MI.isDebugPHI())
1760344a3780SDimitry Andric return false;
1761344a3780SDimitry Andric
1762344a3780SDimitry Andric // Analyse these only when solving the machine value location problem.
1763344a3780SDimitry Andric if (VTracker || TTracker)
1764344a3780SDimitry Andric return true;
1765344a3780SDimitry Andric
1766344a3780SDimitry Andric // First operand is the value location, either a stack slot or register.
1767344a3780SDimitry Andric // Second is the debug instruction number of the original PHI.
1768344a3780SDimitry Andric const MachineOperand &MO = MI.getOperand(0);
1769344a3780SDimitry Andric unsigned InstrNum = MI.getOperand(1).getImm();
1770344a3780SDimitry Andric
177108e8dd7bSDimitry Andric auto EmitBadPHI = [this, &MI, InstrNum]() -> bool {
1772145449b1SDimitry Andric // Helper lambda to do any accounting when we fail to find a location for
1773145449b1SDimitry Andric // a DBG_PHI. This can happen if DBG_PHIs are malformed, or refer to a
1774145449b1SDimitry Andric // dead stack slot, for example.
1775145449b1SDimitry Andric // Record a DebugPHIRecord with an empty value + location.
1776e3b55780SDimitry Andric DebugPHINumToValue.push_back(
1777e3b55780SDimitry Andric {InstrNum, MI.getParent(), std::nullopt, std::nullopt});
1778145449b1SDimitry Andric return true;
1779145449b1SDimitry Andric };
1780145449b1SDimitry Andric
1781145449b1SDimitry Andric if (MO.isReg() && MO.getReg()) {
1782344a3780SDimitry Andric // The value is whatever's currently in the register. Read and record it,
1783344a3780SDimitry Andric // to be analysed later.
1784344a3780SDimitry Andric Register Reg = MO.getReg();
1785344a3780SDimitry Andric ValueIDNum Num = MTracker->readReg(Reg);
1786344a3780SDimitry Andric auto PHIRec = DebugPHIRecord(
1787344a3780SDimitry Andric {InstrNum, MI.getParent(), Num, MTracker->lookupOrTrackRegister(Reg)});
1788344a3780SDimitry Andric DebugPHINumToValue.push_back(PHIRec);
1789c0981da4SDimitry Andric
1790c0981da4SDimitry Andric // Ensure this register is tracked.
1791c0981da4SDimitry Andric for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1792c0981da4SDimitry Andric MTracker->lookupOrTrackRegister(*RAI);
1793145449b1SDimitry Andric } else if (MO.isFI()) {
1794344a3780SDimitry Andric // The value is whatever's in this stack slot.
1795344a3780SDimitry Andric unsigned FI = MO.getIndex();
1796344a3780SDimitry Andric
1797344a3780SDimitry Andric // If the stack slot is dead, then this was optimized away.
1798344a3780SDimitry Andric // FIXME: stack slot colouring should account for slots that get merged.
1799344a3780SDimitry Andric if (MFI->isDeadObjectIndex(FI))
1800145449b1SDimitry Andric return EmitBadPHI();
1801344a3780SDimitry Andric
1802c0981da4SDimitry Andric // Identify this spill slot, ensure it's tracked.
1803344a3780SDimitry Andric Register Base;
1804344a3780SDimitry Andric StackOffset Offs = TFI->getFrameIndexReference(*MI.getMF(), FI, Base);
1805344a3780SDimitry Andric SpillLoc SL = {Base, Offs};
1806e3b55780SDimitry Andric std::optional<SpillLocationNo> SpillNo = MTracker->getOrTrackSpillLoc(SL);
1807344a3780SDimitry Andric
1808145449b1SDimitry Andric // We might be able to find a value, but have chosen not to, to avoid
1809145449b1SDimitry Andric // tracking too much stack information.
1810145449b1SDimitry Andric if (!SpillNo)
1811145449b1SDimitry Andric return EmitBadPHI();
1812c0981da4SDimitry Andric
1813145449b1SDimitry Andric // Any stack location DBG_PHI should have an associate bit-size.
1814145449b1SDimitry Andric assert(MI.getNumOperands() == 3 && "Stack DBG_PHI with no size?");
1815145449b1SDimitry Andric unsigned slotBitSize = MI.getOperand(2).getImm();
1816145449b1SDimitry Andric
1817145449b1SDimitry Andric unsigned SpillID = MTracker->getLocID(*SpillNo, {slotBitSize, 0});
1818145449b1SDimitry Andric LocIdx SpillLoc = MTracker->getSpillMLoc(SpillID);
1819145449b1SDimitry Andric ValueIDNum Result = MTracker->readMLoc(SpillLoc);
1820344a3780SDimitry Andric
1821344a3780SDimitry Andric // Record this DBG_PHI for later analysis.
1822145449b1SDimitry Andric auto DbgPHI = DebugPHIRecord({InstrNum, MI.getParent(), Result, SpillLoc});
1823344a3780SDimitry Andric DebugPHINumToValue.push_back(DbgPHI);
1824145449b1SDimitry Andric } else {
1825145449b1SDimitry Andric // Else: if the operand is neither a legal register or a stack slot, then
1826145449b1SDimitry Andric // we're being fed illegal debug-info. Record an empty PHI, so that any
1827145449b1SDimitry Andric // debug users trying to read this number will be put off trying to
1828145449b1SDimitry Andric // interpret the value.
1829145449b1SDimitry Andric LLVM_DEBUG(
1830145449b1SDimitry Andric { dbgs() << "Seen DBG_PHI with unrecognised operand format\n"; });
1831145449b1SDimitry Andric return EmitBadPHI();
1832344a3780SDimitry Andric }
1833b60736ecSDimitry Andric
1834b60736ecSDimitry Andric return true;
1835b60736ecSDimitry Andric }
1836b60736ecSDimitry Andric
transferRegisterDef(MachineInstr & MI)1837b60736ecSDimitry Andric void InstrRefBasedLDV::transferRegisterDef(MachineInstr &MI) {
1838b60736ecSDimitry Andric // Meta Instructions do not affect the debug liveness of any register they
1839b60736ecSDimitry Andric // define.
1840b60736ecSDimitry Andric if (MI.isImplicitDef()) {
1841b60736ecSDimitry Andric // Except when there's an implicit def, and the location it's defining has
1842b60736ecSDimitry Andric // no value number. The whole point of an implicit def is to announce that
1843b60736ecSDimitry Andric // the register is live, without be specific about it's value. So define
1844b60736ecSDimitry Andric // a value if there isn't one already.
1845b60736ecSDimitry Andric ValueIDNum Num = MTracker->readReg(MI.getOperand(0).getReg());
1846b60736ecSDimitry Andric // Has a legitimate value -> ignore the implicit def.
1847b60736ecSDimitry Andric if (Num.getLoc() != 0)
1848b60736ecSDimitry Andric return;
1849b60736ecSDimitry Andric // Otherwise, def it here.
1850b60736ecSDimitry Andric } else if (MI.isMetaInstruction())
1851b60736ecSDimitry Andric return;
1852b60736ecSDimitry Andric
1853f65dcba8SDimitry Andric // We always ignore SP defines on call instructions, they don't actually
1854f65dcba8SDimitry Andric // change the value of the stack pointer... except for win32's _chkstk. This
1855f65dcba8SDimitry Andric // is rare: filter quickly for the common case (no stack adjustments, not a
1856f65dcba8SDimitry Andric // call, etc). If it is a call that modifies SP, recognise the SP register
1857f65dcba8SDimitry Andric // defs.
1858f65dcba8SDimitry Andric bool CallChangesSP = false;
1859f65dcba8SDimitry Andric if (AdjustsStackInCalls && MI.isCall() && MI.getOperand(0).isSymbol() &&
1860f65dcba8SDimitry Andric !strcmp(MI.getOperand(0).getSymbolName(), StackProbeSymbolName.data()))
1861f65dcba8SDimitry Andric CallChangesSP = true;
1862f65dcba8SDimitry Andric
1863f65dcba8SDimitry Andric // Test whether we should ignore a def of this register due to it being part
1864f65dcba8SDimitry Andric // of the stack pointer.
1865f65dcba8SDimitry Andric auto IgnoreSPAlias = [this, &MI, CallChangesSP](Register R) -> bool {
1866f65dcba8SDimitry Andric if (CallChangesSP)
1867f65dcba8SDimitry Andric return false;
1868f65dcba8SDimitry Andric return MI.isCall() && MTracker->SPAliases.count(R);
1869f65dcba8SDimitry Andric };
1870f65dcba8SDimitry Andric
1871b60736ecSDimitry Andric // Find the regs killed by MI, and find regmasks of preserved regs.
1872b60736ecSDimitry Andric // Max out the number of statically allocated elements in `DeadRegs`, as this
1873b60736ecSDimitry Andric // prevents fallback to std::set::count() operations.
1874b60736ecSDimitry Andric SmallSet<uint32_t, 32> DeadRegs;
1875b60736ecSDimitry Andric SmallVector<const uint32_t *, 4> RegMasks;
1876b60736ecSDimitry Andric SmallVector<const MachineOperand *, 4> RegMaskPtrs;
1877b60736ecSDimitry Andric for (const MachineOperand &MO : MI.operands()) {
1878b60736ecSDimitry Andric // Determine whether the operand is a register def.
1879e3b55780SDimitry Andric if (MO.isReg() && MO.isDef() && MO.getReg() && MO.getReg().isPhysical() &&
1880f65dcba8SDimitry Andric !IgnoreSPAlias(MO.getReg())) {
1881b60736ecSDimitry Andric // Remove ranges of all aliased registers.
1882b60736ecSDimitry Andric for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1883b60736ecSDimitry Andric // FIXME: Can we break out of this loop early if no insertion occurs?
1884b60736ecSDimitry Andric DeadRegs.insert(*RAI);
1885b60736ecSDimitry Andric } else if (MO.isRegMask()) {
1886b60736ecSDimitry Andric RegMasks.push_back(MO.getRegMask());
1887b60736ecSDimitry Andric RegMaskPtrs.push_back(&MO);
1888b60736ecSDimitry Andric }
1889b60736ecSDimitry Andric }
1890b60736ecSDimitry Andric
1891b60736ecSDimitry Andric // Tell MLocTracker about all definitions, of regmasks and otherwise.
1892b60736ecSDimitry Andric for (uint32_t DeadReg : DeadRegs)
1893b60736ecSDimitry Andric MTracker->defReg(DeadReg, CurBB, CurInst);
1894b60736ecSDimitry Andric
18954b4fe385SDimitry Andric for (const auto *MO : RegMaskPtrs)
1896b60736ecSDimitry Andric MTracker->writeRegMask(MO, CurBB, CurInst);
1897344a3780SDimitry Andric
1898c0981da4SDimitry Andric // If this instruction writes to a spill slot, def that slot.
1899c0981da4SDimitry Andric if (hasFoldedStackStore(MI)) {
1900e3b55780SDimitry Andric if (std::optional<SpillLocationNo> SpillNo =
1901e3b55780SDimitry Andric extractSpillBaseRegAndOffset(MI)) {
1902c0981da4SDimitry Andric for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) {
1903145449b1SDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillNo, I);
1904c0981da4SDimitry Andric LocIdx L = MTracker->getSpillMLoc(SpillID);
1905c0981da4SDimitry Andric MTracker->setMLoc(L, ValueIDNum(CurBB, CurInst, L));
1906c0981da4SDimitry Andric }
1907c0981da4SDimitry Andric }
1908145449b1SDimitry Andric }
1909c0981da4SDimitry Andric
1910344a3780SDimitry Andric if (!TTracker)
1911344a3780SDimitry Andric return;
1912344a3780SDimitry Andric
1913344a3780SDimitry Andric // When committing variable values to locations: tell transfer tracker that
1914344a3780SDimitry Andric // we've clobbered things. It may be able to recover the variable from a
1915344a3780SDimitry Andric // different location.
1916344a3780SDimitry Andric
1917344a3780SDimitry Andric // Inform TTracker about any direct clobbers.
1918344a3780SDimitry Andric for (uint32_t DeadReg : DeadRegs) {
1919344a3780SDimitry Andric LocIdx Loc = MTracker->lookupOrTrackRegister(DeadReg);
1920344a3780SDimitry Andric TTracker->clobberMloc(Loc, MI.getIterator(), false);
1921344a3780SDimitry Andric }
1922344a3780SDimitry Andric
1923344a3780SDimitry Andric // Look for any clobbers performed by a register mask. Only test locations
1924344a3780SDimitry Andric // that are actually being tracked.
1925ecbca9f5SDimitry Andric if (!RegMaskPtrs.empty()) {
1926344a3780SDimitry Andric for (auto L : MTracker->locations()) {
1927344a3780SDimitry Andric // Stack locations can't be clobbered by regmasks.
1928344a3780SDimitry Andric if (MTracker->isSpill(L.Idx))
1929344a3780SDimitry Andric continue;
1930344a3780SDimitry Andric
1931344a3780SDimitry Andric Register Reg = MTracker->LocIdxToLocID[L.Idx];
1932f65dcba8SDimitry Andric if (IgnoreSPAlias(Reg))
1933f65dcba8SDimitry Andric continue;
1934f65dcba8SDimitry Andric
19354b4fe385SDimitry Andric for (const auto *MO : RegMaskPtrs)
1936344a3780SDimitry Andric if (MO->clobbersPhysReg(Reg))
1937344a3780SDimitry Andric TTracker->clobberMloc(L.Idx, MI.getIterator(), false);
1938344a3780SDimitry Andric }
1939ecbca9f5SDimitry Andric }
1940c0981da4SDimitry Andric
1941c0981da4SDimitry Andric // Tell TTracker about any folded stack store.
1942c0981da4SDimitry Andric if (hasFoldedStackStore(MI)) {
1943e3b55780SDimitry Andric if (std::optional<SpillLocationNo> SpillNo =
1944e3b55780SDimitry Andric extractSpillBaseRegAndOffset(MI)) {
1945c0981da4SDimitry Andric for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) {
1946145449b1SDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillNo, I);
1947c0981da4SDimitry Andric LocIdx L = MTracker->getSpillMLoc(SpillID);
1948c0981da4SDimitry Andric TTracker->clobberMloc(L, MI.getIterator(), true);
1949c0981da4SDimitry Andric }
1950c0981da4SDimitry Andric }
1951b60736ecSDimitry Andric }
1952145449b1SDimitry Andric }
1953b60736ecSDimitry Andric
performCopy(Register SrcRegNum,Register DstRegNum)1954b60736ecSDimitry Andric void InstrRefBasedLDV::performCopy(Register SrcRegNum, Register DstRegNum) {
1955c0981da4SDimitry Andric // In all circumstances, re-def all aliases. It's definitely a new value now.
1956c0981da4SDimitry Andric for (MCRegAliasIterator RAI(DstRegNum, TRI, true); RAI.isValid(); ++RAI)
1957c0981da4SDimitry Andric MTracker->defReg(*RAI, CurBB, CurInst);
1958b60736ecSDimitry Andric
1959c0981da4SDimitry Andric ValueIDNum SrcValue = MTracker->readReg(SrcRegNum);
1960b60736ecSDimitry Andric MTracker->setReg(DstRegNum, SrcValue);
1961b60736ecSDimitry Andric
1962c0981da4SDimitry Andric // Copy subregisters from one location to another.
1963b60736ecSDimitry Andric for (MCSubRegIndexIterator SRI(SrcRegNum, TRI); SRI.isValid(); ++SRI) {
1964b60736ecSDimitry Andric unsigned SrcSubReg = SRI.getSubReg();
1965b60736ecSDimitry Andric unsigned SubRegIdx = SRI.getSubRegIndex();
1966b60736ecSDimitry Andric unsigned DstSubReg = TRI->getSubReg(DstRegNum, SubRegIdx);
1967b60736ecSDimitry Andric if (!DstSubReg)
1968b60736ecSDimitry Andric continue;
1969b60736ecSDimitry Andric
1970b60736ecSDimitry Andric // Do copy. There are two matching subregisters, the source value should
1971b60736ecSDimitry Andric // have been def'd when the super-reg was, the latter might not be tracked
1972b60736ecSDimitry Andric // yet.
1973c0981da4SDimitry Andric // This will force SrcSubReg to be tracked, if it isn't yet. Will read
1974c0981da4SDimitry Andric // mphi values if it wasn't tracked.
1975c0981da4SDimitry Andric LocIdx SrcL = MTracker->lookupOrTrackRegister(SrcSubReg);
1976c0981da4SDimitry Andric LocIdx DstL = MTracker->lookupOrTrackRegister(DstSubReg);
1977c0981da4SDimitry Andric (void)SrcL;
1978b60736ecSDimitry Andric (void)DstL;
1979c0981da4SDimitry Andric ValueIDNum CpyValue = MTracker->readReg(SrcSubReg);
1980b60736ecSDimitry Andric
1981b60736ecSDimitry Andric MTracker->setReg(DstSubReg, CpyValue);
1982b60736ecSDimitry Andric }
1983b60736ecSDimitry Andric }
1984b60736ecSDimitry Andric
1985e3b55780SDimitry Andric std::optional<SpillLocationNo>
isSpillInstruction(const MachineInstr & MI,MachineFunction * MF)1986145449b1SDimitry Andric InstrRefBasedLDV::isSpillInstruction(const MachineInstr &MI,
1987b60736ecSDimitry Andric MachineFunction *MF) {
1988b60736ecSDimitry Andric // TODO: Handle multiple stores folded into one.
1989b60736ecSDimitry Andric if (!MI.hasOneMemOperand())
1990e3b55780SDimitry Andric return std::nullopt;
1991b60736ecSDimitry Andric
1992c0981da4SDimitry Andric // Reject any memory operand that's aliased -- we can't guarantee its value.
1993c0981da4SDimitry Andric auto MMOI = MI.memoperands_begin();
1994c0981da4SDimitry Andric const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
1995c0981da4SDimitry Andric if (PVal->isAliased(MFI))
1996e3b55780SDimitry Andric return std::nullopt;
1997c0981da4SDimitry Andric
1998b60736ecSDimitry Andric if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
1999e3b55780SDimitry Andric return std::nullopt; // This is not a spill instruction, since no valid size
2000e3b55780SDimitry Andric // was returned from either function.
2001b60736ecSDimitry Andric
2002145449b1SDimitry Andric return extractSpillBaseRegAndOffset(MI);
2003b60736ecSDimitry Andric }
2004b60736ecSDimitry Andric
isLocationSpill(const MachineInstr & MI,MachineFunction * MF,unsigned & Reg)2005b60736ecSDimitry Andric bool InstrRefBasedLDV::isLocationSpill(const MachineInstr &MI,
2006b60736ecSDimitry Andric MachineFunction *MF, unsigned &Reg) {
2007b60736ecSDimitry Andric if (!isSpillInstruction(MI, MF))
2008b60736ecSDimitry Andric return false;
2009b60736ecSDimitry Andric
2010b60736ecSDimitry Andric int FI;
2011b60736ecSDimitry Andric Reg = TII->isStoreToStackSlotPostFE(MI, FI);
2012b60736ecSDimitry Andric return Reg != 0;
2013b60736ecSDimitry Andric }
2014b60736ecSDimitry Andric
2015e3b55780SDimitry Andric std::optional<SpillLocationNo>
isRestoreInstruction(const MachineInstr & MI,MachineFunction * MF,unsigned & Reg)2016b60736ecSDimitry Andric InstrRefBasedLDV::isRestoreInstruction(const MachineInstr &MI,
2017b60736ecSDimitry Andric MachineFunction *MF, unsigned &Reg) {
2018b60736ecSDimitry Andric if (!MI.hasOneMemOperand())
2019e3b55780SDimitry Andric return std::nullopt;
2020b60736ecSDimitry Andric
2021b60736ecSDimitry Andric // FIXME: Handle folded restore instructions with more than one memory
2022b60736ecSDimitry Andric // operand.
2023b60736ecSDimitry Andric if (MI.getRestoreSize(TII)) {
2024b60736ecSDimitry Andric Reg = MI.getOperand(0).getReg();
2025b60736ecSDimitry Andric return extractSpillBaseRegAndOffset(MI);
2026b60736ecSDimitry Andric }
2027e3b55780SDimitry Andric return std::nullopt;
2028b60736ecSDimitry Andric }
2029b60736ecSDimitry Andric
transferSpillOrRestoreInst(MachineInstr & MI)2030b60736ecSDimitry Andric bool InstrRefBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI) {
2031b60736ecSDimitry Andric // XXX -- it's too difficult to implement VarLocBasedImpl's stack location
2032b60736ecSDimitry Andric // limitations under the new model. Therefore, when comparing them, compare
2033b60736ecSDimitry Andric // versions that don't attempt spills or restores at all.
2034b60736ecSDimitry Andric if (EmulateOldLDV)
2035b60736ecSDimitry Andric return false;
2036b60736ecSDimitry Andric
2037c0981da4SDimitry Andric // Strictly limit ourselves to plain loads and stores, not all instructions
2038c0981da4SDimitry Andric // that can access the stack.
2039c0981da4SDimitry Andric int DummyFI = -1;
2040c0981da4SDimitry Andric if (!TII->isStoreToStackSlotPostFE(MI, DummyFI) &&
2041c0981da4SDimitry Andric !TII->isLoadFromStackSlotPostFE(MI, DummyFI))
2042c0981da4SDimitry Andric return false;
2043c0981da4SDimitry Andric
2044b60736ecSDimitry Andric MachineFunction *MF = MI.getMF();
2045b60736ecSDimitry Andric unsigned Reg;
2046b60736ecSDimitry Andric
2047b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
2048b60736ecSDimitry Andric
2049c0981da4SDimitry Andric // Strictly limit ourselves to plain loads and stores, not all instructions
2050c0981da4SDimitry Andric // that can access the stack.
2051c0981da4SDimitry Andric int FIDummy;
2052c0981da4SDimitry Andric if (!TII->isStoreToStackSlotPostFE(MI, FIDummy) &&
2053c0981da4SDimitry Andric !TII->isLoadFromStackSlotPostFE(MI, FIDummy))
2054c0981da4SDimitry Andric return false;
2055c0981da4SDimitry Andric
2056b60736ecSDimitry Andric // First, if there are any DBG_VALUEs pointing at a spill slot that is
2057b60736ecSDimitry Andric // written to, terminate that variable location. The value in memory
2058b60736ecSDimitry Andric // will have changed. DbgEntityHistoryCalculator doesn't try to detect this.
2059e3b55780SDimitry Andric if (std::optional<SpillLocationNo> Loc = isSpillInstruction(MI, MF)) {
2060c0981da4SDimitry Andric // Un-set this location and clobber, so that earlier locations don't
2061c0981da4SDimitry Andric // continue past this store.
2062c0981da4SDimitry Andric for (unsigned SlotIdx = 0; SlotIdx < MTracker->NumSlotIdxes; ++SlotIdx) {
2063145449b1SDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(*Loc, SlotIdx);
2064e3b55780SDimitry Andric std::optional<LocIdx> MLoc = MTracker->getSpillMLoc(SpillID);
2065c0981da4SDimitry Andric if (!MLoc)
2066c0981da4SDimitry Andric continue;
2067c0981da4SDimitry Andric
2068c0981da4SDimitry Andric // We need to over-write the stack slot with something (here, a def at
2069c0981da4SDimitry Andric // this instruction) to ensure no values are preserved in this stack slot
2070c0981da4SDimitry Andric // after the spill. It also prevents TTracker from trying to recover the
2071c0981da4SDimitry Andric // location and re-installing it in the same place.
2072c0981da4SDimitry Andric ValueIDNum Def(CurBB, CurInst, *MLoc);
2073c0981da4SDimitry Andric MTracker->setMLoc(*MLoc, Def);
2074c0981da4SDimitry Andric if (TTracker)
2075b60736ecSDimitry Andric TTracker->clobberMloc(*MLoc, MI.getIterator());
2076b60736ecSDimitry Andric }
2077b60736ecSDimitry Andric }
2078b60736ecSDimitry Andric
2079b60736ecSDimitry Andric // Try to recognise spill and restore instructions that may transfer a value.
2080b60736ecSDimitry Andric if (isLocationSpill(MI, MF, Reg)) {
2081145449b1SDimitry Andric // isLocationSpill returning true should guarantee we can extract a
2082145449b1SDimitry Andric // location.
2083145449b1SDimitry Andric SpillLocationNo Loc = *extractSpillBaseRegAndOffset(MI);
2084b60736ecSDimitry Andric
2085c0981da4SDimitry Andric auto DoTransfer = [&](Register SrcReg, unsigned SpillID) {
2086c0981da4SDimitry Andric auto ReadValue = MTracker->readReg(SrcReg);
2087c0981da4SDimitry Andric LocIdx DstLoc = MTracker->getSpillMLoc(SpillID);
2088c0981da4SDimitry Andric MTracker->setMLoc(DstLoc, ReadValue);
2089b60736ecSDimitry Andric
2090c0981da4SDimitry Andric if (TTracker) {
2091c0981da4SDimitry Andric LocIdx SrcLoc = MTracker->getRegMLoc(SrcReg);
2092c0981da4SDimitry Andric TTracker->transferMlocs(SrcLoc, DstLoc, MI.getIterator());
2093b60736ecSDimitry Andric }
2094c0981da4SDimitry Andric };
2095c0981da4SDimitry Andric
2096c0981da4SDimitry Andric // Then, transfer subreg bits.
20977fa27ce4SDimitry Andric for (MCPhysReg SR : TRI->subregs(Reg)) {
2098c0981da4SDimitry Andric // Ensure this reg is tracked,
20997fa27ce4SDimitry Andric (void)MTracker->lookupOrTrackRegister(SR);
21007fa27ce4SDimitry Andric unsigned SubregIdx = TRI->getSubRegIndex(Reg, SR);
2101c0981da4SDimitry Andric unsigned SpillID = MTracker->getLocID(Loc, SubregIdx);
21027fa27ce4SDimitry Andric DoTransfer(SR, SpillID);
2103c0981da4SDimitry Andric }
2104c0981da4SDimitry Andric
2105c0981da4SDimitry Andric // Directly lookup size of main source reg, and transfer.
2106c0981da4SDimitry Andric unsigned Size = TRI->getRegSizeInBits(Reg, *MRI);
2107c0981da4SDimitry Andric unsigned SpillID = MTracker->getLocID(Loc, {Size, 0});
2108c0981da4SDimitry Andric DoTransfer(Reg, SpillID);
2109c0981da4SDimitry Andric } else {
2110e3b55780SDimitry Andric std::optional<SpillLocationNo> Loc = isRestoreInstruction(MI, MF, Reg);
2111145449b1SDimitry Andric if (!Loc)
2112c0981da4SDimitry Andric return false;
2113c0981da4SDimitry Andric
2114c0981da4SDimitry Andric // Assumption: we're reading from the base of the stack slot, not some
2115c0981da4SDimitry Andric // offset into it. It seems very unlikely LLVM would ever generate
2116c0981da4SDimitry Andric // restores where this wasn't true. This then becomes a question of what
2117c0981da4SDimitry Andric // subregisters in the destination register line up with positions in the
2118c0981da4SDimitry Andric // stack slot.
2119c0981da4SDimitry Andric
2120c0981da4SDimitry Andric // Def all registers that alias the destination.
2121c0981da4SDimitry Andric for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
2122c0981da4SDimitry Andric MTracker->defReg(*RAI, CurBB, CurInst);
2123c0981da4SDimitry Andric
2124c0981da4SDimitry Andric // Now find subregisters within the destination register, and load values
2125c0981da4SDimitry Andric // from stack slot positions.
2126c0981da4SDimitry Andric auto DoTransfer = [&](Register DestReg, unsigned SpillID) {
2127c0981da4SDimitry Andric LocIdx SrcIdx = MTracker->getSpillMLoc(SpillID);
2128c0981da4SDimitry Andric auto ReadValue = MTracker->readMLoc(SrcIdx);
2129c0981da4SDimitry Andric MTracker->setReg(DestReg, ReadValue);
2130c0981da4SDimitry Andric };
2131c0981da4SDimitry Andric
21327fa27ce4SDimitry Andric for (MCPhysReg SR : TRI->subregs(Reg)) {
21337fa27ce4SDimitry Andric unsigned Subreg = TRI->getSubRegIndex(Reg, SR);
2134145449b1SDimitry Andric unsigned SpillID = MTracker->getLocID(*Loc, Subreg);
21357fa27ce4SDimitry Andric DoTransfer(SR, SpillID);
2136c0981da4SDimitry Andric }
2137c0981da4SDimitry Andric
2138c0981da4SDimitry Andric // Directly look up this registers slot idx by size, and transfer.
2139c0981da4SDimitry Andric unsigned Size = TRI->getRegSizeInBits(Reg, *MRI);
2140145449b1SDimitry Andric unsigned SpillID = MTracker->getLocID(*Loc, {Size, 0});
2141c0981da4SDimitry Andric DoTransfer(Reg, SpillID);
2142b60736ecSDimitry Andric }
2143b60736ecSDimitry Andric return true;
2144b60736ecSDimitry Andric }
2145b60736ecSDimitry Andric
transferRegisterCopy(MachineInstr & MI)2146b60736ecSDimitry Andric bool InstrRefBasedLDV::transferRegisterCopy(MachineInstr &MI) {
2147312c0ed1SDimitry Andric auto DestSrc = TII->isCopyLikeInstr(MI);
2148b60736ecSDimitry Andric if (!DestSrc)
2149b60736ecSDimitry Andric return false;
2150b60736ecSDimitry Andric
2151b60736ecSDimitry Andric const MachineOperand *DestRegOp = DestSrc->Destination;
2152b60736ecSDimitry Andric const MachineOperand *SrcRegOp = DestSrc->Source;
2153b60736ecSDimitry Andric
2154b60736ecSDimitry Andric Register SrcReg = SrcRegOp->getReg();
2155b60736ecSDimitry Andric Register DestReg = DestRegOp->getReg();
2156b60736ecSDimitry Andric
2157b60736ecSDimitry Andric // Ignore identity copies. Yep, these make it as far as LiveDebugValues.
2158b60736ecSDimitry Andric if (SrcReg == DestReg)
2159b60736ecSDimitry Andric return true;
2160b60736ecSDimitry Andric
2161b60736ecSDimitry Andric // For emulating VarLocBasedImpl:
2162b60736ecSDimitry Andric // We want to recognize instructions where destination register is callee
2163b60736ecSDimitry Andric // saved register. If register that could be clobbered by the call is
2164b60736ecSDimitry Andric // included, there would be a great chance that it is going to be clobbered
2165b60736ecSDimitry Andric // soon. It is more likely that previous register, which is callee saved, is
2166b60736ecSDimitry Andric // going to stay unclobbered longer, even if it is killed.
2167b60736ecSDimitry Andric //
2168b60736ecSDimitry Andric // For InstrRefBasedImpl, we can track multiple locations per value, so
2169b60736ecSDimitry Andric // ignore this condition.
2170b60736ecSDimitry Andric if (EmulateOldLDV && !isCalleeSavedReg(DestReg))
2171b60736ecSDimitry Andric return false;
2172b60736ecSDimitry Andric
2173b60736ecSDimitry Andric // InstrRefBasedImpl only followed killing copies.
2174b60736ecSDimitry Andric if (EmulateOldLDV && !SrcRegOp->isKill())
2175b60736ecSDimitry Andric return false;
2176b60736ecSDimitry Andric
21771f917f69SDimitry Andric // Before we update MTracker, remember which values were present in each of
21781f917f69SDimitry Andric // the locations about to be overwritten, so that we can recover any
21791f917f69SDimitry Andric // potentially clobbered variables.
21801f917f69SDimitry Andric DenseMap<LocIdx, ValueIDNum> ClobberedLocs;
21811f917f69SDimitry Andric if (TTracker) {
21821f917f69SDimitry Andric for (MCRegAliasIterator RAI(DestReg, TRI, true); RAI.isValid(); ++RAI) {
21831f917f69SDimitry Andric LocIdx ClobberedLoc = MTracker->getRegMLoc(*RAI);
21841f917f69SDimitry Andric auto MLocIt = TTracker->ActiveMLocs.find(ClobberedLoc);
21851f917f69SDimitry Andric // If ActiveMLocs isn't tracking this location or there are no variables
21861f917f69SDimitry Andric // using it, don't bother remembering.
21871f917f69SDimitry Andric if (MLocIt == TTracker->ActiveMLocs.end() || MLocIt->second.empty())
21881f917f69SDimitry Andric continue;
21891f917f69SDimitry Andric ValueIDNum Value = MTracker->readReg(*RAI);
21901f917f69SDimitry Andric ClobberedLocs[ClobberedLoc] = Value;
21911f917f69SDimitry Andric }
21921f917f69SDimitry Andric }
21931f917f69SDimitry Andric
2194b60736ecSDimitry Andric // Copy MTracker info, including subregs if available.
2195b60736ecSDimitry Andric InstrRefBasedLDV::performCopy(SrcReg, DestReg);
2196b60736ecSDimitry Andric
21971f917f69SDimitry Andric // The copy might have clobbered variables based on the destination register.
21981f917f69SDimitry Andric // Tell TTracker about it, passing the old ValueIDNum to search for
21991f917f69SDimitry Andric // alternative locations (or else terminating those variables).
22001f917f69SDimitry Andric if (TTracker) {
22011f917f69SDimitry Andric for (auto LocVal : ClobberedLocs) {
22021f917f69SDimitry Andric TTracker->clobberMloc(LocVal.first, LocVal.second, MI.getIterator(), false);
22031f917f69SDimitry Andric }
22041f917f69SDimitry Andric }
22051f917f69SDimitry Andric
2206b60736ecSDimitry Andric // Only produce a transfer of DBG_VALUE within a block where old LDV
2207b60736ecSDimitry Andric // would have. We might make use of the additional value tracking in some
2208b60736ecSDimitry Andric // other way, later.
2209b60736ecSDimitry Andric if (TTracker && isCalleeSavedReg(DestReg) && SrcRegOp->isKill())
2210b60736ecSDimitry Andric TTracker->transferMlocs(MTracker->getRegMLoc(SrcReg),
2211b60736ecSDimitry Andric MTracker->getRegMLoc(DestReg), MI.getIterator());
2212b60736ecSDimitry Andric
2213b60736ecSDimitry Andric // VarLocBasedImpl would quit tracking the old location after copying.
2214b60736ecSDimitry Andric if (EmulateOldLDV && SrcReg != DestReg)
2215b60736ecSDimitry Andric MTracker->defReg(SrcReg, CurBB, CurInst);
2216b60736ecSDimitry Andric
2217b60736ecSDimitry Andric return true;
2218b60736ecSDimitry Andric }
2219b60736ecSDimitry Andric
2220b60736ecSDimitry Andric /// Accumulate a mapping between each DILocalVariable fragment and other
2221b60736ecSDimitry Andric /// fragments of that DILocalVariable which overlap. This reduces work during
2222b60736ecSDimitry Andric /// the data-flow stage from "Find any overlapping fragments" to "Check if the
2223b60736ecSDimitry Andric /// known-to-overlap fragments are present".
2224f65dcba8SDimitry Andric /// \param MI A previously unprocessed debug instruction to analyze for
2225b60736ecSDimitry Andric /// fragment usage.
accumulateFragmentMap(MachineInstr & MI)2226b60736ecSDimitry Andric void InstrRefBasedLDV::accumulateFragmentMap(MachineInstr &MI) {
2227e3b55780SDimitry Andric assert(MI.isDebugValueLike());
2228b60736ecSDimitry Andric DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(),
2229b60736ecSDimitry Andric MI.getDebugLoc()->getInlinedAt());
2230b60736ecSDimitry Andric FragmentInfo ThisFragment = MIVar.getFragmentOrDefault();
2231b60736ecSDimitry Andric
2232b60736ecSDimitry Andric // If this is the first sighting of this variable, then we are guaranteed
2233b60736ecSDimitry Andric // there are currently no overlapping fragments either. Initialize the set
2234b60736ecSDimitry Andric // of seen fragments, record no overlaps for the current one, and return.
2235b60736ecSDimitry Andric auto SeenIt = SeenFragments.find(MIVar.getVariable());
2236b60736ecSDimitry Andric if (SeenIt == SeenFragments.end()) {
2237b60736ecSDimitry Andric SmallSet<FragmentInfo, 4> OneFragment;
2238b60736ecSDimitry Andric OneFragment.insert(ThisFragment);
2239b60736ecSDimitry Andric SeenFragments.insert({MIVar.getVariable(), OneFragment});
2240b60736ecSDimitry Andric
2241b60736ecSDimitry Andric OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
2242b60736ecSDimitry Andric return;
2243b60736ecSDimitry Andric }
2244b60736ecSDimitry Andric
2245b60736ecSDimitry Andric // If this particular Variable/Fragment pair already exists in the overlap
2246b60736ecSDimitry Andric // map, it has already been accounted for.
2247b60736ecSDimitry Andric auto IsInOLapMap =
2248b60736ecSDimitry Andric OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
2249b60736ecSDimitry Andric if (!IsInOLapMap.second)
2250b60736ecSDimitry Andric return;
2251b60736ecSDimitry Andric
2252b60736ecSDimitry Andric auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
2253b60736ecSDimitry Andric auto &AllSeenFragments = SeenIt->second;
2254b60736ecSDimitry Andric
2255b60736ecSDimitry Andric // Otherwise, examine all other seen fragments for this variable, with "this"
2256b60736ecSDimitry Andric // fragment being a previously unseen fragment. Record any pair of
2257b60736ecSDimitry Andric // overlapping fragments.
22584b4fe385SDimitry Andric for (const auto &ASeenFragment : AllSeenFragments) {
2259b60736ecSDimitry Andric // Does this previously seen fragment overlap?
2260b60736ecSDimitry Andric if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
2261b60736ecSDimitry Andric // Yes: Mark the current fragment as being overlapped.
2262b60736ecSDimitry Andric ThisFragmentsOverlaps.push_back(ASeenFragment);
2263b60736ecSDimitry Andric // Mark the previously seen fragment as being overlapped by the current
2264b60736ecSDimitry Andric // one.
2265b60736ecSDimitry Andric auto ASeenFragmentsOverlaps =
2266b60736ecSDimitry Andric OverlapFragments.find({MIVar.getVariable(), ASeenFragment});
2267b60736ecSDimitry Andric assert(ASeenFragmentsOverlaps != OverlapFragments.end() &&
2268b60736ecSDimitry Andric "Previously seen var fragment has no vector of overlaps");
2269b60736ecSDimitry Andric ASeenFragmentsOverlaps->second.push_back(ThisFragment);
2270b60736ecSDimitry Andric }
2271b60736ecSDimitry Andric }
2272b60736ecSDimitry Andric
2273b60736ecSDimitry Andric AllSeenFragments.insert(ThisFragment);
2274b60736ecSDimitry Andric }
2275b60736ecSDimitry Andric
process(MachineInstr & MI,const FuncValueTable * MLiveOuts,const FuncValueTable * MLiveIns)2276312c0ed1SDimitry Andric void InstrRefBasedLDV::process(MachineInstr &MI,
2277312c0ed1SDimitry Andric const FuncValueTable *MLiveOuts,
2278312c0ed1SDimitry Andric const FuncValueTable *MLiveIns) {
2279b60736ecSDimitry Andric // Try to interpret an MI as a debug or transfer instruction. Only if it's
2280b60736ecSDimitry Andric // none of these should we interpret it's register defs as new value
2281b60736ecSDimitry Andric // definitions.
2282b60736ecSDimitry Andric if (transferDebugValue(MI))
2283b60736ecSDimitry Andric return;
2284344a3780SDimitry Andric if (transferDebugInstrRef(MI, MLiveOuts, MLiveIns))
2285344a3780SDimitry Andric return;
2286344a3780SDimitry Andric if (transferDebugPHI(MI))
2287b60736ecSDimitry Andric return;
2288b60736ecSDimitry Andric if (transferRegisterCopy(MI))
2289b60736ecSDimitry Andric return;
2290b60736ecSDimitry Andric if (transferSpillOrRestoreInst(MI))
2291b60736ecSDimitry Andric return;
2292b60736ecSDimitry Andric transferRegisterDef(MI);
2293b60736ecSDimitry Andric }
2294b60736ecSDimitry Andric
produceMLocTransferFunction(MachineFunction & MF,SmallVectorImpl<MLocTransferMap> & MLocTransfer,unsigned MaxNumBlocks)2295b60736ecSDimitry Andric void InstrRefBasedLDV::produceMLocTransferFunction(
2296b60736ecSDimitry Andric MachineFunction &MF, SmallVectorImpl<MLocTransferMap> &MLocTransfer,
2297b60736ecSDimitry Andric unsigned MaxNumBlocks) {
2298b60736ecSDimitry Andric // Because we try to optimize around register mask operands by ignoring regs
2299b60736ecSDimitry Andric // that aren't currently tracked, we set up something ugly for later: RegMask
2300b60736ecSDimitry Andric // operands that are seen earlier than the first use of a register, still need
2301b60736ecSDimitry Andric // to clobber that register in the transfer function. But this information
2302b60736ecSDimitry Andric // isn't actively recorded. Instead, we track each RegMask used in each block,
2303b60736ecSDimitry Andric // and accumulated the clobbered but untracked registers in each block into
2304b60736ecSDimitry Andric // the following bitvector. Later, if new values are tracked, we can add
2305b60736ecSDimitry Andric // appropriate clobbers.
2306b60736ecSDimitry Andric SmallVector<BitVector, 32> BlockMasks;
2307b60736ecSDimitry Andric BlockMasks.resize(MaxNumBlocks);
2308b60736ecSDimitry Andric
2309b60736ecSDimitry Andric // Reserve one bit per register for the masks described above.
2310b60736ecSDimitry Andric unsigned BVWords = MachineOperand::getRegMaskSize(TRI->getNumRegs());
2311b60736ecSDimitry Andric for (auto &BV : BlockMasks)
2312b60736ecSDimitry Andric BV.resize(TRI->getNumRegs(), true);
2313b60736ecSDimitry Andric
2314b60736ecSDimitry Andric // Step through all instructions and inhale the transfer function.
2315b60736ecSDimitry Andric for (auto &MBB : MF) {
2316b60736ecSDimitry Andric // Object fields that are read by trackers to know where we are in the
2317b60736ecSDimitry Andric // function.
2318b60736ecSDimitry Andric CurBB = MBB.getNumber();
2319b60736ecSDimitry Andric CurInst = 1;
2320b60736ecSDimitry Andric
2321b60736ecSDimitry Andric // Set all machine locations to a PHI value. For transfer function
2322b60736ecSDimitry Andric // production only, this signifies the live-in value to the block.
2323b60736ecSDimitry Andric MTracker->reset();
2324b60736ecSDimitry Andric MTracker->setMPhis(CurBB);
2325b60736ecSDimitry Andric
2326b60736ecSDimitry Andric // Step through each instruction in this block.
2327b60736ecSDimitry Andric for (auto &MI : MBB) {
2328145449b1SDimitry Andric // Pass in an empty unique_ptr for the value tables when accumulating the
2329145449b1SDimitry Andric // machine transfer function.
2330145449b1SDimitry Andric process(MI, nullptr, nullptr);
2331145449b1SDimitry Andric
2332b60736ecSDimitry Andric // Also accumulate fragment map.
2333e3b55780SDimitry Andric if (MI.isDebugValueLike())
2334b60736ecSDimitry Andric accumulateFragmentMap(MI);
2335b60736ecSDimitry Andric
2336b60736ecSDimitry Andric // Create a map from the instruction number (if present) to the
2337b60736ecSDimitry Andric // MachineInstr and its position.
2338b60736ecSDimitry Andric if (uint64_t InstrNo = MI.peekDebugInstrNum()) {
2339b60736ecSDimitry Andric auto InstrAndPos = std::make_pair(&MI, CurInst);
2340b60736ecSDimitry Andric auto InsertResult =
2341b60736ecSDimitry Andric DebugInstrNumToInstr.insert(std::make_pair(InstrNo, InstrAndPos));
2342b60736ecSDimitry Andric
2343b60736ecSDimitry Andric // There should never be duplicate instruction numbers.
2344b60736ecSDimitry Andric assert(InsertResult.second);
2345b60736ecSDimitry Andric (void)InsertResult;
2346b60736ecSDimitry Andric }
2347b60736ecSDimitry Andric
2348b60736ecSDimitry Andric ++CurInst;
2349b60736ecSDimitry Andric }
2350b60736ecSDimitry Andric
2351b60736ecSDimitry Andric // Produce the transfer function, a map of machine location to new value. If
2352b60736ecSDimitry Andric // any machine location has the live-in phi value from the start of the
2353b60736ecSDimitry Andric // block, it's live-through and doesn't need recording in the transfer
2354b60736ecSDimitry Andric // function.
2355b60736ecSDimitry Andric for (auto Location : MTracker->locations()) {
2356b60736ecSDimitry Andric LocIdx Idx = Location.Idx;
2357b60736ecSDimitry Andric ValueIDNum &P = Location.Value;
2358b60736ecSDimitry Andric if (P.isPHI() && P.getLoc() == Idx.asU64())
2359b60736ecSDimitry Andric continue;
2360b60736ecSDimitry Andric
2361b60736ecSDimitry Andric // Insert-or-update.
2362b60736ecSDimitry Andric auto &TransferMap = MLocTransfer[CurBB];
2363b60736ecSDimitry Andric auto Result = TransferMap.insert(std::make_pair(Idx.asU64(), P));
2364b60736ecSDimitry Andric if (!Result.second)
2365b60736ecSDimitry Andric Result.first->second = P;
2366b60736ecSDimitry Andric }
2367b60736ecSDimitry Andric
2368e3b55780SDimitry Andric // Accumulate any bitmask operands into the clobbered reg mask for this
2369b60736ecSDimitry Andric // block.
2370b60736ecSDimitry Andric for (auto &P : MTracker->Masks) {
2371b60736ecSDimitry Andric BlockMasks[CurBB].clearBitsNotInMask(P.first->getRegMask(), BVWords);
2372b60736ecSDimitry Andric }
2373b60736ecSDimitry Andric }
2374b60736ecSDimitry Andric
2375b60736ecSDimitry Andric // Compute a bitvector of all the registers that are tracked in this block.
2376b60736ecSDimitry Andric BitVector UsedRegs(TRI->getNumRegs());
2377b60736ecSDimitry Andric for (auto Location : MTracker->locations()) {
2378b60736ecSDimitry Andric unsigned ID = MTracker->LocIdxToLocID[Location.Idx];
2379c0981da4SDimitry Andric // Ignore stack slots, and aliases of the stack pointer.
2380c0981da4SDimitry Andric if (ID >= TRI->getNumRegs() || MTracker->SPAliases.count(ID))
2381b60736ecSDimitry Andric continue;
2382b60736ecSDimitry Andric UsedRegs.set(ID);
2383b60736ecSDimitry Andric }
2384b60736ecSDimitry Andric
2385b60736ecSDimitry Andric // Check that any regmask-clobber of a register that gets tracked, is not
2386b60736ecSDimitry Andric // live-through in the transfer function. It needs to be clobbered at the
2387b60736ecSDimitry Andric // very least.
2388b60736ecSDimitry Andric for (unsigned int I = 0; I < MaxNumBlocks; ++I) {
2389b60736ecSDimitry Andric BitVector &BV = BlockMasks[I];
2390b60736ecSDimitry Andric BV.flip();
2391b60736ecSDimitry Andric BV &= UsedRegs;
2392b60736ecSDimitry Andric // This produces all the bits that we clobber, but also use. Check that
2393b60736ecSDimitry Andric // they're all clobbered or at least set in the designated transfer
2394b60736ecSDimitry Andric // elem.
2395b60736ecSDimitry Andric for (unsigned Bit : BV.set_bits()) {
2396c0981da4SDimitry Andric unsigned ID = MTracker->getLocID(Bit);
2397b60736ecSDimitry Andric LocIdx Idx = MTracker->LocIDToLocIdx[ID];
2398b60736ecSDimitry Andric auto &TransferMap = MLocTransfer[I];
2399b60736ecSDimitry Andric
2400b60736ecSDimitry Andric // Install a value representing the fact that this location is effectively
2401b60736ecSDimitry Andric // written to in this block. As there's no reserved value, instead use
2402b60736ecSDimitry Andric // a value number that is never generated. Pick the value number for the
2403b60736ecSDimitry Andric // first instruction in the block, def'ing this location, which we know
2404b60736ecSDimitry Andric // this block never used anyway.
2405b60736ecSDimitry Andric ValueIDNum NotGeneratedNum = ValueIDNum(I, 1, Idx);
2406b60736ecSDimitry Andric auto Result =
2407b60736ecSDimitry Andric TransferMap.insert(std::make_pair(Idx.asU64(), NotGeneratedNum));
2408b60736ecSDimitry Andric if (!Result.second) {
2409b60736ecSDimitry Andric ValueIDNum &ValueID = Result.first->second;
2410b60736ecSDimitry Andric if (ValueID.getBlock() == I && ValueID.isPHI())
2411b60736ecSDimitry Andric // It was left as live-through. Set it to clobbered.
2412b60736ecSDimitry Andric ValueID = NotGeneratedNum;
2413b60736ecSDimitry Andric }
2414b60736ecSDimitry Andric }
2415b60736ecSDimitry Andric }
2416b60736ecSDimitry Andric }
2417b60736ecSDimitry Andric
mlocJoin(MachineBasicBlock & MBB,SmallPtrSet<const MachineBasicBlock *,16> & Visited,FuncValueTable & OutLocs,ValueTable & InLocs)2418c0981da4SDimitry Andric bool InstrRefBasedLDV::mlocJoin(
2419c0981da4SDimitry Andric MachineBasicBlock &MBB, SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
2420145449b1SDimitry Andric FuncValueTable &OutLocs, ValueTable &InLocs) {
2421b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
2422b60736ecSDimitry Andric bool Changed = false;
2423b60736ecSDimitry Andric
2424c0981da4SDimitry Andric // Handle value-propagation when control flow merges on entry to a block. For
2425c0981da4SDimitry Andric // any location without a PHI already placed, the location has the same value
2426c0981da4SDimitry Andric // as its predecessors. If a PHI is placed, test to see whether it's now a
2427c0981da4SDimitry Andric // redundant PHI that we can eliminate.
2428c0981da4SDimitry Andric
2429b60736ecSDimitry Andric SmallVector<const MachineBasicBlock *, 8> BlockOrders;
24304b4fe385SDimitry Andric for (auto *Pred : MBB.predecessors())
2431b60736ecSDimitry Andric BlockOrders.push_back(Pred);
2432b60736ecSDimitry Andric
2433b60736ecSDimitry Andric // Visit predecessors in RPOT order.
2434b60736ecSDimitry Andric auto Cmp = [&](const MachineBasicBlock *A, const MachineBasicBlock *B) {
2435b60736ecSDimitry Andric return BBToOrder.find(A)->second < BBToOrder.find(B)->second;
2436b60736ecSDimitry Andric };
2437b60736ecSDimitry Andric llvm::sort(BlockOrders, Cmp);
2438b60736ecSDimitry Andric
2439b60736ecSDimitry Andric // Skip entry block.
2440950076cdSDimitry Andric if (BlockOrders.size() == 0) {
2441950076cdSDimitry Andric // FIXME: We don't use assert here to prevent instr-ref-unreachable.mir
2442950076cdSDimitry Andric // failing.
2443950076cdSDimitry Andric LLVM_DEBUG(if (!MBB.isEntryBlock()) dbgs()
2444950076cdSDimitry Andric << "Found not reachable block " << MBB.getFullName()
2445950076cdSDimitry Andric << " from entry which may lead out of "
2446950076cdSDimitry Andric "bound access to VarLocs\n");
2447c0981da4SDimitry Andric return false;
2448950076cdSDimitry Andric }
2449b60736ecSDimitry Andric
2450c0981da4SDimitry Andric // Step through all machine locations, look at each predecessor and test
2451c0981da4SDimitry Andric // whether we can eliminate redundant PHIs.
2452b60736ecSDimitry Andric for (auto Location : MTracker->locations()) {
2453b60736ecSDimitry Andric LocIdx Idx = Location.Idx;
2454c0981da4SDimitry Andric
2455b60736ecSDimitry Andric // Pick out the first predecessors live-out value for this location. It's
2456c0981da4SDimitry Andric // guaranteed to not be a backedge, as we order by RPO.
245799aabd70SDimitry Andric ValueIDNum FirstVal = OutLocs[*BlockOrders[0]][Idx.asU64()];
2458b60736ecSDimitry Andric
2459c0981da4SDimitry Andric // If we've already eliminated a PHI here, do no further checking, just
2460c0981da4SDimitry Andric // propagate the first live-in value into this block.
2461c0981da4SDimitry Andric if (InLocs[Idx.asU64()] != ValueIDNum(MBB.getNumber(), 0, Idx)) {
2462c0981da4SDimitry Andric if (InLocs[Idx.asU64()] != FirstVal) {
2463c0981da4SDimitry Andric InLocs[Idx.asU64()] = FirstVal;
2464c0981da4SDimitry Andric Changed |= true;
2465c0981da4SDimitry Andric }
2466c0981da4SDimitry Andric continue;
2467c0981da4SDimitry Andric }
2468c0981da4SDimitry Andric
2469c0981da4SDimitry Andric // We're now examining a PHI to see whether it's un-necessary. Loop around
2470c0981da4SDimitry Andric // the other live-in values and test whether they're all the same.
2471b60736ecSDimitry Andric bool Disagree = false;
2472b60736ecSDimitry Andric for (unsigned int I = 1; I < BlockOrders.size(); ++I) {
2473c0981da4SDimitry Andric const MachineBasicBlock *PredMBB = BlockOrders[I];
247499aabd70SDimitry Andric const ValueIDNum &PredLiveOut = OutLocs[*PredMBB][Idx.asU64()];
2475c0981da4SDimitry Andric
2476c0981da4SDimitry Andric // Incoming values agree, continue trying to eliminate this PHI.
2477c0981da4SDimitry Andric if (FirstVal == PredLiveOut)
2478c0981da4SDimitry Andric continue;
2479c0981da4SDimitry Andric
2480c0981da4SDimitry Andric // We can also accept a PHI value that feeds back into itself.
2481c0981da4SDimitry Andric if (PredLiveOut == ValueIDNum(MBB.getNumber(), 0, Idx))
2482c0981da4SDimitry Andric continue;
2483c0981da4SDimitry Andric
2484b60736ecSDimitry Andric // Live-out of a predecessor disagrees with the first predecessor.
2485b60736ecSDimitry Andric Disagree = true;
2486b60736ecSDimitry Andric }
2487b60736ecSDimitry Andric
2488c0981da4SDimitry Andric // No disagreement? No PHI. Otherwise, leave the PHI in live-ins.
2489c0981da4SDimitry Andric if (!Disagree) {
2490c0981da4SDimitry Andric InLocs[Idx.asU64()] = FirstVal;
2491b60736ecSDimitry Andric Changed |= true;
2492b60736ecSDimitry Andric }
2493b60736ecSDimitry Andric }
2494b60736ecSDimitry Andric
2495b60736ecSDimitry Andric // TODO: Reimplement NumInserted and NumRemoved.
2496c0981da4SDimitry Andric return Changed;
2497b60736ecSDimitry Andric }
2498b60736ecSDimitry Andric
findStackIndexInterference(SmallVectorImpl<unsigned> & Slots)2499c0981da4SDimitry Andric void InstrRefBasedLDV::findStackIndexInterference(
2500c0981da4SDimitry Andric SmallVectorImpl<unsigned> &Slots) {
2501c0981da4SDimitry Andric // We could spend a bit of time finding the exact, minimal, set of stack
2502c0981da4SDimitry Andric // indexes that interfere with each other, much like reg units. Or, we can
2503c0981da4SDimitry Andric // rely on the fact that:
2504c0981da4SDimitry Andric // * The smallest / lowest index will interfere with everything at zero
2505c0981da4SDimitry Andric // offset, which will be the largest set of registers,
2506c0981da4SDimitry Andric // * Most indexes with non-zero offset will end up being interference units
2507c0981da4SDimitry Andric // anyway.
2508c0981da4SDimitry Andric // So just pick those out and return them.
2509c0981da4SDimitry Andric
2510c0981da4SDimitry Andric // We can rely on a single-byte stack index existing already, because we
2511c0981da4SDimitry Andric // initialize them in MLocTracker.
2512c0981da4SDimitry Andric auto It = MTracker->StackSlotIdxes.find({8, 0});
2513c0981da4SDimitry Andric assert(It != MTracker->StackSlotIdxes.end());
2514c0981da4SDimitry Andric Slots.push_back(It->second);
2515c0981da4SDimitry Andric
2516c0981da4SDimitry Andric // Find anything that has a non-zero offset and add that too.
2517c0981da4SDimitry Andric for (auto &Pair : MTracker->StackSlotIdxes) {
2518c0981da4SDimitry Andric // Is offset zero? If so, ignore.
2519c0981da4SDimitry Andric if (!Pair.first.second)
2520c0981da4SDimitry Andric continue;
2521c0981da4SDimitry Andric Slots.push_back(Pair.second);
2522c0981da4SDimitry Andric }
2523c0981da4SDimitry Andric }
2524c0981da4SDimitry Andric
placeMLocPHIs(MachineFunction & MF,SmallPtrSetImpl<MachineBasicBlock * > & AllBlocks,FuncValueTable & MInLocs,SmallVectorImpl<MLocTransferMap> & MLocTransfer)2525c0981da4SDimitry Andric void InstrRefBasedLDV::placeMLocPHIs(
2526c0981da4SDimitry Andric MachineFunction &MF, SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
2527145449b1SDimitry Andric FuncValueTable &MInLocs, SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
2528c0981da4SDimitry Andric SmallVector<unsigned, 4> StackUnits;
2529c0981da4SDimitry Andric findStackIndexInterference(StackUnits);
2530c0981da4SDimitry Andric
2531c0981da4SDimitry Andric // To avoid repeatedly running the PHI placement algorithm, leverage the
2532c0981da4SDimitry Andric // fact that a def of register MUST also def its register units. Find the
2533c0981da4SDimitry Andric // units for registers, place PHIs for them, and then replicate them for
2534c0981da4SDimitry Andric // aliasing registers. Some inputs that are never def'd (DBG_PHIs of
2535c0981da4SDimitry Andric // arguments) don't lead to register units being tracked, just place PHIs for
2536c0981da4SDimitry Andric // those registers directly. Stack slots have their own form of "unit",
2537c0981da4SDimitry Andric // store them to one side.
2538c0981da4SDimitry Andric SmallSet<Register, 32> RegUnitsToPHIUp;
2539c0981da4SDimitry Andric SmallSet<LocIdx, 32> NormalLocsToPHI;
2540c0981da4SDimitry Andric SmallSet<SpillLocationNo, 32> StackSlots;
2541c0981da4SDimitry Andric for (auto Location : MTracker->locations()) {
2542c0981da4SDimitry Andric LocIdx L = Location.Idx;
2543c0981da4SDimitry Andric if (MTracker->isSpill(L)) {
2544c0981da4SDimitry Andric StackSlots.insert(MTracker->locIDToSpill(MTracker->LocIdxToLocID[L]));
2545c0981da4SDimitry Andric continue;
2546c0981da4SDimitry Andric }
2547c0981da4SDimitry Andric
2548c0981da4SDimitry Andric Register R = MTracker->LocIdxToLocID[L];
2549c0981da4SDimitry Andric SmallSet<Register, 8> FoundRegUnits;
2550c0981da4SDimitry Andric bool AnyIllegal = false;
25517fa27ce4SDimitry Andric for (MCRegUnit Unit : TRI->regunits(R.asMCReg())) {
25527fa27ce4SDimitry Andric for (MCRegUnitRootIterator URoot(Unit, TRI); URoot.isValid(); ++URoot) {
2553c0981da4SDimitry Andric if (!MTracker->isRegisterTracked(*URoot)) {
2554c0981da4SDimitry Andric // Not all roots were loaded into the tracking map: this register
2555c0981da4SDimitry Andric // isn't actually def'd anywhere, we only read from it. Generate PHIs
2556c0981da4SDimitry Andric // for this reg, but don't iterate units.
2557c0981da4SDimitry Andric AnyIllegal = true;
2558c0981da4SDimitry Andric } else {
2559c0981da4SDimitry Andric FoundRegUnits.insert(*URoot);
2560c0981da4SDimitry Andric }
2561c0981da4SDimitry Andric }
2562c0981da4SDimitry Andric }
2563c0981da4SDimitry Andric
2564c0981da4SDimitry Andric if (AnyIllegal) {
2565c0981da4SDimitry Andric NormalLocsToPHI.insert(L);
2566c0981da4SDimitry Andric continue;
2567c0981da4SDimitry Andric }
2568c0981da4SDimitry Andric
2569c0981da4SDimitry Andric RegUnitsToPHIUp.insert(FoundRegUnits.begin(), FoundRegUnits.end());
2570c0981da4SDimitry Andric }
2571c0981da4SDimitry Andric
2572c0981da4SDimitry Andric // Lambda to fetch PHIs for a given location, and write into the PHIBlocks
2573c0981da4SDimitry Andric // collection.
2574c0981da4SDimitry Andric SmallVector<MachineBasicBlock *, 32> PHIBlocks;
2575c0981da4SDimitry Andric auto CollectPHIsForLoc = [&](LocIdx L) {
2576c0981da4SDimitry Andric // Collect the set of defs.
2577c0981da4SDimitry Andric SmallPtrSet<MachineBasicBlock *, 32> DefBlocks;
2578c0981da4SDimitry Andric for (unsigned int I = 0; I < OrderToBB.size(); ++I) {
2579c0981da4SDimitry Andric MachineBasicBlock *MBB = OrderToBB[I];
2580c0981da4SDimitry Andric const auto &TransferFunc = MLocTransfer[MBB->getNumber()];
2581b1c73532SDimitry Andric if (TransferFunc.contains(L))
2582c0981da4SDimitry Andric DefBlocks.insert(MBB);
2583c0981da4SDimitry Andric }
2584c0981da4SDimitry Andric
2585c0981da4SDimitry Andric // The entry block defs the location too: it's the live-in / argument value.
2586c0981da4SDimitry Andric // Only insert if there are other defs though; everything is trivially live
2587c0981da4SDimitry Andric // through otherwise.
2588c0981da4SDimitry Andric if (!DefBlocks.empty())
2589c0981da4SDimitry Andric DefBlocks.insert(&*MF.begin());
2590c0981da4SDimitry Andric
2591c0981da4SDimitry Andric // Ask the SSA construction algorithm where we should put PHIs. Clear
2592c0981da4SDimitry Andric // anything that might have been hanging around from earlier.
2593c0981da4SDimitry Andric PHIBlocks.clear();
2594c0981da4SDimitry Andric BlockPHIPlacement(AllBlocks, DefBlocks, PHIBlocks);
2595c0981da4SDimitry Andric };
2596c0981da4SDimitry Andric
2597c0981da4SDimitry Andric auto InstallPHIsAtLoc = [&PHIBlocks, &MInLocs](LocIdx L) {
2598c0981da4SDimitry Andric for (const MachineBasicBlock *MBB : PHIBlocks)
259999aabd70SDimitry Andric MInLocs[*MBB][L.asU64()] = ValueIDNum(MBB->getNumber(), 0, L);
2600c0981da4SDimitry Andric };
2601c0981da4SDimitry Andric
2602c0981da4SDimitry Andric // For locations with no reg units, just place PHIs.
2603c0981da4SDimitry Andric for (LocIdx L : NormalLocsToPHI) {
2604c0981da4SDimitry Andric CollectPHIsForLoc(L);
2605c0981da4SDimitry Andric // Install those PHI values into the live-in value array.
2606c0981da4SDimitry Andric InstallPHIsAtLoc(L);
2607c0981da4SDimitry Andric }
2608c0981da4SDimitry Andric
2609c0981da4SDimitry Andric // For stack slots, calculate PHIs for the equivalent of the units, then
2610c0981da4SDimitry Andric // install for each index.
2611c0981da4SDimitry Andric for (SpillLocationNo Slot : StackSlots) {
2612c0981da4SDimitry Andric for (unsigned Idx : StackUnits) {
2613c0981da4SDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(Slot, Idx);
2614c0981da4SDimitry Andric LocIdx L = MTracker->getSpillMLoc(SpillID);
2615c0981da4SDimitry Andric CollectPHIsForLoc(L);
2616c0981da4SDimitry Andric InstallPHIsAtLoc(L);
2617c0981da4SDimitry Andric
2618c0981da4SDimitry Andric // Find anything that aliases this stack index, install PHIs for it too.
2619c0981da4SDimitry Andric unsigned Size, Offset;
2620c0981da4SDimitry Andric std::tie(Size, Offset) = MTracker->StackIdxesToPos[Idx];
2621c0981da4SDimitry Andric for (auto &Pair : MTracker->StackSlotIdxes) {
2622c0981da4SDimitry Andric unsigned ThisSize, ThisOffset;
2623c0981da4SDimitry Andric std::tie(ThisSize, ThisOffset) = Pair.first;
2624c0981da4SDimitry Andric if (ThisSize + ThisOffset <= Offset || Size + Offset <= ThisOffset)
2625c0981da4SDimitry Andric continue;
2626c0981da4SDimitry Andric
2627c0981da4SDimitry Andric unsigned ThisID = MTracker->getSpillIDWithIdx(Slot, Pair.second);
2628c0981da4SDimitry Andric LocIdx ThisL = MTracker->getSpillMLoc(ThisID);
2629c0981da4SDimitry Andric InstallPHIsAtLoc(ThisL);
2630c0981da4SDimitry Andric }
2631c0981da4SDimitry Andric }
2632c0981da4SDimitry Andric }
2633c0981da4SDimitry Andric
2634c0981da4SDimitry Andric // For reg units, place PHIs, and then place them for any aliasing registers.
2635c0981da4SDimitry Andric for (Register R : RegUnitsToPHIUp) {
2636c0981da4SDimitry Andric LocIdx L = MTracker->lookupOrTrackRegister(R);
2637c0981da4SDimitry Andric CollectPHIsForLoc(L);
2638c0981da4SDimitry Andric
2639c0981da4SDimitry Andric // Install those PHI values into the live-in value array.
2640c0981da4SDimitry Andric InstallPHIsAtLoc(L);
2641c0981da4SDimitry Andric
2642c0981da4SDimitry Andric // Now find aliases and install PHIs for those.
2643c0981da4SDimitry Andric for (MCRegAliasIterator RAI(R, TRI, true); RAI.isValid(); ++RAI) {
2644c0981da4SDimitry Andric // Super-registers that are "above" the largest register read/written by
2645c0981da4SDimitry Andric // the function will alias, but will not be tracked.
2646c0981da4SDimitry Andric if (!MTracker->isRegisterTracked(*RAI))
2647c0981da4SDimitry Andric continue;
2648c0981da4SDimitry Andric
2649c0981da4SDimitry Andric LocIdx AliasLoc = MTracker->lookupOrTrackRegister(*RAI);
2650c0981da4SDimitry Andric InstallPHIsAtLoc(AliasLoc);
2651c0981da4SDimitry Andric }
2652c0981da4SDimitry Andric }
2653c0981da4SDimitry Andric }
2654c0981da4SDimitry Andric
buildMLocValueMap(MachineFunction & MF,FuncValueTable & MInLocs,FuncValueTable & MOutLocs,SmallVectorImpl<MLocTransferMap> & MLocTransfer)2655c0981da4SDimitry Andric void InstrRefBasedLDV::buildMLocValueMap(
2656145449b1SDimitry Andric MachineFunction &MF, FuncValueTable &MInLocs, FuncValueTable &MOutLocs,
2657b60736ecSDimitry Andric SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
2658b60736ecSDimitry Andric std::priority_queue<unsigned int, std::vector<unsigned int>,
2659b60736ecSDimitry Andric std::greater<unsigned int>>
2660b60736ecSDimitry Andric Worklist, Pending;
2661b60736ecSDimitry Andric
2662b60736ecSDimitry Andric // We track what is on the current and pending worklist to avoid inserting
2663b60736ecSDimitry Andric // the same thing twice. We could avoid this with a custom priority queue,
2664b60736ecSDimitry Andric // but this is probably not worth it.
2665b60736ecSDimitry Andric SmallPtrSet<MachineBasicBlock *, 16> OnPending, OnWorklist;
2666b60736ecSDimitry Andric
2667c0981da4SDimitry Andric // Initialize worklist with every block to be visited. Also produce list of
2668c0981da4SDimitry Andric // all blocks.
2669c0981da4SDimitry Andric SmallPtrSet<MachineBasicBlock *, 32> AllBlocks;
2670b60736ecSDimitry Andric for (unsigned int I = 0; I < BBToOrder.size(); ++I) {
2671b60736ecSDimitry Andric Worklist.push(I);
2672b60736ecSDimitry Andric OnWorklist.insert(OrderToBB[I]);
2673c0981da4SDimitry Andric AllBlocks.insert(OrderToBB[I]);
2674b60736ecSDimitry Andric }
2675b60736ecSDimitry Andric
2676c0981da4SDimitry Andric // Initialize entry block to PHIs. These represent arguments.
2677c0981da4SDimitry Andric for (auto Location : MTracker->locations())
267899aabd70SDimitry Andric MInLocs.tableForEntryMBB()[Location.Idx.asU64()] =
267999aabd70SDimitry Andric ValueIDNum(0, 0, Location.Idx);
2680c0981da4SDimitry Andric
2681b60736ecSDimitry Andric MTracker->reset();
2682b60736ecSDimitry Andric
2683c0981da4SDimitry Andric // Start by placing PHIs, using the usual SSA constructor algorithm. Consider
2684c0981da4SDimitry Andric // any machine-location that isn't live-through a block to be def'd in that
2685c0981da4SDimitry Andric // block.
2686c0981da4SDimitry Andric placeMLocPHIs(MF, AllBlocks, MInLocs, MLocTransfer);
2687b60736ecSDimitry Andric
2688c0981da4SDimitry Andric // Propagate values to eliminate redundant PHIs. At the same time, this
2689c0981da4SDimitry Andric // produces the table of Block x Location => Value for the entry to each
2690c0981da4SDimitry Andric // block.
2691c0981da4SDimitry Andric // The kind of PHIs we can eliminate are, for example, where one path in a
2692c0981da4SDimitry Andric // conditional spills and restores a register, and the register still has
2693c0981da4SDimitry Andric // the same value once control flow joins, unbeknowns to the PHI placement
2694c0981da4SDimitry Andric // code. Propagating values allows us to identify such un-necessary PHIs and
2695c0981da4SDimitry Andric // remove them.
2696b60736ecSDimitry Andric SmallPtrSet<const MachineBasicBlock *, 16> Visited;
2697b60736ecSDimitry Andric while (!Worklist.empty() || !Pending.empty()) {
2698b60736ecSDimitry Andric // Vector for storing the evaluated block transfer function.
2699b60736ecSDimitry Andric SmallVector<std::pair<LocIdx, ValueIDNum>, 32> ToRemap;
2700b60736ecSDimitry Andric
2701b60736ecSDimitry Andric while (!Worklist.empty()) {
2702b60736ecSDimitry Andric MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
2703b60736ecSDimitry Andric CurBB = MBB->getNumber();
2704b60736ecSDimitry Andric Worklist.pop();
2705b60736ecSDimitry Andric
2706b60736ecSDimitry Andric // Join the values in all predecessor blocks.
2707c0981da4SDimitry Andric bool InLocsChanged;
270899aabd70SDimitry Andric InLocsChanged = mlocJoin(*MBB, Visited, MOutLocs, MInLocs[*MBB]);
2709b60736ecSDimitry Andric InLocsChanged |= Visited.insert(MBB).second;
2710b60736ecSDimitry Andric
2711b60736ecSDimitry Andric // Don't examine transfer function if we've visited this loc at least
2712b60736ecSDimitry Andric // once, and inlocs haven't changed.
2713b60736ecSDimitry Andric if (!InLocsChanged)
2714b60736ecSDimitry Andric continue;
2715b60736ecSDimitry Andric
2716b60736ecSDimitry Andric // Load the current set of live-ins into MLocTracker.
271799aabd70SDimitry Andric MTracker->loadFromArray(MInLocs[*MBB], CurBB);
2718b60736ecSDimitry Andric
2719b60736ecSDimitry Andric // Each element of the transfer function can be a new def, or a read of
2720b60736ecSDimitry Andric // a live-in value. Evaluate each element, and store to "ToRemap".
2721b60736ecSDimitry Andric ToRemap.clear();
2722b60736ecSDimitry Andric for (auto &P : MLocTransfer[CurBB]) {
2723b60736ecSDimitry Andric if (P.second.getBlock() == CurBB && P.second.isPHI()) {
2724b60736ecSDimitry Andric // This is a movement of whatever was live in. Read it.
2725c0981da4SDimitry Andric ValueIDNum NewID = MTracker->readMLoc(P.second.getLoc());
2726b60736ecSDimitry Andric ToRemap.push_back(std::make_pair(P.first, NewID));
2727b60736ecSDimitry Andric } else {
2728b60736ecSDimitry Andric // It's a def. Just set it.
2729b60736ecSDimitry Andric assert(P.second.getBlock() == CurBB);
2730b60736ecSDimitry Andric ToRemap.push_back(std::make_pair(P.first, P.second));
2731b60736ecSDimitry Andric }
2732b60736ecSDimitry Andric }
2733b60736ecSDimitry Andric
2734b60736ecSDimitry Andric // Commit the transfer function changes into mloc tracker, which
2735b60736ecSDimitry Andric // transforms the contents of the MLocTracker into the live-outs.
2736b60736ecSDimitry Andric for (auto &P : ToRemap)
2737b60736ecSDimitry Andric MTracker->setMLoc(P.first, P.second);
2738b60736ecSDimitry Andric
2739b60736ecSDimitry Andric // Now copy out-locs from mloc tracker into out-loc vector, checking
2740b60736ecSDimitry Andric // whether changes have occurred. These changes can have come from both
2741b60736ecSDimitry Andric // the transfer function, and mlocJoin.
2742b60736ecSDimitry Andric bool OLChanged = false;
2743b60736ecSDimitry Andric for (auto Location : MTracker->locations()) {
274499aabd70SDimitry Andric OLChanged |= MOutLocs[*MBB][Location.Idx.asU64()] != Location.Value;
274599aabd70SDimitry Andric MOutLocs[*MBB][Location.Idx.asU64()] = Location.Value;
2746b60736ecSDimitry Andric }
2747b60736ecSDimitry Andric
2748b60736ecSDimitry Andric MTracker->reset();
2749b60736ecSDimitry Andric
2750b60736ecSDimitry Andric // No need to examine successors again if out-locs didn't change.
2751b60736ecSDimitry Andric if (!OLChanged)
2752b60736ecSDimitry Andric continue;
2753b60736ecSDimitry Andric
2754b60736ecSDimitry Andric // All successors should be visited: put any back-edges on the pending
2755c0981da4SDimitry Andric // list for the next pass-through, and any other successors to be
2756c0981da4SDimitry Andric // visited this pass, if they're not going to be already.
27574b4fe385SDimitry Andric for (auto *s : MBB->successors()) {
2758b60736ecSDimitry Andric // Does branching to this successor represent a back-edge?
2759b60736ecSDimitry Andric if (BBToOrder[s] > BBToOrder[MBB]) {
2760b60736ecSDimitry Andric // No: visit it during this dataflow iteration.
2761b60736ecSDimitry Andric if (OnWorklist.insert(s).second)
2762b60736ecSDimitry Andric Worklist.push(BBToOrder[s]);
2763b60736ecSDimitry Andric } else {
2764b60736ecSDimitry Andric // Yes: visit it on the next iteration.
2765b60736ecSDimitry Andric if (OnPending.insert(s).second)
2766b60736ecSDimitry Andric Pending.push(BBToOrder[s]);
2767b60736ecSDimitry Andric }
2768b60736ecSDimitry Andric }
2769b60736ecSDimitry Andric }
2770b60736ecSDimitry Andric
2771b60736ecSDimitry Andric Worklist.swap(Pending);
2772b60736ecSDimitry Andric std::swap(OnPending, OnWorklist);
2773b60736ecSDimitry Andric OnPending.clear();
2774b60736ecSDimitry Andric // At this point, pending must be empty, since it was just the empty
2775b60736ecSDimitry Andric // worklist
2776b60736ecSDimitry Andric assert(Pending.empty() && "Pending should be empty");
2777b60736ecSDimitry Andric }
2778b60736ecSDimitry Andric
2779c0981da4SDimitry Andric // Once all the live-ins don't change on mlocJoin(), we've eliminated all
2780c0981da4SDimitry Andric // redundant PHIs.
2781b60736ecSDimitry Andric }
2782b60736ecSDimitry Andric
BlockPHIPlacement(const SmallPtrSetImpl<MachineBasicBlock * > & AllBlocks,const SmallPtrSetImpl<MachineBasicBlock * > & DefBlocks,SmallVectorImpl<MachineBasicBlock * > & PHIBlocks)2783c0981da4SDimitry Andric void InstrRefBasedLDV::BlockPHIPlacement(
2784c0981da4SDimitry Andric const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
2785c0981da4SDimitry Andric const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks,
2786c0981da4SDimitry Andric SmallVectorImpl<MachineBasicBlock *> &PHIBlocks) {
2787c0981da4SDimitry Andric // Apply IDF calculator to the designated set of location defs, storing
2788c0981da4SDimitry Andric // required PHIs into PHIBlocks. Uses the dominator tree stored in the
2789c0981da4SDimitry Andric // InstrRefBasedLDV object.
2790ecbca9f5SDimitry Andric IDFCalculatorBase<MachineBasicBlock, false> IDF(DomTree->getBase());
2791c0981da4SDimitry Andric
2792c0981da4SDimitry Andric IDF.setLiveInBlocks(AllBlocks);
2793c0981da4SDimitry Andric IDF.setDefiningBlocks(DefBlocks);
2794c0981da4SDimitry Andric IDF.calculate(PHIBlocks);
2795b60736ecSDimitry Andric }
2796b60736ecSDimitry Andric
pickVPHILoc(SmallVectorImpl<DbgOpID> & OutValues,const MachineBasicBlock & MBB,const LiveIdxT & LiveOuts,FuncValueTable & MOutLocs,const SmallVectorImpl<const MachineBasicBlock * > & BlockOrders)2797e3b55780SDimitry Andric bool InstrRefBasedLDV::pickVPHILoc(
2798e3b55780SDimitry Andric SmallVectorImpl<DbgOpID> &OutValues, const MachineBasicBlock &MBB,
2799145449b1SDimitry Andric const LiveIdxT &LiveOuts, FuncValueTable &MOutLocs,
2800c0981da4SDimitry Andric const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) {
2801c0981da4SDimitry Andric
2802c0981da4SDimitry Andric // No predecessors means no PHIs.
2803c0981da4SDimitry Andric if (BlockOrders.empty())
2804e3b55780SDimitry Andric return false;
2805b60736ecSDimitry Andric
2806e3b55780SDimitry Andric // All the location operands that do not already agree need to be joined,
2807e3b55780SDimitry Andric // track the indices of each such location operand here.
2808e3b55780SDimitry Andric SmallDenseSet<unsigned> LocOpsToJoin;
2809e3b55780SDimitry Andric
2810e3b55780SDimitry Andric auto FirstValueIt = LiveOuts.find(BlockOrders[0]);
2811e3b55780SDimitry Andric if (FirstValueIt == LiveOuts.end())
2812e3b55780SDimitry Andric return false;
2813e3b55780SDimitry Andric const DbgValue &FirstValue = *FirstValueIt->second;
2814e3b55780SDimitry Andric
2815e3b55780SDimitry Andric for (const auto p : BlockOrders) {
2816c0981da4SDimitry Andric auto OutValIt = LiveOuts.find(p);
2817c0981da4SDimitry Andric if (OutValIt == LiveOuts.end())
2818c0981da4SDimitry Andric // If we have a predecessor not in scope, we'll never find a PHI position.
2819e3b55780SDimitry Andric return false;
2820c0981da4SDimitry Andric const DbgValue &OutVal = *OutValIt->second;
2821b60736ecSDimitry Andric
2822e3b55780SDimitry Andric // No-values cannot have locations we can join on.
2823e3b55780SDimitry Andric if (OutVal.Kind == DbgValue::NoVal)
2824e3b55780SDimitry Andric return false;
2825b60736ecSDimitry Andric
2826e3b55780SDimitry Andric // For unjoined VPHIs where we don't know the location, we definitely
2827e3b55780SDimitry Andric // can't find a join loc unless the VPHI is a backedge.
2828e3b55780SDimitry Andric if (OutVal.isUnjoinedPHI() && OutVal.BlockNo != MBB.getNumber())
2829e3b55780SDimitry Andric return false;
2830e3b55780SDimitry Andric
2831e3b55780SDimitry Andric if (!FirstValue.Properties.isJoinable(OutVal.Properties))
2832e3b55780SDimitry Andric return false;
2833e3b55780SDimitry Andric
2834e3b55780SDimitry Andric for (unsigned Idx = 0; Idx < FirstValue.getLocationOpCount(); ++Idx) {
2835e3b55780SDimitry Andric // An unjoined PHI has no defined locations, and so a shared location must
2836e3b55780SDimitry Andric // be found for every operand.
2837e3b55780SDimitry Andric if (OutVal.isUnjoinedPHI()) {
2838e3b55780SDimitry Andric LocOpsToJoin.insert(Idx);
2839e3b55780SDimitry Andric continue;
2840e3b55780SDimitry Andric }
2841e3b55780SDimitry Andric DbgOpID FirstValOp = FirstValue.getDbgOpID(Idx);
2842e3b55780SDimitry Andric DbgOpID OutValOp = OutVal.getDbgOpID(Idx);
2843e3b55780SDimitry Andric if (FirstValOp != OutValOp) {
2844e3b55780SDimitry Andric // We can never join constant ops - the ops must either both be equal
2845e3b55780SDimitry Andric // constant ops or non-const ops.
2846e3b55780SDimitry Andric if (FirstValOp.isConst() || OutValOp.isConst())
2847e3b55780SDimitry Andric return false;
2848e3b55780SDimitry Andric else
2849e3b55780SDimitry Andric LocOpsToJoin.insert(Idx);
2850e3b55780SDimitry Andric }
2851e3b55780SDimitry Andric }
2852e3b55780SDimitry Andric }
2853e3b55780SDimitry Andric
2854e3b55780SDimitry Andric SmallVector<DbgOpID> NewDbgOps;
2855e3b55780SDimitry Andric
2856e3b55780SDimitry Andric for (unsigned Idx = 0; Idx < FirstValue.getLocationOpCount(); ++Idx) {
2857e3b55780SDimitry Andric // If this op doesn't need to be joined because the values agree, use that
2858e3b55780SDimitry Andric // already-agreed value.
2859e3b55780SDimitry Andric if (!LocOpsToJoin.contains(Idx)) {
2860e3b55780SDimitry Andric NewDbgOps.push_back(FirstValue.getDbgOpID(Idx));
2861e3b55780SDimitry Andric continue;
2862e3b55780SDimitry Andric }
2863e3b55780SDimitry Andric
2864e3b55780SDimitry Andric std::optional<ValueIDNum> JoinedOpLoc =
2865e3b55780SDimitry Andric pickOperandPHILoc(Idx, MBB, LiveOuts, MOutLocs, BlockOrders);
2866e3b55780SDimitry Andric
2867e3b55780SDimitry Andric if (!JoinedOpLoc)
2868e3b55780SDimitry Andric return false;
2869e3b55780SDimitry Andric
2870e3b55780SDimitry Andric NewDbgOps.push_back(DbgOpStore.insert(*JoinedOpLoc));
2871e3b55780SDimitry Andric }
2872e3b55780SDimitry Andric
2873e3b55780SDimitry Andric OutValues.append(NewDbgOps);
2874e3b55780SDimitry Andric return true;
2875e3b55780SDimitry Andric }
2876e3b55780SDimitry Andric
pickOperandPHILoc(unsigned DbgOpIdx,const MachineBasicBlock & MBB,const LiveIdxT & LiveOuts,FuncValueTable & MOutLocs,const SmallVectorImpl<const MachineBasicBlock * > & BlockOrders)2877e3b55780SDimitry Andric std::optional<ValueIDNum> InstrRefBasedLDV::pickOperandPHILoc(
2878e3b55780SDimitry Andric unsigned DbgOpIdx, const MachineBasicBlock &MBB, const LiveIdxT &LiveOuts,
2879e3b55780SDimitry Andric FuncValueTable &MOutLocs,
2880e3b55780SDimitry Andric const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) {
2881e3b55780SDimitry Andric
2882e3b55780SDimitry Andric // Collect a set of locations from predecessor where its live-out value can
2883e3b55780SDimitry Andric // be found.
2884e3b55780SDimitry Andric SmallVector<SmallVector<LocIdx, 4>, 8> Locs;
2885e3b55780SDimitry Andric unsigned NumLocs = MTracker->getNumLocs();
2886e3b55780SDimitry Andric
2887e3b55780SDimitry Andric for (const auto p : BlockOrders) {
2888e3b55780SDimitry Andric auto OutValIt = LiveOuts.find(p);
2889e3b55780SDimitry Andric assert(OutValIt != LiveOuts.end());
2890e3b55780SDimitry Andric const DbgValue &OutVal = *OutValIt->second;
2891e3b55780SDimitry Andric DbgOpID OutValOpID = OutVal.getDbgOpID(DbgOpIdx);
2892e3b55780SDimitry Andric DbgOp OutValOp = DbgOpStore.find(OutValOpID);
2893e3b55780SDimitry Andric assert(!OutValOp.IsConst);
2894c0981da4SDimitry Andric
2895c0981da4SDimitry Andric // Create new empty vector of locations.
2896c0981da4SDimitry Andric Locs.resize(Locs.size() + 1);
2897c0981da4SDimitry Andric
2898c0981da4SDimitry Andric // If the live-in value is a def, find the locations where that value is
2899c0981da4SDimitry Andric // present. Do the same for VPHIs where we know the VPHI value.
2900c0981da4SDimitry Andric if (OutVal.Kind == DbgValue::Def ||
2901c0981da4SDimitry Andric (OutVal.Kind == DbgValue::VPHI && OutVal.BlockNo != MBB.getNumber() &&
2902e3b55780SDimitry Andric !OutValOp.isUndef())) {
2903e3b55780SDimitry Andric ValueIDNum ValToLookFor = OutValOp.ID;
2904b60736ecSDimitry Andric // Search the live-outs of the predecessor for the specified value.
2905b60736ecSDimitry Andric for (unsigned int I = 0; I < NumLocs; ++I) {
290699aabd70SDimitry Andric if (MOutLocs[*p][I] == ValToLookFor)
2907b60736ecSDimitry Andric Locs.back().push_back(LocIdx(I));
2908b60736ecSDimitry Andric }
2909c0981da4SDimitry Andric } else {
2910c0981da4SDimitry Andric assert(OutVal.Kind == DbgValue::VPHI);
2911c0981da4SDimitry Andric // Otherwise: this is a VPHI on a backedge feeding back into itself, i.e.
2912c0981da4SDimitry Andric // a value that's live-through the whole loop. (It has to be a backedge,
2913c0981da4SDimitry Andric // because a block can't dominate itself). We can accept as a PHI location
2914c0981da4SDimitry Andric // any location where the other predecessors agree, _and_ the machine
2915c0981da4SDimitry Andric // locations feed back into themselves. Therefore, add all self-looping
2916c0981da4SDimitry Andric // machine-value PHI locations.
2917c0981da4SDimitry Andric for (unsigned int I = 0; I < NumLocs; ++I) {
2918c0981da4SDimitry Andric ValueIDNum MPHI(MBB.getNumber(), 0, LocIdx(I));
291999aabd70SDimitry Andric if (MOutLocs[*p][I] == MPHI)
2920c0981da4SDimitry Andric Locs.back().push_back(LocIdx(I));
2921c0981da4SDimitry Andric }
2922c0981da4SDimitry Andric }
2923b60736ecSDimitry Andric }
2924c0981da4SDimitry Andric // We should have found locations for all predecessors, or returned.
2925c0981da4SDimitry Andric assert(Locs.size() == BlockOrders.size());
2926b60736ecSDimitry Andric
2927b60736ecSDimitry Andric // Starting with the first set of locations, take the intersection with
2928b60736ecSDimitry Andric // subsequent sets.
2929c0981da4SDimitry Andric SmallVector<LocIdx, 4> CandidateLocs = Locs[0];
2930c0981da4SDimitry Andric for (unsigned int I = 1; I < Locs.size(); ++I) {
2931c0981da4SDimitry Andric auto &LocVec = Locs[I];
2932c0981da4SDimitry Andric SmallVector<LocIdx, 4> NewCandidates;
2933c0981da4SDimitry Andric std::set_intersection(CandidateLocs.begin(), CandidateLocs.end(),
2934c0981da4SDimitry Andric LocVec.begin(), LocVec.end(), std::inserter(NewCandidates, NewCandidates.begin()));
2935c0981da4SDimitry Andric CandidateLocs = NewCandidates;
2936b60736ecSDimitry Andric }
2937c0981da4SDimitry Andric if (CandidateLocs.empty())
2938e3b55780SDimitry Andric return std::nullopt;
2939b60736ecSDimitry Andric
2940b60736ecSDimitry Andric // We now have a set of LocIdxes that contain the right output value in
2941b60736ecSDimitry Andric // each of the predecessors. Pick the lowest; if there's a register loc,
2942b60736ecSDimitry Andric // that'll be it.
2943c0981da4SDimitry Andric LocIdx L = *CandidateLocs.begin();
2944b60736ecSDimitry Andric
2945b60736ecSDimitry Andric // Return a PHI-value-number for the found location.
2946b60736ecSDimitry Andric ValueIDNum PHIVal = {(unsigned)MBB.getNumber(), 0, L};
2947c0981da4SDimitry Andric return PHIVal;
2948b60736ecSDimitry Andric }
2949b60736ecSDimitry Andric
vlocJoin(MachineBasicBlock & MBB,LiveIdxT & VLOCOutLocs,SmallPtrSet<const MachineBasicBlock *,8> & BlocksToExplore,DbgValue & LiveIn)2950c0981da4SDimitry Andric bool InstrRefBasedLDV::vlocJoin(
2951c0981da4SDimitry Andric MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs,
2952b60736ecSDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
2953c0981da4SDimitry Andric DbgValue &LiveIn) {
2954b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
2955b60736ecSDimitry Andric bool Changed = false;
2956b60736ecSDimitry Andric
2957b60736ecSDimitry Andric // Order predecessors by RPOT order, for exploring them in that order.
2958344a3780SDimitry Andric SmallVector<MachineBasicBlock *, 8> BlockOrders(MBB.predecessors());
2959b60736ecSDimitry Andric
2960b60736ecSDimitry Andric auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
2961b60736ecSDimitry Andric return BBToOrder[A] < BBToOrder[B];
2962b60736ecSDimitry Andric };
2963b60736ecSDimitry Andric
2964b60736ecSDimitry Andric llvm::sort(BlockOrders, Cmp);
2965b60736ecSDimitry Andric
2966b60736ecSDimitry Andric unsigned CurBlockRPONum = BBToOrder[&MBB];
2967b60736ecSDimitry Andric
2968c0981da4SDimitry Andric // Collect all the incoming DbgValues for this variable, from predecessor
2969c0981da4SDimitry Andric // live-out values.
2970b60736ecSDimitry Andric SmallVector<InValueT, 8> Values;
2971b60736ecSDimitry Andric bool Bail = false;
2972c0981da4SDimitry Andric int BackEdgesStart = 0;
29734b4fe385SDimitry Andric for (auto *p : BlockOrders) {
2974b60736ecSDimitry Andric // If the predecessor isn't in scope / to be explored, we'll never be
2975b60736ecSDimitry Andric // able to join any locations.
2976b60736ecSDimitry Andric if (!BlocksToExplore.contains(p)) {
2977b60736ecSDimitry Andric Bail = true;
2978b60736ecSDimitry Andric break;
2979b60736ecSDimitry Andric }
2980b60736ecSDimitry Andric
2981c0981da4SDimitry Andric // All Live-outs will have been initialized.
2982c0981da4SDimitry Andric DbgValue &OutLoc = *VLOCOutLocs.find(p)->second;
2983b60736ecSDimitry Andric
2984b60736ecSDimitry Andric // Keep track of where back-edges begin in the Values vector. Relies on
2985b60736ecSDimitry Andric // BlockOrders being sorted by RPO.
2986b60736ecSDimitry Andric unsigned ThisBBRPONum = BBToOrder[p];
2987b60736ecSDimitry Andric if (ThisBBRPONum < CurBlockRPONum)
2988b60736ecSDimitry Andric ++BackEdgesStart;
2989b60736ecSDimitry Andric
2990c0981da4SDimitry Andric Values.push_back(std::make_pair(p, &OutLoc));
2991b60736ecSDimitry Andric }
2992b60736ecSDimitry Andric
2993b60736ecSDimitry Andric // If there were no values, or one of the predecessors couldn't have a
2994b60736ecSDimitry Andric // value, then give up immediately. It's not safe to produce a live-in
2995c0981da4SDimitry Andric // value. Leave as whatever it was before.
2996b60736ecSDimitry Andric if (Bail || Values.size() == 0)
2997c0981da4SDimitry Andric return false;
2998b60736ecSDimitry Andric
2999b60736ecSDimitry Andric // All (non-entry) blocks have at least one non-backedge predecessor.
3000b60736ecSDimitry Andric // Pick the variable value from the first of these, to compare against
3001b60736ecSDimitry Andric // all others.
3002b60736ecSDimitry Andric const DbgValue &FirstVal = *Values[0].second;
3003b60736ecSDimitry Andric
3004c0981da4SDimitry Andric // If the old live-in value is not a PHI then either a) no PHI is needed
3005c0981da4SDimitry Andric // here, or b) we eliminated the PHI that was here. If so, we can just
3006c0981da4SDimitry Andric // propagate in the first parent's incoming value.
3007c0981da4SDimitry Andric if (LiveIn.Kind != DbgValue::VPHI || LiveIn.BlockNo != MBB.getNumber()) {
3008c0981da4SDimitry Andric Changed = LiveIn != FirstVal;
3009c0981da4SDimitry Andric if (Changed)
3010c0981da4SDimitry Andric LiveIn = FirstVal;
3011c0981da4SDimitry Andric return Changed;
3012c0981da4SDimitry Andric }
3013c0981da4SDimitry Andric
3014c0981da4SDimitry Andric // Scan for variable values that can never be resolved: if they have
3015c0981da4SDimitry Andric // different DIExpressions, different indirectness, or are mixed constants /
3016b60736ecSDimitry Andric // non-constants.
3017e3b55780SDimitry Andric for (const auto &V : Values) {
3018e3b55780SDimitry Andric if (!V.second->Properties.isJoinable(FirstVal.Properties))
3019c0981da4SDimitry Andric return false;
3020c0981da4SDimitry Andric if (V.second->Kind == DbgValue::NoVal)
3021c0981da4SDimitry Andric return false;
3022e3b55780SDimitry Andric if (!V.second->hasJoinableLocOps(FirstVal))
3023c0981da4SDimitry Andric return false;
3024b60736ecSDimitry Andric }
3025b60736ecSDimitry Andric
3026c0981da4SDimitry Andric // Try to eliminate this PHI. Do the incoming values all agree?
3027b60736ecSDimitry Andric bool Disagree = false;
3028b60736ecSDimitry Andric for (auto &V : Values) {
3029b60736ecSDimitry Andric if (*V.second == FirstVal)
3030b60736ecSDimitry Andric continue; // No disagreement.
3031b60736ecSDimitry Andric
3032e3b55780SDimitry Andric // If both values are not equal but have equal non-empty IDs then they refer
3033e3b55780SDimitry Andric // to the same value from different sources (e.g. one is VPHI and the other
3034e3b55780SDimitry Andric // is Def), which does not cause disagreement.
3035e3b55780SDimitry Andric if (V.second->hasIdenticalValidLocOps(FirstVal))
3036e3b55780SDimitry Andric continue;
3037e3b55780SDimitry Andric
3038c0981da4SDimitry Andric // Eliminate if a backedge feeds a VPHI back into itself.
3039c0981da4SDimitry Andric if (V.second->Kind == DbgValue::VPHI &&
3040c0981da4SDimitry Andric V.second->BlockNo == MBB.getNumber() &&
3041c0981da4SDimitry Andric // Is this a backedge?
3042c0981da4SDimitry Andric std::distance(Values.begin(), &V) >= BackEdgesStart)
3043c0981da4SDimitry Andric continue;
3044c0981da4SDimitry Andric
3045b60736ecSDimitry Andric Disagree = true;
3046b60736ecSDimitry Andric }
3047b60736ecSDimitry Andric
3048c0981da4SDimitry Andric // No disagreement -> live-through value.
3049c0981da4SDimitry Andric if (!Disagree) {
3050c0981da4SDimitry Andric Changed = LiveIn != FirstVal;
3051b60736ecSDimitry Andric if (Changed)
3052c0981da4SDimitry Andric LiveIn = FirstVal;
3053c0981da4SDimitry Andric return Changed;
3054c0981da4SDimitry Andric } else {
3055c0981da4SDimitry Andric // Otherwise use a VPHI.
3056c0981da4SDimitry Andric DbgValue VPHI(MBB.getNumber(), FirstVal.Properties, DbgValue::VPHI);
3057c0981da4SDimitry Andric Changed = LiveIn != VPHI;
3058c0981da4SDimitry Andric if (Changed)
3059c0981da4SDimitry Andric LiveIn = VPHI;
3060c0981da4SDimitry Andric return Changed;
3061c0981da4SDimitry Andric }
3062b60736ecSDimitry Andric }
3063b60736ecSDimitry Andric
getBlocksForScope(const DILocation * DILoc,SmallPtrSetImpl<const MachineBasicBlock * > & BlocksToExplore,const SmallPtrSetImpl<MachineBasicBlock * > & AssignBlocks)3064ecbca9f5SDimitry Andric void InstrRefBasedLDV::getBlocksForScope(
3065ecbca9f5SDimitry Andric const DILocation *DILoc,
3066ecbca9f5SDimitry Andric SmallPtrSetImpl<const MachineBasicBlock *> &BlocksToExplore,
3067ecbca9f5SDimitry Andric const SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks) {
3068ecbca9f5SDimitry Andric // Get the set of "normal" in-lexical-scope blocks.
3069ecbca9f5SDimitry Andric LS.getMachineBasicBlocks(DILoc, BlocksToExplore);
3070ecbca9f5SDimitry Andric
3071ecbca9f5SDimitry Andric // VarLoc LiveDebugValues tracks variable locations that are defined in
3072ecbca9f5SDimitry Andric // blocks not in scope. This is something we could legitimately ignore, but
3073ecbca9f5SDimitry Andric // lets allow it for now for the sake of coverage.
3074ecbca9f5SDimitry Andric BlocksToExplore.insert(AssignBlocks.begin(), AssignBlocks.end());
3075ecbca9f5SDimitry Andric
3076ecbca9f5SDimitry Andric // Storage for artificial blocks we intend to add to BlocksToExplore.
3077ecbca9f5SDimitry Andric DenseSet<const MachineBasicBlock *> ToAdd;
3078ecbca9f5SDimitry Andric
3079ecbca9f5SDimitry Andric // To avoid needlessly dropping large volumes of variable locations, propagate
3080ecbca9f5SDimitry Andric // variables through aritifical blocks, i.e. those that don't have any
3081ecbca9f5SDimitry Andric // instructions in scope at all. To accurately replicate VarLoc
3082ecbca9f5SDimitry Andric // LiveDebugValues, this means exploring all artificial successors too.
3083ecbca9f5SDimitry Andric // Perform a depth-first-search to enumerate those blocks.
30844b4fe385SDimitry Andric for (const auto *MBB : BlocksToExplore) {
3085ecbca9f5SDimitry Andric // Depth-first-search state: each node is a block and which successor
3086ecbca9f5SDimitry Andric // we're currently exploring.
3087ecbca9f5SDimitry Andric SmallVector<std::pair<const MachineBasicBlock *,
3088ecbca9f5SDimitry Andric MachineBasicBlock::const_succ_iterator>,
3089ecbca9f5SDimitry Andric 8>
3090ecbca9f5SDimitry Andric DFS;
3091ecbca9f5SDimitry Andric
3092ecbca9f5SDimitry Andric // Find any artificial successors not already tracked.
3093ecbca9f5SDimitry Andric for (auto *succ : MBB->successors()) {
3094ecbca9f5SDimitry Andric if (BlocksToExplore.count(succ))
3095ecbca9f5SDimitry Andric continue;
3096ecbca9f5SDimitry Andric if (!ArtificialBlocks.count(succ))
3097ecbca9f5SDimitry Andric continue;
3098ecbca9f5SDimitry Andric ToAdd.insert(succ);
3099ecbca9f5SDimitry Andric DFS.push_back({succ, succ->succ_begin()});
3100ecbca9f5SDimitry Andric }
3101ecbca9f5SDimitry Andric
3102ecbca9f5SDimitry Andric // Search all those blocks, depth first.
3103ecbca9f5SDimitry Andric while (!DFS.empty()) {
3104ecbca9f5SDimitry Andric const MachineBasicBlock *CurBB = DFS.back().first;
3105ecbca9f5SDimitry Andric MachineBasicBlock::const_succ_iterator &CurSucc = DFS.back().second;
3106ecbca9f5SDimitry Andric // Walk back if we've explored this blocks successors to the end.
3107ecbca9f5SDimitry Andric if (CurSucc == CurBB->succ_end()) {
3108ecbca9f5SDimitry Andric DFS.pop_back();
3109ecbca9f5SDimitry Andric continue;
3110ecbca9f5SDimitry Andric }
3111ecbca9f5SDimitry Andric
3112ecbca9f5SDimitry Andric // If the current successor is artificial and unexplored, descend into
3113ecbca9f5SDimitry Andric // it.
3114ecbca9f5SDimitry Andric if (!ToAdd.count(*CurSucc) && ArtificialBlocks.count(*CurSucc)) {
3115ecbca9f5SDimitry Andric ToAdd.insert(*CurSucc);
3116ecbca9f5SDimitry Andric DFS.push_back({*CurSucc, (*CurSucc)->succ_begin()});
3117ecbca9f5SDimitry Andric continue;
3118ecbca9f5SDimitry Andric }
3119ecbca9f5SDimitry Andric
3120ecbca9f5SDimitry Andric ++CurSucc;
3121ecbca9f5SDimitry Andric }
3122ecbca9f5SDimitry Andric };
3123ecbca9f5SDimitry Andric
3124ecbca9f5SDimitry Andric BlocksToExplore.insert(ToAdd.begin(), ToAdd.end());
3125ecbca9f5SDimitry Andric }
3126ecbca9f5SDimitry Andric
buildVLocValueMap(const DILocation * DILoc,const SmallSet<DebugVariableID,4> & VarsWeCareAbout,SmallPtrSetImpl<MachineBasicBlock * > & AssignBlocks,LiveInsT & Output,FuncValueTable & MOutLocs,FuncValueTable & MInLocs,SmallVectorImpl<VLocTracker> & AllTheVLocs)3127ecbca9f5SDimitry Andric void InstrRefBasedLDV::buildVLocValueMap(
3128ac9a064cSDimitry Andric const DILocation *DILoc,
3129ac9a064cSDimitry Andric const SmallSet<DebugVariableID, 4> &VarsWeCareAbout,
3130b60736ecSDimitry Andric SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, LiveInsT &Output,
3131145449b1SDimitry Andric FuncValueTable &MOutLocs, FuncValueTable &MInLocs,
3132b60736ecSDimitry Andric SmallVectorImpl<VLocTracker> &AllTheVLocs) {
3133c0981da4SDimitry Andric // This method is much like buildMLocValueMap: but focuses on a single
3134b60736ecSDimitry Andric // LexicalScope at a time. Pick out a set of blocks and variables that are
3135b60736ecSDimitry Andric // to have their value assignments solved, then run our dataflow algorithm
3136b60736ecSDimitry Andric // until a fixedpoint is reached.
3137b60736ecSDimitry Andric std::priority_queue<unsigned int, std::vector<unsigned int>,
3138b60736ecSDimitry Andric std::greater<unsigned int>>
3139b60736ecSDimitry Andric Worklist, Pending;
3140b60736ecSDimitry Andric SmallPtrSet<MachineBasicBlock *, 16> OnWorklist, OnPending;
3141b60736ecSDimitry Andric
3142b60736ecSDimitry Andric // The set of blocks we'll be examining.
3143b60736ecSDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
3144b60736ecSDimitry Andric
3145b60736ecSDimitry Andric // The order in which to examine them (RPO).
3146ac9a064cSDimitry Andric SmallVector<MachineBasicBlock *, 16> BlockOrders;
3147ac9a064cSDimitry Andric SmallVector<unsigned, 32> BlockOrderNums;
3148b60736ecSDimitry Andric
3149ecbca9f5SDimitry Andric getBlocksForScope(DILoc, BlocksToExplore, AssignBlocks);
3150b60736ecSDimitry Andric
3151b60736ecSDimitry Andric // Single block scope: not interesting! No propagation at all. Note that
3152b60736ecSDimitry Andric // this could probably go above ArtificialBlocks without damage, but
3153b60736ecSDimitry Andric // that then produces output differences from original-live-debug-values,
3154b60736ecSDimitry Andric // which propagates from a single block into many artificial ones.
3155b60736ecSDimitry Andric if (BlocksToExplore.size() == 1)
3156b60736ecSDimitry Andric return;
3157b60736ecSDimitry Andric
3158c0981da4SDimitry Andric // Convert a const set to a non-const set. LexicalScopes
3159c0981da4SDimitry Andric // getMachineBasicBlocks returns const MBB pointers, IDF wants mutable ones.
3160c0981da4SDimitry Andric // (Neither of them mutate anything).
3161c0981da4SDimitry Andric SmallPtrSet<MachineBasicBlock *, 8> MutBlocksToExplore;
3162c0981da4SDimitry Andric for (const auto *MBB : BlocksToExplore)
3163c0981da4SDimitry Andric MutBlocksToExplore.insert(const_cast<MachineBasicBlock *>(MBB));
3164c0981da4SDimitry Andric
3165ac9a064cSDimitry Andric // Picks out relevants blocks RPO order and sort them. Sort their
3166ac9a064cSDimitry Andric // order-numbers and map back to MBB pointers later, to avoid repeated
3167ac9a064cSDimitry Andric // DenseMap queries during comparisons.
31684b4fe385SDimitry Andric for (const auto *MBB : BlocksToExplore)
3169ac9a064cSDimitry Andric BlockOrderNums.push_back(BBToOrder[MBB]);
3170b60736ecSDimitry Andric
3171ac9a064cSDimitry Andric llvm::sort(BlockOrderNums);
3172ac9a064cSDimitry Andric for (unsigned int I : BlockOrderNums)
3173ac9a064cSDimitry Andric BlockOrders.push_back(OrderToBB[I]);
3174ac9a064cSDimitry Andric BlockOrderNums.clear();
3175b60736ecSDimitry Andric unsigned NumBlocks = BlockOrders.size();
3176b60736ecSDimitry Andric
3177b60736ecSDimitry Andric // Allocate some vectors for storing the live ins and live outs. Large.
3178c0981da4SDimitry Andric SmallVector<DbgValue, 32> LiveIns, LiveOuts;
3179c0981da4SDimitry Andric LiveIns.reserve(NumBlocks);
3180c0981da4SDimitry Andric LiveOuts.reserve(NumBlocks);
3181c0981da4SDimitry Andric
3182c0981da4SDimitry Andric // Initialize all values to start as NoVals. This signifies "it's live
3183c0981da4SDimitry Andric // through, but we don't know what it is".
3184e3b55780SDimitry Andric DbgValueProperties EmptyProperties(EmptyExpr, false, false);
3185c0981da4SDimitry Andric for (unsigned int I = 0; I < NumBlocks; ++I) {
3186c0981da4SDimitry Andric DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal);
3187c0981da4SDimitry Andric LiveIns.push_back(EmptyDbgValue);
3188c0981da4SDimitry Andric LiveOuts.push_back(EmptyDbgValue);
3189c0981da4SDimitry Andric }
3190b60736ecSDimitry Andric
3191b60736ecSDimitry Andric // Produce by-MBB indexes of live-in/live-outs, to ease lookup within
3192b60736ecSDimitry Andric // vlocJoin.
3193b60736ecSDimitry Andric LiveIdxT LiveOutIdx, LiveInIdx;
3194b60736ecSDimitry Andric LiveOutIdx.reserve(NumBlocks);
3195b60736ecSDimitry Andric LiveInIdx.reserve(NumBlocks);
3196b60736ecSDimitry Andric for (unsigned I = 0; I < NumBlocks; ++I) {
3197b60736ecSDimitry Andric LiveOutIdx[BlockOrders[I]] = &LiveOuts[I];
3198b60736ecSDimitry Andric LiveInIdx[BlockOrders[I]] = &LiveIns[I];
3199b60736ecSDimitry Andric }
3200b60736ecSDimitry Andric
3201c0981da4SDimitry Andric // Loop over each variable and place PHIs for it, then propagate values
3202c0981da4SDimitry Andric // between blocks. This keeps the locality of working on one lexical scope at
3203c0981da4SDimitry Andric // at time, but avoids re-processing variable values because some other
3204c0981da4SDimitry Andric // variable has been assigned.
3205ac9a064cSDimitry Andric for (DebugVariableID VarID : VarsWeCareAbout) {
3206c0981da4SDimitry Andric // Re-initialize live-ins and live-outs, to clear the remains of previous
3207c0981da4SDimitry Andric // variables live-ins / live-outs.
3208c0981da4SDimitry Andric for (unsigned int I = 0; I < NumBlocks; ++I) {
3209c0981da4SDimitry Andric DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal);
3210c0981da4SDimitry Andric LiveIns[I] = EmptyDbgValue;
3211c0981da4SDimitry Andric LiveOuts[I] = EmptyDbgValue;
3212c0981da4SDimitry Andric }
3213c0981da4SDimitry Andric
3214c0981da4SDimitry Andric // Place PHIs for variable values, using the LLVM IDF calculator.
3215c0981da4SDimitry Andric // Collect the set of blocks where variables are def'd.
3216c0981da4SDimitry Andric SmallPtrSet<MachineBasicBlock *, 32> DefBlocks;
3217c0981da4SDimitry Andric for (const MachineBasicBlock *ExpMBB : BlocksToExplore) {
3218c0981da4SDimitry Andric auto &TransferFunc = AllTheVLocs[ExpMBB->getNumber()].Vars;
3219ac9a064cSDimitry Andric if (TransferFunc.contains(VarID))
3220c0981da4SDimitry Andric DefBlocks.insert(const_cast<MachineBasicBlock *>(ExpMBB));
3221c0981da4SDimitry Andric }
3222c0981da4SDimitry Andric
3223c0981da4SDimitry Andric SmallVector<MachineBasicBlock *, 32> PHIBlocks;
3224c0981da4SDimitry Andric
3225ecbca9f5SDimitry Andric // Request the set of PHIs we should insert for this variable. If there's
3226ecbca9f5SDimitry Andric // only one value definition, things are very simple.
3227ecbca9f5SDimitry Andric if (DefBlocks.size() == 1) {
3228ecbca9f5SDimitry Andric placePHIsForSingleVarDefinition(MutBlocksToExplore, *DefBlocks.begin(),
3229ac9a064cSDimitry Andric AllTheVLocs, VarID, Output);
3230ecbca9f5SDimitry Andric continue;
3231ecbca9f5SDimitry Andric }
3232ecbca9f5SDimitry Andric
3233ecbca9f5SDimitry Andric // Otherwise: we need to place PHIs through SSA and propagate values.
3234c0981da4SDimitry Andric BlockPHIPlacement(MutBlocksToExplore, DefBlocks, PHIBlocks);
3235c0981da4SDimitry Andric
3236c0981da4SDimitry Andric // Insert PHIs into the per-block live-in tables for this variable.
3237c0981da4SDimitry Andric for (MachineBasicBlock *PHIMBB : PHIBlocks) {
3238c0981da4SDimitry Andric unsigned BlockNo = PHIMBB->getNumber();
3239c0981da4SDimitry Andric DbgValue *LiveIn = LiveInIdx[PHIMBB];
3240c0981da4SDimitry Andric *LiveIn = DbgValue(BlockNo, EmptyProperties, DbgValue::VPHI);
3241c0981da4SDimitry Andric }
3242c0981da4SDimitry Andric
3243b60736ecSDimitry Andric for (auto *MBB : BlockOrders) {
3244b60736ecSDimitry Andric Worklist.push(BBToOrder[MBB]);
3245b60736ecSDimitry Andric OnWorklist.insert(MBB);
3246b60736ecSDimitry Andric }
3247b60736ecSDimitry Andric
3248c0981da4SDimitry Andric // Iterate over all the blocks we selected, propagating the variables value.
3249c0981da4SDimitry Andric // This loop does two things:
3250c0981da4SDimitry Andric // * Eliminates un-necessary VPHIs in vlocJoin,
3251c0981da4SDimitry Andric // * Evaluates the blocks transfer function (i.e. variable assignments) and
3252c0981da4SDimitry Andric // stores the result to the blocks live-outs.
3253c0981da4SDimitry Andric // Always evaluate the transfer function on the first iteration, and when
3254c0981da4SDimitry Andric // the live-ins change thereafter.
3255b60736ecSDimitry Andric bool FirstTrip = true;
3256b60736ecSDimitry Andric while (!Worklist.empty() || !Pending.empty()) {
3257b60736ecSDimitry Andric while (!Worklist.empty()) {
3258b60736ecSDimitry Andric auto *MBB = OrderToBB[Worklist.top()];
3259b60736ecSDimitry Andric CurBB = MBB->getNumber();
3260b60736ecSDimitry Andric Worklist.pop();
3261b60736ecSDimitry Andric
3262c0981da4SDimitry Andric auto LiveInsIt = LiveInIdx.find(MBB);
3263c0981da4SDimitry Andric assert(LiveInsIt != LiveInIdx.end());
3264c0981da4SDimitry Andric DbgValue *LiveIn = LiveInsIt->second;
3265b60736ecSDimitry Andric
3266b60736ecSDimitry Andric // Join values from predecessors. Updates LiveInIdx, and writes output
3267b60736ecSDimitry Andric // into JoinedInLocs.
3268c0981da4SDimitry Andric bool InLocsChanged =
3269f65dcba8SDimitry Andric vlocJoin(*MBB, LiveOutIdx, BlocksToExplore, *LiveIn);
3270b60736ecSDimitry Andric
3271c0981da4SDimitry Andric SmallVector<const MachineBasicBlock *, 8> Preds;
3272c0981da4SDimitry Andric for (const auto *Pred : MBB->predecessors())
3273c0981da4SDimitry Andric Preds.push_back(Pred);
3274b60736ecSDimitry Andric
3275c0981da4SDimitry Andric // If this block's live-in value is a VPHI, try to pick a machine-value
3276c0981da4SDimitry Andric // for it. This makes the machine-value available and propagated
3277c0981da4SDimitry Andric // through all blocks by the time value propagation finishes. We can't
3278c0981da4SDimitry Andric // do this any earlier as it needs to read the block live-outs.
3279c0981da4SDimitry Andric if (LiveIn->Kind == DbgValue::VPHI && LiveIn->BlockNo == (int)CurBB) {
3280c0981da4SDimitry Andric // There's a small possibility that on a preceeding path, a VPHI is
3281c0981da4SDimitry Andric // eliminated and transitions from VPHI-with-location to
3282c0981da4SDimitry Andric // live-through-value. As a result, the selected location of any VPHI
3283c0981da4SDimitry Andric // might change, so we need to re-compute it on each iteration.
3284e3b55780SDimitry Andric SmallVector<DbgOpID> JoinedOps;
3285b60736ecSDimitry Andric
3286e3b55780SDimitry Andric if (pickVPHILoc(JoinedOps, *MBB, LiveOutIdx, MOutLocs, Preds)) {
3287e3b55780SDimitry Andric bool NewLocPicked = !equal(LiveIn->getDbgOpIDs(), JoinedOps);
3288e3b55780SDimitry Andric InLocsChanged |= NewLocPicked;
3289e3b55780SDimitry Andric if (NewLocPicked)
3290e3b55780SDimitry Andric LiveIn->setDbgOpIDs(JoinedOps);
3291c0981da4SDimitry Andric }
3292c0981da4SDimitry Andric }
3293b60736ecSDimitry Andric
3294c0981da4SDimitry Andric if (!InLocsChanged && !FirstTrip)
3295b60736ecSDimitry Andric continue;
3296b60736ecSDimitry Andric
3297c0981da4SDimitry Andric DbgValue *LiveOut = LiveOutIdx[MBB];
3298c0981da4SDimitry Andric bool OLChanged = false;
3299c0981da4SDimitry Andric
3300b60736ecSDimitry Andric // Do transfer function.
3301b60736ecSDimitry Andric auto &VTracker = AllTheVLocs[MBB->getNumber()];
3302ac9a064cSDimitry Andric auto TransferIt = VTracker.Vars.find(VarID);
3303c0981da4SDimitry Andric if (TransferIt != VTracker.Vars.end()) {
3304b60736ecSDimitry Andric // Erase on empty transfer (DBG_VALUE $noreg).
3305c0981da4SDimitry Andric if (TransferIt->second.Kind == DbgValue::Undef) {
3306c0981da4SDimitry Andric DbgValue NewVal(MBB->getNumber(), EmptyProperties, DbgValue::NoVal);
3307c0981da4SDimitry Andric if (*LiveOut != NewVal) {
3308c0981da4SDimitry Andric *LiveOut = NewVal;
3309c0981da4SDimitry Andric OLChanged = true;
3310c0981da4SDimitry Andric }
3311b60736ecSDimitry Andric } else {
3312b60736ecSDimitry Andric // Insert new variable value; or overwrite.
3313c0981da4SDimitry Andric if (*LiveOut != TransferIt->second) {
3314c0981da4SDimitry Andric *LiveOut = TransferIt->second;
3315c0981da4SDimitry Andric OLChanged = true;
3316b60736ecSDimitry Andric }
3317b60736ecSDimitry Andric }
3318c0981da4SDimitry Andric } else {
3319c0981da4SDimitry Andric // Just copy live-ins to live-outs, for anything not transferred.
3320c0981da4SDimitry Andric if (*LiveOut != *LiveIn) {
3321c0981da4SDimitry Andric *LiveOut = *LiveIn;
3322c0981da4SDimitry Andric OLChanged = true;
3323c0981da4SDimitry Andric }
3324b60736ecSDimitry Andric }
3325b60736ecSDimitry Andric
3326c0981da4SDimitry Andric // If no live-out value changed, there's no need to explore further.
3327b60736ecSDimitry Andric if (!OLChanged)
3328b60736ecSDimitry Andric continue;
3329b60736ecSDimitry Andric
3330b60736ecSDimitry Andric // We should visit all successors. Ensure we'll visit any non-backedge
3331b60736ecSDimitry Andric // successors during this dataflow iteration; book backedge successors
3332b60736ecSDimitry Andric // to be visited next time around.
33334b4fe385SDimitry Andric for (auto *s : MBB->successors()) {
3334b60736ecSDimitry Andric // Ignore out of scope / not-to-be-explored successors.
33357fa27ce4SDimitry Andric if (!LiveInIdx.contains(s))
3336b60736ecSDimitry Andric continue;
3337b60736ecSDimitry Andric
3338b60736ecSDimitry Andric if (BBToOrder[s] > BBToOrder[MBB]) {
3339b60736ecSDimitry Andric if (OnWorklist.insert(s).second)
3340b60736ecSDimitry Andric Worklist.push(BBToOrder[s]);
3341b60736ecSDimitry Andric } else if (OnPending.insert(s).second && (FirstTrip || OLChanged)) {
3342b60736ecSDimitry Andric Pending.push(BBToOrder[s]);
3343b60736ecSDimitry Andric }
3344b60736ecSDimitry Andric }
3345b60736ecSDimitry Andric }
3346b60736ecSDimitry Andric Worklist.swap(Pending);
3347b60736ecSDimitry Andric std::swap(OnWorklist, OnPending);
3348b60736ecSDimitry Andric OnPending.clear();
3349b60736ecSDimitry Andric assert(Pending.empty());
3350b60736ecSDimitry Andric FirstTrip = false;
3351b60736ecSDimitry Andric }
3352b60736ecSDimitry Andric
3353c0981da4SDimitry Andric // Save live-ins to output vector. Ignore any that are still marked as being
3354c0981da4SDimitry Andric // VPHIs with no location -- those are variables that we know the value of,
3355c0981da4SDimitry Andric // but are not actually available in the register file.
3356b60736ecSDimitry Andric for (auto *MBB : BlockOrders) {
3357c0981da4SDimitry Andric DbgValue *BlockLiveIn = LiveInIdx[MBB];
3358c0981da4SDimitry Andric if (BlockLiveIn->Kind == DbgValue::NoVal)
3359b60736ecSDimitry Andric continue;
3360e3b55780SDimitry Andric if (BlockLiveIn->isUnjoinedPHI())
3361c0981da4SDimitry Andric continue;
3362c0981da4SDimitry Andric if (BlockLiveIn->Kind == DbgValue::VPHI)
3363c0981da4SDimitry Andric BlockLiveIn->Kind = DbgValue::Def;
3364ac9a064cSDimitry Andric [[maybe_unused]] auto &[Var, DILoc] = DVMap.lookupDVID(VarID);
3365f65dcba8SDimitry Andric assert(BlockLiveIn->Properties.DIExpr->getFragmentInfo() ==
3366ac9a064cSDimitry Andric Var.getFragment() &&
3367ac9a064cSDimitry Andric "Fragment info missing during value prop");
3368ac9a064cSDimitry Andric Output[MBB->getNumber()].push_back(std::make_pair(VarID, *BlockLiveIn));
3369b60736ecSDimitry Andric }
3370c0981da4SDimitry Andric } // Per-variable loop.
3371b60736ecSDimitry Andric
3372b60736ecSDimitry Andric BlockOrders.clear();
3373b60736ecSDimitry Andric BlocksToExplore.clear();
3374b60736ecSDimitry Andric }
3375b60736ecSDimitry Andric
placePHIsForSingleVarDefinition(const SmallPtrSetImpl<MachineBasicBlock * > & InScopeBlocks,MachineBasicBlock * AssignMBB,SmallVectorImpl<VLocTracker> & AllTheVLocs,DebugVariableID VarID,LiveInsT & Output)3376ecbca9f5SDimitry Andric void InstrRefBasedLDV::placePHIsForSingleVarDefinition(
3377ecbca9f5SDimitry Andric const SmallPtrSetImpl<MachineBasicBlock *> &InScopeBlocks,
3378ecbca9f5SDimitry Andric MachineBasicBlock *AssignMBB, SmallVectorImpl<VLocTracker> &AllTheVLocs,
3379ac9a064cSDimitry Andric DebugVariableID VarID, LiveInsT &Output) {
3380ecbca9f5SDimitry Andric // If there is a single definition of the variable, then working out it's
3381ecbca9f5SDimitry Andric // value everywhere is very simple: it's every block dominated by the
3382ecbca9f5SDimitry Andric // definition. At the dominance frontier, the usual algorithm would:
3383ecbca9f5SDimitry Andric // * Place PHIs,
3384ecbca9f5SDimitry Andric // * Propagate values into them,
3385ecbca9f5SDimitry Andric // * Find there's no incoming variable value from the other incoming branches
3386ecbca9f5SDimitry Andric // of the dominance frontier,
3387ecbca9f5SDimitry Andric // * Specify there's no variable value in blocks past the frontier.
3388ecbca9f5SDimitry Andric // This is a common case, hence it's worth special-casing it.
3389ecbca9f5SDimitry Andric
3390ecbca9f5SDimitry Andric // Pick out the variables value from the block transfer function.
3391ecbca9f5SDimitry Andric VLocTracker &VLocs = AllTheVLocs[AssignMBB->getNumber()];
3392ac9a064cSDimitry Andric auto ValueIt = VLocs.Vars.find(VarID);
3393ecbca9f5SDimitry Andric const DbgValue &Value = ValueIt->second;
3394ecbca9f5SDimitry Andric
3395145449b1SDimitry Andric // If it's an explicit assignment of "undef", that means there is no location
3396145449b1SDimitry Andric // anyway, anywhere.
3397145449b1SDimitry Andric if (Value.Kind == DbgValue::Undef)
3398145449b1SDimitry Andric return;
3399145449b1SDimitry Andric
3400ecbca9f5SDimitry Andric // Assign the variable value to entry to each dominated block that's in scope.
3401ecbca9f5SDimitry Andric // Skip the definition block -- it's assigned the variable value in the middle
3402ecbca9f5SDimitry Andric // of the block somewhere.
3403ecbca9f5SDimitry Andric for (auto *ScopeBlock : InScopeBlocks) {
3404ecbca9f5SDimitry Andric if (!DomTree->properlyDominates(AssignMBB, ScopeBlock))
3405ecbca9f5SDimitry Andric continue;
3406ecbca9f5SDimitry Andric
3407ac9a064cSDimitry Andric Output[ScopeBlock->getNumber()].push_back({VarID, Value});
3408ecbca9f5SDimitry Andric }
3409ecbca9f5SDimitry Andric
3410ecbca9f5SDimitry Andric // All blocks that aren't dominated have no live-in value, thus no variable
3411ecbca9f5SDimitry Andric // value will be given to them.
3412ecbca9f5SDimitry Andric }
3413ecbca9f5SDimitry Andric
3414b60736ecSDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump_mloc_transfer(const MLocTransferMap & mloc_transfer) const3415b60736ecSDimitry Andric void InstrRefBasedLDV::dump_mloc_transfer(
3416b60736ecSDimitry Andric const MLocTransferMap &mloc_transfer) const {
34174b4fe385SDimitry Andric for (const auto &P : mloc_transfer) {
3418b60736ecSDimitry Andric std::string foo = MTracker->LocIdxToName(P.first);
3419b60736ecSDimitry Andric std::string bar = MTracker->IDAsString(P.second);
3420b60736ecSDimitry Andric dbgs() << "Loc " << foo << " --> " << bar << "\n";
3421b60736ecSDimitry Andric }
3422b60736ecSDimitry Andric }
3423b60736ecSDimitry Andric #endif
3424b60736ecSDimitry Andric
initialSetup(MachineFunction & MF)3425b60736ecSDimitry Andric void InstrRefBasedLDV::initialSetup(MachineFunction &MF) {
3426b60736ecSDimitry Andric // Build some useful data structures.
3427c0981da4SDimitry Andric
3428c0981da4SDimitry Andric LLVMContext &Context = MF.getFunction().getContext();
3429c0981da4SDimitry Andric EmptyExpr = DIExpression::get(Context, {});
3430c0981da4SDimitry Andric
3431b60736ecSDimitry Andric auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
3432b60736ecSDimitry Andric if (const DebugLoc &DL = MI.getDebugLoc())
3433b60736ecSDimitry Andric return DL.getLine() != 0;
3434b60736ecSDimitry Andric return false;
3435b60736ecSDimitry Andric };
3436ac9a064cSDimitry Andric
3437ac9a064cSDimitry Andric // Collect a set of all the artificial blocks. Collect the size too, ilist
3438ac9a064cSDimitry Andric // size calls are O(n).
3439ac9a064cSDimitry Andric unsigned int Size = 0;
3440ac9a064cSDimitry Andric for (auto &MBB : MF) {
3441ac9a064cSDimitry Andric ++Size;
3442b60736ecSDimitry Andric if (none_of(MBB.instrs(), hasNonArtificialLocation))
3443b60736ecSDimitry Andric ArtificialBlocks.insert(&MBB);
3444ac9a064cSDimitry Andric }
3445b60736ecSDimitry Andric
3446b60736ecSDimitry Andric // Compute mappings of block <=> RPO order.
3447b60736ecSDimitry Andric ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
3448b60736ecSDimitry Andric unsigned int RPONumber = 0;
3449ac9a064cSDimitry Andric OrderToBB.reserve(Size);
3450ac9a064cSDimitry Andric BBToOrder.reserve(Size);
3451ac9a064cSDimitry Andric BBNumToRPO.reserve(Size);
3452e3b55780SDimitry Andric auto processMBB = [&](MachineBasicBlock *MBB) {
3453ac9a064cSDimitry Andric OrderToBB.push_back(MBB);
3454344a3780SDimitry Andric BBToOrder[MBB] = RPONumber;
3455344a3780SDimitry Andric BBNumToRPO[MBB->getNumber()] = RPONumber;
3456b60736ecSDimitry Andric ++RPONumber;
3457e3b55780SDimitry Andric };
3458e3b55780SDimitry Andric for (MachineBasicBlock *MBB : RPOT)
3459e3b55780SDimitry Andric processMBB(MBB);
3460e3b55780SDimitry Andric for (MachineBasicBlock &MBB : MF)
34617fa27ce4SDimitry Andric if (!BBToOrder.contains(&MBB))
3462e3b55780SDimitry Andric processMBB(&MBB);
3463344a3780SDimitry Andric
3464344a3780SDimitry Andric // Order value substitutions by their "source" operand pair, for quick lookup.
3465344a3780SDimitry Andric llvm::sort(MF.DebugValueSubstitutions);
3466344a3780SDimitry Andric
3467344a3780SDimitry Andric #ifdef EXPENSIVE_CHECKS
3468344a3780SDimitry Andric // As an expensive check, test whether there are any duplicate substitution
3469344a3780SDimitry Andric // sources in the collection.
3470344a3780SDimitry Andric if (MF.DebugValueSubstitutions.size() > 2) {
3471344a3780SDimitry Andric for (auto It = MF.DebugValueSubstitutions.begin();
3472344a3780SDimitry Andric It != std::prev(MF.DebugValueSubstitutions.end()); ++It) {
3473344a3780SDimitry Andric assert(It->Src != std::next(It)->Src && "Duplicate variable location "
3474344a3780SDimitry Andric "substitution seen");
3475344a3780SDimitry Andric }
3476344a3780SDimitry Andric }
3477344a3780SDimitry Andric #endif
3478b60736ecSDimitry Andric }
3479b60736ecSDimitry Andric
3480145449b1SDimitry Andric // Produce an "ejection map" for blocks, i.e., what's the highest-numbered
3481145449b1SDimitry Andric // lexical scope it's used in. When exploring in DFS order and we pass that
3482145449b1SDimitry Andric // scope, the block can be processed and any tracking information freed.
makeDepthFirstEjectionMap(SmallVectorImpl<unsigned> & EjectionMap,const ScopeToDILocT & ScopeToDILocation,ScopeToAssignBlocksT & ScopeToAssignBlocks)3483145449b1SDimitry Andric void InstrRefBasedLDV::makeDepthFirstEjectionMap(
3484145449b1SDimitry Andric SmallVectorImpl<unsigned> &EjectionMap,
3485145449b1SDimitry Andric const ScopeToDILocT &ScopeToDILocation,
3486145449b1SDimitry Andric ScopeToAssignBlocksT &ScopeToAssignBlocks) {
3487145449b1SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
3488145449b1SDimitry Andric SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack;
3489145449b1SDimitry Andric auto *TopScope = LS.getCurrentFunctionScope();
3490145449b1SDimitry Andric
3491145449b1SDimitry Andric // Unlike lexical scope explorers, we explore in reverse order, to find the
3492145449b1SDimitry Andric // "last" lexical scope used for each block early.
3493145449b1SDimitry Andric WorkStack.push_back({TopScope, TopScope->getChildren().size() - 1});
3494145449b1SDimitry Andric
3495145449b1SDimitry Andric while (!WorkStack.empty()) {
3496145449b1SDimitry Andric auto &ScopePosition = WorkStack.back();
3497145449b1SDimitry Andric LexicalScope *WS = ScopePosition.first;
3498145449b1SDimitry Andric ssize_t ChildNum = ScopePosition.second--;
3499145449b1SDimitry Andric
3500145449b1SDimitry Andric const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();
3501145449b1SDimitry Andric if (ChildNum >= 0) {
3502145449b1SDimitry Andric // If ChildNum is positive, there are remaining children to explore.
3503145449b1SDimitry Andric // Push the child and its children-count onto the stack.
3504145449b1SDimitry Andric auto &ChildScope = Children[ChildNum];
3505145449b1SDimitry Andric WorkStack.push_back(
3506145449b1SDimitry Andric std::make_pair(ChildScope, ChildScope->getChildren().size() - 1));
3507145449b1SDimitry Andric } else {
3508145449b1SDimitry Andric WorkStack.pop_back();
3509145449b1SDimitry Andric
3510145449b1SDimitry Andric // We've explored all children and any later blocks: examine all blocks
3511145449b1SDimitry Andric // in our scope. If they haven't yet had an ejection number set, then
3512145449b1SDimitry Andric // this scope will be the last to use that block.
3513145449b1SDimitry Andric auto DILocationIt = ScopeToDILocation.find(WS);
3514145449b1SDimitry Andric if (DILocationIt != ScopeToDILocation.end()) {
3515145449b1SDimitry Andric getBlocksForScope(DILocationIt->second, BlocksToExplore,
3516145449b1SDimitry Andric ScopeToAssignBlocks.find(WS)->second);
35174b4fe385SDimitry Andric for (const auto *MBB : BlocksToExplore) {
3518145449b1SDimitry Andric unsigned BBNum = MBB->getNumber();
3519145449b1SDimitry Andric if (EjectionMap[BBNum] == 0)
3520145449b1SDimitry Andric EjectionMap[BBNum] = WS->getDFSOut();
3521145449b1SDimitry Andric }
3522145449b1SDimitry Andric
3523145449b1SDimitry Andric BlocksToExplore.clear();
3524145449b1SDimitry Andric }
3525145449b1SDimitry Andric }
3526145449b1SDimitry Andric }
3527145449b1SDimitry Andric }
3528145449b1SDimitry Andric
depthFirstVLocAndEmit(unsigned MaxNumBlocks,const ScopeToDILocT & ScopeToDILocation,const ScopeToVarsT & ScopeToVars,ScopeToAssignBlocksT & ScopeToAssignBlocks,LiveInsT & Output,FuncValueTable & MOutLocs,FuncValueTable & MInLocs,SmallVectorImpl<VLocTracker> & AllTheVLocs,MachineFunction & MF,const TargetPassConfig & TPC)3529145449b1SDimitry Andric bool InstrRefBasedLDV::depthFirstVLocAndEmit(
3530145449b1SDimitry Andric unsigned MaxNumBlocks, const ScopeToDILocT &ScopeToDILocation,
3531145449b1SDimitry Andric const ScopeToVarsT &ScopeToVars, ScopeToAssignBlocksT &ScopeToAssignBlocks,
3532145449b1SDimitry Andric LiveInsT &Output, FuncValueTable &MOutLocs, FuncValueTable &MInLocs,
3533145449b1SDimitry Andric SmallVectorImpl<VLocTracker> &AllTheVLocs, MachineFunction &MF,
3534145449b1SDimitry Andric const TargetPassConfig &TPC) {
3535ac9a064cSDimitry Andric TTracker =
3536ac9a064cSDimitry Andric new TransferTracker(TII, MTracker, MF, DVMap, *TRI, CalleeSavedRegs, TPC);
3537145449b1SDimitry Andric unsigned NumLocs = MTracker->getNumLocs();
3538145449b1SDimitry Andric VTracker = nullptr;
3539145449b1SDimitry Andric
3540145449b1SDimitry Andric // No scopes? No variable locations.
3541145449b1SDimitry Andric if (!LS.getCurrentFunctionScope())
3542145449b1SDimitry Andric return false;
3543145449b1SDimitry Andric
3544145449b1SDimitry Andric // Build map from block number to the last scope that uses the block.
3545145449b1SDimitry Andric SmallVector<unsigned, 16> EjectionMap;
3546145449b1SDimitry Andric EjectionMap.resize(MaxNumBlocks, 0);
3547145449b1SDimitry Andric makeDepthFirstEjectionMap(EjectionMap, ScopeToDILocation,
3548145449b1SDimitry Andric ScopeToAssignBlocks);
3549145449b1SDimitry Andric
3550145449b1SDimitry Andric // Helper lambda for ejecting a block -- if nothing is going to use the block,
3551145449b1SDimitry Andric // we can translate the variable location information into DBG_VALUEs and then
3552145449b1SDimitry Andric // free all of InstrRefBasedLDV's data structures.
3553145449b1SDimitry Andric auto EjectBlock = [&](MachineBasicBlock &MBB) -> void {
3554145449b1SDimitry Andric unsigned BBNum = MBB.getNumber();
3555145449b1SDimitry Andric AllTheVLocs[BBNum].clear();
3556145449b1SDimitry Andric
3557145449b1SDimitry Andric // Prime the transfer-tracker, and then step through all the block
3558145449b1SDimitry Andric // instructions, installing transfers.
3559145449b1SDimitry Andric MTracker->reset();
356099aabd70SDimitry Andric MTracker->loadFromArray(MInLocs[MBB], BBNum);
356199aabd70SDimitry Andric TTracker->loadInlocs(MBB, MInLocs[MBB], DbgOpStore, Output[BBNum], NumLocs);
3562145449b1SDimitry Andric
3563145449b1SDimitry Andric CurBB = BBNum;
3564145449b1SDimitry Andric CurInst = 1;
3565145449b1SDimitry Andric for (auto &MI : MBB) {
3566312c0ed1SDimitry Andric process(MI, &MOutLocs, &MInLocs);
3567145449b1SDimitry Andric TTracker->checkInstForNewValues(CurInst, MI.getIterator());
3568145449b1SDimitry Andric ++CurInst;
3569145449b1SDimitry Andric }
3570145449b1SDimitry Andric
3571145449b1SDimitry Andric // Free machine-location tables for this block.
357299aabd70SDimitry Andric MInLocs.ejectTableForBlock(MBB);
357399aabd70SDimitry Andric MOutLocs.ejectTableForBlock(MBB);
3574145449b1SDimitry Andric // We don't need live-in variable values for this block either.
3575145449b1SDimitry Andric Output[BBNum].clear();
3576145449b1SDimitry Andric AllTheVLocs[BBNum].clear();
3577145449b1SDimitry Andric };
3578145449b1SDimitry Andric
3579145449b1SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
3580145449b1SDimitry Andric SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack;
3581145449b1SDimitry Andric WorkStack.push_back({LS.getCurrentFunctionScope(), 0});
3582145449b1SDimitry Andric unsigned HighestDFSIn = 0;
3583145449b1SDimitry Andric
3584145449b1SDimitry Andric // Proceed to explore in depth first order.
3585145449b1SDimitry Andric while (!WorkStack.empty()) {
3586145449b1SDimitry Andric auto &ScopePosition = WorkStack.back();
3587145449b1SDimitry Andric LexicalScope *WS = ScopePosition.first;
3588145449b1SDimitry Andric ssize_t ChildNum = ScopePosition.second++;
3589145449b1SDimitry Andric
3590145449b1SDimitry Andric // We obesrve scopes with children twice here, once descending in, once
3591145449b1SDimitry Andric // ascending out of the scope nest. Use HighestDFSIn as a ratchet to ensure
3592145449b1SDimitry Andric // we don't process a scope twice. Additionally, ignore scopes that don't
3593145449b1SDimitry Andric // have a DILocation -- by proxy, this means we never tracked any variable
3594145449b1SDimitry Andric // assignments in that scope.
3595145449b1SDimitry Andric auto DILocIt = ScopeToDILocation.find(WS);
3596145449b1SDimitry Andric if (HighestDFSIn <= WS->getDFSIn() && DILocIt != ScopeToDILocation.end()) {
3597145449b1SDimitry Andric const DILocation *DILoc = DILocIt->second;
3598145449b1SDimitry Andric auto &VarsWeCareAbout = ScopeToVars.find(WS)->second;
3599145449b1SDimitry Andric auto &BlocksInScope = ScopeToAssignBlocks.find(WS)->second;
3600145449b1SDimitry Andric
3601145449b1SDimitry Andric buildVLocValueMap(DILoc, VarsWeCareAbout, BlocksInScope, Output, MOutLocs,
3602145449b1SDimitry Andric MInLocs, AllTheVLocs);
3603145449b1SDimitry Andric }
3604145449b1SDimitry Andric
3605145449b1SDimitry Andric HighestDFSIn = std::max(HighestDFSIn, WS->getDFSIn());
3606145449b1SDimitry Andric
3607145449b1SDimitry Andric // Descend into any scope nests.
3608145449b1SDimitry Andric const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();
3609145449b1SDimitry Andric if (ChildNum < (ssize_t)Children.size()) {
3610145449b1SDimitry Andric // There are children to explore -- push onto stack and continue.
3611145449b1SDimitry Andric auto &ChildScope = Children[ChildNum];
3612145449b1SDimitry Andric WorkStack.push_back(std::make_pair(ChildScope, 0));
3613145449b1SDimitry Andric } else {
3614145449b1SDimitry Andric WorkStack.pop_back();
3615145449b1SDimitry Andric
3616145449b1SDimitry Andric // We've explored a leaf, or have explored all the children of a scope.
3617145449b1SDimitry Andric // Try to eject any blocks where this is the last scope it's relevant to.
3618145449b1SDimitry Andric auto DILocationIt = ScopeToDILocation.find(WS);
3619145449b1SDimitry Andric if (DILocationIt == ScopeToDILocation.end())
3620145449b1SDimitry Andric continue;
3621145449b1SDimitry Andric
3622145449b1SDimitry Andric getBlocksForScope(DILocationIt->second, BlocksToExplore,
3623145449b1SDimitry Andric ScopeToAssignBlocks.find(WS)->second);
36244b4fe385SDimitry Andric for (const auto *MBB : BlocksToExplore)
3625145449b1SDimitry Andric if (WS->getDFSOut() == EjectionMap[MBB->getNumber()])
3626145449b1SDimitry Andric EjectBlock(const_cast<MachineBasicBlock &>(*MBB));
3627145449b1SDimitry Andric
3628145449b1SDimitry Andric BlocksToExplore.clear();
3629145449b1SDimitry Andric }
3630145449b1SDimitry Andric }
3631145449b1SDimitry Andric
3632145449b1SDimitry Andric // Some artificial blocks may not have been ejected, meaning they're not
3633145449b1SDimitry Andric // connected to an actual legitimate scope. This can technically happen
3634145449b1SDimitry Andric // with things like the entry block. In theory, we shouldn't need to do
3635145449b1SDimitry Andric // anything for such out-of-scope blocks, but for the sake of being similar
3636145449b1SDimitry Andric // to VarLocBasedLDV, eject these too.
3637145449b1SDimitry Andric for (auto *MBB : ArtificialBlocks)
363899aabd70SDimitry Andric if (MInLocs.hasTableFor(*MBB))
3639145449b1SDimitry Andric EjectBlock(*MBB);
3640145449b1SDimitry Andric
3641ac9a064cSDimitry Andric return emitTransfers();
3642145449b1SDimitry Andric }
3643145449b1SDimitry Andric
emitTransfers()3644ac9a064cSDimitry Andric bool InstrRefBasedLDV::emitTransfers() {
3645ecbca9f5SDimitry Andric // Go through all the transfers recorded in the TransferTracker -- this is
3646ecbca9f5SDimitry Andric // both the live-ins to a block, and any movements of values that happen
3647ecbca9f5SDimitry Andric // in the middle.
3648ac9a064cSDimitry Andric for (auto &P : TTracker->Transfers) {
3649ecbca9f5SDimitry Andric // We have to insert DBG_VALUEs in a consistent order, otherwise they
3650ecbca9f5SDimitry Andric // appear in DWARF in different orders. Use the order that they appear
3651ecbca9f5SDimitry Andric // when walking through each block / each instruction, stored in
3652ac9a064cSDimitry Andric // DVMap.
3653ac9a064cSDimitry Andric llvm::sort(P.Insts, llvm::less_first());
3654ecbca9f5SDimitry Andric
3655ecbca9f5SDimitry Andric // Insert either before or after the designated point...
3656ecbca9f5SDimitry Andric if (P.MBB) {
3657ecbca9f5SDimitry Andric MachineBasicBlock &MBB = *P.MBB;
3658ac9a064cSDimitry Andric for (const auto &Pair : P.Insts)
3659ecbca9f5SDimitry Andric MBB.insert(P.Pos, Pair.second);
3660ecbca9f5SDimitry Andric } else {
3661ecbca9f5SDimitry Andric // Terminators, like tail calls, can clobber things. Don't try and place
3662ecbca9f5SDimitry Andric // transfers after them.
3663ecbca9f5SDimitry Andric if (P.Pos->isTerminator())
3664ecbca9f5SDimitry Andric continue;
3665ecbca9f5SDimitry Andric
3666ecbca9f5SDimitry Andric MachineBasicBlock &MBB = *P.Pos->getParent();
3667ac9a064cSDimitry Andric for (const auto &Pair : P.Insts)
3668ecbca9f5SDimitry Andric MBB.insertAfterBundle(P.Pos, Pair.second);
3669ecbca9f5SDimitry Andric }
3670ecbca9f5SDimitry Andric }
3671ecbca9f5SDimitry Andric
3672ecbca9f5SDimitry Andric return TTracker->Transfers.size() != 0;
3673ecbca9f5SDimitry Andric }
3674ecbca9f5SDimitry Andric
3675b60736ecSDimitry Andric /// Calculate the liveness information for the given machine function and
3676b60736ecSDimitry Andric /// extend ranges across basic blocks.
ExtendRanges(MachineFunction & MF,MachineDominatorTree * DomTree,TargetPassConfig * TPC,unsigned InputBBLimit,unsigned InputDbgValLimit)3677b60736ecSDimitry Andric bool InstrRefBasedLDV::ExtendRanges(MachineFunction &MF,
3678c0981da4SDimitry Andric MachineDominatorTree *DomTree,
3679c0981da4SDimitry Andric TargetPassConfig *TPC,
3680c0981da4SDimitry Andric unsigned InputBBLimit,
3681c0981da4SDimitry Andric unsigned InputDbgValLimit) {
3682b60736ecSDimitry Andric // No subprogram means this function contains no debuginfo.
3683b60736ecSDimitry Andric if (!MF.getFunction().getSubprogram())
3684b60736ecSDimitry Andric return false;
3685b60736ecSDimitry Andric
3686b60736ecSDimitry Andric LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
3687b60736ecSDimitry Andric this->TPC = TPC;
3688b60736ecSDimitry Andric
3689c0981da4SDimitry Andric this->DomTree = DomTree;
3690b60736ecSDimitry Andric TRI = MF.getSubtarget().getRegisterInfo();
3691c0981da4SDimitry Andric MRI = &MF.getRegInfo();
3692b60736ecSDimitry Andric TII = MF.getSubtarget().getInstrInfo();
3693b60736ecSDimitry Andric TFI = MF.getSubtarget().getFrameLowering();
3694b60736ecSDimitry Andric TFI->getCalleeSaves(MF, CalleeSavedRegs);
3695344a3780SDimitry Andric MFI = &MF.getFrameInfo();
3696b60736ecSDimitry Andric LS.initialize(MF);
3697b60736ecSDimitry Andric
3698f65dcba8SDimitry Andric const auto &STI = MF.getSubtarget();
3699f65dcba8SDimitry Andric AdjustsStackInCalls = MFI->adjustsStack() &&
3700f65dcba8SDimitry Andric STI.getFrameLowering()->stackProbeFunctionModifiesSP();
3701f65dcba8SDimitry Andric if (AdjustsStackInCalls)
3702f65dcba8SDimitry Andric StackProbeSymbolName = STI.getTargetLowering()->getStackProbeSymbolName(MF);
3703f65dcba8SDimitry Andric
3704b60736ecSDimitry Andric MTracker =
3705b60736ecSDimitry Andric new MLocTracker(MF, *TII, *TRI, *MF.getSubtarget().getTargetLowering());
3706b60736ecSDimitry Andric VTracker = nullptr;
3707b60736ecSDimitry Andric TTracker = nullptr;
3708b60736ecSDimitry Andric
3709b60736ecSDimitry Andric SmallVector<MLocTransferMap, 32> MLocTransfer;
3710b60736ecSDimitry Andric SmallVector<VLocTracker, 8> vlocs;
3711b60736ecSDimitry Andric LiveInsT SavedLiveIns;
3712b60736ecSDimitry Andric
3713b60736ecSDimitry Andric int MaxNumBlocks = -1;
3714b60736ecSDimitry Andric for (auto &MBB : MF)
3715b60736ecSDimitry Andric MaxNumBlocks = std::max(MBB.getNumber(), MaxNumBlocks);
3716b60736ecSDimitry Andric assert(MaxNumBlocks >= 0);
3717b60736ecSDimitry Andric ++MaxNumBlocks;
3718b60736ecSDimitry Andric
3719145449b1SDimitry Andric initialSetup(MF);
3720145449b1SDimitry Andric
3721b60736ecSDimitry Andric MLocTransfer.resize(MaxNumBlocks);
3722ac9a064cSDimitry Andric vlocs.resize(MaxNumBlocks, VLocTracker(DVMap, OverlapFragments, EmptyExpr));
3723b60736ecSDimitry Andric SavedLiveIns.resize(MaxNumBlocks);
3724b60736ecSDimitry Andric
3725b60736ecSDimitry Andric produceMLocTransferFunction(MF, MLocTransfer, MaxNumBlocks);
3726b60736ecSDimitry Andric
3727b60736ecSDimitry Andric // Allocate and initialize two array-of-arrays for the live-in and live-out
3728b60736ecSDimitry Andric // machine values. The outer dimension is the block number; while the inner
3729b60736ecSDimitry Andric // dimension is a LocIdx from MLocTracker.
3730b60736ecSDimitry Andric unsigned NumLocs = MTracker->getNumLocs();
373199aabd70SDimitry Andric FuncValueTable MOutLocs(MaxNumBlocks, NumLocs);
373299aabd70SDimitry Andric FuncValueTable MInLocs(MaxNumBlocks, NumLocs);
3733b60736ecSDimitry Andric
3734b60736ecSDimitry Andric // Solve the machine value dataflow problem using the MLocTransfer function,
3735b60736ecSDimitry Andric // storing the computed live-ins / live-outs into the array-of-arrays. We use
3736b60736ecSDimitry Andric // both live-ins and live-outs for decision making in the variable value
3737b60736ecSDimitry Andric // dataflow problem.
3738c0981da4SDimitry Andric buildMLocValueMap(MF, MInLocs, MOutLocs, MLocTransfer);
3739b60736ecSDimitry Andric
3740344a3780SDimitry Andric // Patch up debug phi numbers, turning unknown block-live-in values into
3741344a3780SDimitry Andric // either live-through machine values, or PHIs.
3742344a3780SDimitry Andric for (auto &DBG_PHI : DebugPHINumToValue) {
3743344a3780SDimitry Andric // Identify unresolved block-live-ins.
3744145449b1SDimitry Andric if (!DBG_PHI.ValueRead)
3745145449b1SDimitry Andric continue;
3746145449b1SDimitry Andric
3747145449b1SDimitry Andric ValueIDNum &Num = *DBG_PHI.ValueRead;
3748344a3780SDimitry Andric if (!Num.isPHI())
3749344a3780SDimitry Andric continue;
3750344a3780SDimitry Andric
3751344a3780SDimitry Andric unsigned BlockNo = Num.getBlock();
3752344a3780SDimitry Andric LocIdx LocNo = Num.getLoc();
37537fa27ce4SDimitry Andric ValueIDNum ResolvedValue = MInLocs[BlockNo][LocNo.asU64()];
37547fa27ce4SDimitry Andric // If there is no resolved value for this live-in then it is not directly
37557fa27ce4SDimitry Andric // reachable from the entry block -- model it as a PHI on entry to this
37567fa27ce4SDimitry Andric // block, which means we leave the ValueIDNum unchanged.
37577fa27ce4SDimitry Andric if (ResolvedValue != ValueIDNum::EmptyValue)
37587fa27ce4SDimitry Andric Num = ResolvedValue;
3759344a3780SDimitry Andric }
3760344a3780SDimitry Andric // Later, we'll be looking up ranges of instruction numbers.
3761344a3780SDimitry Andric llvm::sort(DebugPHINumToValue);
3762344a3780SDimitry Andric
3763b60736ecSDimitry Andric // Walk back through each block / instruction, collecting DBG_VALUE
3764b60736ecSDimitry Andric // instructions and recording what machine value their operands refer to.
3765ac9a064cSDimitry Andric for (MachineBasicBlock *MBB : OrderToBB) {
3766ac9a064cSDimitry Andric CurBB = MBB->getNumber();
3767b60736ecSDimitry Andric VTracker = &vlocs[CurBB];
3768ac9a064cSDimitry Andric VTracker->MBB = MBB;
3769ac9a064cSDimitry Andric MTracker->loadFromArray(MInLocs[*MBB], CurBB);
3770b60736ecSDimitry Andric CurInst = 1;
3771ac9a064cSDimitry Andric for (auto &MI : *MBB) {
3772312c0ed1SDimitry Andric process(MI, &MOutLocs, &MInLocs);
3773b60736ecSDimitry Andric ++CurInst;
3774b60736ecSDimitry Andric }
3775b60736ecSDimitry Andric MTracker->reset();
3776b60736ecSDimitry Andric }
3777b60736ecSDimitry Andric
3778b60736ecSDimitry Andric // Map from one LexicalScope to all the variables in that scope.
3779ecbca9f5SDimitry Andric ScopeToVarsT ScopeToVars;
3780b60736ecSDimitry Andric
3781ecbca9f5SDimitry Andric // Map from One lexical scope to all blocks where assignments happen for
3782ecbca9f5SDimitry Andric // that scope.
3783ecbca9f5SDimitry Andric ScopeToAssignBlocksT ScopeToAssignBlocks;
3784b60736ecSDimitry Andric
3785ecbca9f5SDimitry Andric // Store map of DILocations that describes scopes.
3786ecbca9f5SDimitry Andric ScopeToDILocT ScopeToDILocation;
3787b60736ecSDimitry Andric
3788b60736ecSDimitry Andric // To mirror old LiveDebugValues, enumerate variables in RPOT order. Otherwise
3789b60736ecSDimitry Andric // the order is unimportant, it just has to be stable.
3790c0981da4SDimitry Andric unsigned VarAssignCount = 0;
3791b60736ecSDimitry Andric for (unsigned int I = 0; I < OrderToBB.size(); ++I) {
3792b60736ecSDimitry Andric auto *MBB = OrderToBB[I];
3793b60736ecSDimitry Andric auto *VTracker = &vlocs[MBB->getNumber()];
3794b60736ecSDimitry Andric // Collect each variable with a DBG_VALUE in this block.
3795b60736ecSDimitry Andric for (auto &idx : VTracker->Vars) {
3796ac9a064cSDimitry Andric DebugVariableID VarID = idx.first;
3797ac9a064cSDimitry Andric const DILocation *ScopeLoc = VTracker->Scopes[VarID];
3798b60736ecSDimitry Andric assert(ScopeLoc != nullptr);
3799b60736ecSDimitry Andric auto *Scope = LS.findLexicalScope(ScopeLoc);
3800b60736ecSDimitry Andric
3801b60736ecSDimitry Andric // No insts in scope -> shouldn't have been recorded.
3802b60736ecSDimitry Andric assert(Scope != nullptr);
3803b60736ecSDimitry Andric
3804ac9a064cSDimitry Andric ScopeToVars[Scope].insert(VarID);
3805ecbca9f5SDimitry Andric ScopeToAssignBlocks[Scope].insert(VTracker->MBB);
3806b60736ecSDimitry Andric ScopeToDILocation[Scope] = ScopeLoc;
3807c0981da4SDimitry Andric ++VarAssignCount;
3808b60736ecSDimitry Andric }
3809b60736ecSDimitry Andric }
3810b60736ecSDimitry Andric
3811c0981da4SDimitry Andric bool Changed = false;
3812c0981da4SDimitry Andric
3813c0981da4SDimitry Andric // If we have an extremely large number of variable assignments and blocks,
3814c0981da4SDimitry Andric // bail out at this point. We've burnt some time doing analysis already,
3815c0981da4SDimitry Andric // however we should cut our losses.
3816c0981da4SDimitry Andric if ((unsigned)MaxNumBlocks > InputBBLimit &&
3817c0981da4SDimitry Andric VarAssignCount > InputDbgValLimit) {
3818c0981da4SDimitry Andric LLVM_DEBUG(dbgs() << "Disabling InstrRefBasedLDV: " << MF.getName()
3819c0981da4SDimitry Andric << " has " << MaxNumBlocks << " basic blocks and "
3820c0981da4SDimitry Andric << VarAssignCount
3821c0981da4SDimitry Andric << " variable assignments, exceeding limits.\n");
3822c0981da4SDimitry Andric } else {
3823145449b1SDimitry Andric // Optionally, solve the variable value problem and emit to blocks by using
3824145449b1SDimitry Andric // a lexical-scope-depth search. It should be functionally identical to
3825145449b1SDimitry Andric // the "else" block of this condition.
3826145449b1SDimitry Andric Changed = depthFirstVLocAndEmit(
3827145449b1SDimitry Andric MaxNumBlocks, ScopeToDILocation, ScopeToVars, ScopeToAssignBlocks,
3828ac9a064cSDimitry Andric SavedLiveIns, MOutLocs, MInLocs, vlocs, MF, *TPC);
3829b60736ecSDimitry Andric }
3830b60736ecSDimitry Andric
3831b60736ecSDimitry Andric delete MTracker;
3832b60736ecSDimitry Andric delete TTracker;
3833b60736ecSDimitry Andric MTracker = nullptr;
3834b60736ecSDimitry Andric VTracker = nullptr;
3835b60736ecSDimitry Andric TTracker = nullptr;
3836b60736ecSDimitry Andric
3837b60736ecSDimitry Andric ArtificialBlocks.clear();
3838b60736ecSDimitry Andric OrderToBB.clear();
3839b60736ecSDimitry Andric BBToOrder.clear();
3840b60736ecSDimitry Andric BBNumToRPO.clear();
3841b60736ecSDimitry Andric DebugInstrNumToInstr.clear();
3842344a3780SDimitry Andric DebugPHINumToValue.clear();
3843f65dcba8SDimitry Andric OverlapFragments.clear();
3844f65dcba8SDimitry Andric SeenFragments.clear();
3845145449b1SDimitry Andric SeenDbgPHIs.clear();
3846e3b55780SDimitry Andric DbgOpStore.clear();
3847ac9a064cSDimitry Andric DVMap.clear();
3848b60736ecSDimitry Andric
3849b60736ecSDimitry Andric return Changed;
3850b60736ecSDimitry Andric }
3851b60736ecSDimitry Andric
makeInstrRefBasedLiveDebugValues()3852b60736ecSDimitry Andric LDVImpl *llvm::makeInstrRefBasedLiveDebugValues() {
3853b60736ecSDimitry Andric return new InstrRefBasedLDV();
3854b60736ecSDimitry Andric }
3855344a3780SDimitry Andric
3856344a3780SDimitry Andric namespace {
3857344a3780SDimitry Andric class LDVSSABlock;
3858344a3780SDimitry Andric class LDVSSAUpdater;
3859344a3780SDimitry Andric
3860344a3780SDimitry Andric // Pick a type to identify incoming block values as we construct SSA. We
3861344a3780SDimitry Andric // can't use anything more robust than an integer unfortunately, as SSAUpdater
3862344a3780SDimitry Andric // expects to zero-initialize the type.
3863344a3780SDimitry Andric typedef uint64_t BlockValueNum;
3864344a3780SDimitry Andric
3865344a3780SDimitry Andric /// Represents an SSA PHI node for the SSA updater class. Contains the block
3866344a3780SDimitry Andric /// this PHI is in, the value number it would have, and the expected incoming
3867344a3780SDimitry Andric /// values from parent blocks.
3868344a3780SDimitry Andric class LDVSSAPhi {
3869344a3780SDimitry Andric public:
3870344a3780SDimitry Andric SmallVector<std::pair<LDVSSABlock *, BlockValueNum>, 4> IncomingValues;
3871344a3780SDimitry Andric LDVSSABlock *ParentBlock;
3872344a3780SDimitry Andric BlockValueNum PHIValNum;
LDVSSAPhi(BlockValueNum PHIValNum,LDVSSABlock * ParentBlock)3873344a3780SDimitry Andric LDVSSAPhi(BlockValueNum PHIValNum, LDVSSABlock *ParentBlock)
3874344a3780SDimitry Andric : ParentBlock(ParentBlock), PHIValNum(PHIValNum) {}
3875344a3780SDimitry Andric
getParent()3876344a3780SDimitry Andric LDVSSABlock *getParent() { return ParentBlock; }
3877344a3780SDimitry Andric };
3878344a3780SDimitry Andric
3879344a3780SDimitry Andric /// Thin wrapper around a block predecessor iterator. Only difference from a
3880344a3780SDimitry Andric /// normal block iterator is that it dereferences to an LDVSSABlock.
3881344a3780SDimitry Andric class LDVSSABlockIterator {
3882344a3780SDimitry Andric public:
3883344a3780SDimitry Andric MachineBasicBlock::pred_iterator PredIt;
3884344a3780SDimitry Andric LDVSSAUpdater &Updater;
3885344a3780SDimitry Andric
LDVSSABlockIterator(MachineBasicBlock::pred_iterator PredIt,LDVSSAUpdater & Updater)3886344a3780SDimitry Andric LDVSSABlockIterator(MachineBasicBlock::pred_iterator PredIt,
3887344a3780SDimitry Andric LDVSSAUpdater &Updater)
3888344a3780SDimitry Andric : PredIt(PredIt), Updater(Updater) {}
3889344a3780SDimitry Andric
operator !=(const LDVSSABlockIterator & OtherIt) const3890344a3780SDimitry Andric bool operator!=(const LDVSSABlockIterator &OtherIt) const {
3891344a3780SDimitry Andric return OtherIt.PredIt != PredIt;
3892344a3780SDimitry Andric }
3893344a3780SDimitry Andric
operator ++()3894344a3780SDimitry Andric LDVSSABlockIterator &operator++() {
3895344a3780SDimitry Andric ++PredIt;
3896344a3780SDimitry Andric return *this;
3897344a3780SDimitry Andric }
3898344a3780SDimitry Andric
3899344a3780SDimitry Andric LDVSSABlock *operator*();
3900344a3780SDimitry Andric };
3901344a3780SDimitry Andric
3902344a3780SDimitry Andric /// Thin wrapper around a block for SSA Updater interface. Necessary because
3903344a3780SDimitry Andric /// we need to track the PHI value(s) that we may have observed as necessary
3904344a3780SDimitry Andric /// in this block.
3905344a3780SDimitry Andric class LDVSSABlock {
3906344a3780SDimitry Andric public:
3907344a3780SDimitry Andric MachineBasicBlock &BB;
3908344a3780SDimitry Andric LDVSSAUpdater &Updater;
3909344a3780SDimitry Andric using PHIListT = SmallVector<LDVSSAPhi, 1>;
3910344a3780SDimitry Andric /// List of PHIs in this block. There should only ever be one.
3911344a3780SDimitry Andric PHIListT PHIList;
3912344a3780SDimitry Andric
LDVSSABlock(MachineBasicBlock & BB,LDVSSAUpdater & Updater)3913344a3780SDimitry Andric LDVSSABlock(MachineBasicBlock &BB, LDVSSAUpdater &Updater)
3914344a3780SDimitry Andric : BB(BB), Updater(Updater) {}
3915344a3780SDimitry Andric
succ_begin()3916344a3780SDimitry Andric LDVSSABlockIterator succ_begin() {
3917344a3780SDimitry Andric return LDVSSABlockIterator(BB.succ_begin(), Updater);
3918344a3780SDimitry Andric }
3919344a3780SDimitry Andric
succ_end()3920344a3780SDimitry Andric LDVSSABlockIterator succ_end() {
3921344a3780SDimitry Andric return LDVSSABlockIterator(BB.succ_end(), Updater);
3922344a3780SDimitry Andric }
3923344a3780SDimitry Andric
3924344a3780SDimitry Andric /// SSAUpdater has requested a PHI: create that within this block record.
newPHI(BlockValueNum Value)3925344a3780SDimitry Andric LDVSSAPhi *newPHI(BlockValueNum Value) {
3926344a3780SDimitry Andric PHIList.emplace_back(Value, this);
3927344a3780SDimitry Andric return &PHIList.back();
3928344a3780SDimitry Andric }
3929344a3780SDimitry Andric
3930344a3780SDimitry Andric /// SSAUpdater wishes to know what PHIs already exist in this block.
phis()3931344a3780SDimitry Andric PHIListT &phis() { return PHIList; }
3932344a3780SDimitry Andric };
3933344a3780SDimitry Andric
3934344a3780SDimitry Andric /// Utility class for the SSAUpdater interface: tracks blocks, PHIs and values
3935344a3780SDimitry Andric /// while SSAUpdater is exploring the CFG. It's passed as a handle / baton to
3936344a3780SDimitry Andric // SSAUpdaterTraits<LDVSSAUpdater>.
3937344a3780SDimitry Andric class LDVSSAUpdater {
3938344a3780SDimitry Andric public:
3939344a3780SDimitry Andric /// Map of value numbers to PHI records.
3940344a3780SDimitry Andric DenseMap<BlockValueNum, LDVSSAPhi *> PHIs;
3941344a3780SDimitry Andric /// Map of which blocks generate Undef values -- blocks that are not
3942344a3780SDimitry Andric /// dominated by any Def.
3943ac9a064cSDimitry Andric DenseMap<MachineBasicBlock *, BlockValueNum> PoisonMap;
3944344a3780SDimitry Andric /// Map of machine blocks to our own records of them.
3945344a3780SDimitry Andric DenseMap<MachineBasicBlock *, LDVSSABlock *> BlockMap;
3946344a3780SDimitry Andric /// Machine location where any PHI must occur.
3947344a3780SDimitry Andric LocIdx Loc;
3948344a3780SDimitry Andric /// Table of live-in machine value numbers for blocks / locations.
3949312c0ed1SDimitry Andric const FuncValueTable &MLiveIns;
3950344a3780SDimitry Andric
LDVSSAUpdater(LocIdx L,const FuncValueTable & MLiveIns)3951312c0ed1SDimitry Andric LDVSSAUpdater(LocIdx L, const FuncValueTable &MLiveIns)
3952145449b1SDimitry Andric : Loc(L), MLiveIns(MLiveIns) {}
3953344a3780SDimitry Andric
reset()3954344a3780SDimitry Andric void reset() {
3955344a3780SDimitry Andric for (auto &Block : BlockMap)
3956344a3780SDimitry Andric delete Block.second;
3957344a3780SDimitry Andric
3958344a3780SDimitry Andric PHIs.clear();
3959ac9a064cSDimitry Andric PoisonMap.clear();
3960344a3780SDimitry Andric BlockMap.clear();
3961344a3780SDimitry Andric }
3962344a3780SDimitry Andric
~LDVSSAUpdater()3963344a3780SDimitry Andric ~LDVSSAUpdater() { reset(); }
3964344a3780SDimitry Andric
3965344a3780SDimitry Andric /// For a given MBB, create a wrapper block for it. Stores it in the
3966344a3780SDimitry Andric /// LDVSSAUpdater block map.
getSSALDVBlock(MachineBasicBlock * BB)3967344a3780SDimitry Andric LDVSSABlock *getSSALDVBlock(MachineBasicBlock *BB) {
3968344a3780SDimitry Andric auto it = BlockMap.find(BB);
3969344a3780SDimitry Andric if (it == BlockMap.end()) {
3970344a3780SDimitry Andric BlockMap[BB] = new LDVSSABlock(*BB, *this);
3971344a3780SDimitry Andric it = BlockMap.find(BB);
3972344a3780SDimitry Andric }
3973344a3780SDimitry Andric return it->second;
3974344a3780SDimitry Andric }
3975344a3780SDimitry Andric
3976344a3780SDimitry Andric /// Find the live-in value number for the given block. Looks up the value at
3977344a3780SDimitry Andric /// the PHI location on entry.
getValue(LDVSSABlock * LDVBB)3978344a3780SDimitry Andric BlockValueNum getValue(LDVSSABlock *LDVBB) {
397999aabd70SDimitry Andric return MLiveIns[LDVBB->BB][Loc.asU64()].asU64();
3980344a3780SDimitry Andric }
3981344a3780SDimitry Andric };
3982344a3780SDimitry Andric
operator *()3983344a3780SDimitry Andric LDVSSABlock *LDVSSABlockIterator::operator*() {
3984344a3780SDimitry Andric return Updater.getSSALDVBlock(*PredIt);
3985344a3780SDimitry Andric }
3986344a3780SDimitry Andric
3987344a3780SDimitry Andric #ifndef NDEBUG
3988344a3780SDimitry Andric
operator <<(raw_ostream & out,const LDVSSAPhi & PHI)3989344a3780SDimitry Andric raw_ostream &operator<<(raw_ostream &out, const LDVSSAPhi &PHI) {
3990344a3780SDimitry Andric out << "SSALDVPHI " << PHI.PHIValNum;
3991344a3780SDimitry Andric return out;
3992344a3780SDimitry Andric }
3993344a3780SDimitry Andric
3994344a3780SDimitry Andric #endif
3995344a3780SDimitry Andric
3996344a3780SDimitry Andric } // namespace
3997344a3780SDimitry Andric
3998344a3780SDimitry Andric namespace llvm {
3999344a3780SDimitry Andric
4000344a3780SDimitry Andric /// Template specialization to give SSAUpdater access to CFG and value
4001344a3780SDimitry Andric /// information. SSAUpdater calls methods in these traits, passing in the
4002344a3780SDimitry Andric /// LDVSSAUpdater object, to learn about blocks and the values they define.
4003344a3780SDimitry Andric /// It also provides methods to create PHI nodes and track them.
4004344a3780SDimitry Andric template <> class SSAUpdaterTraits<LDVSSAUpdater> {
4005344a3780SDimitry Andric public:
4006344a3780SDimitry Andric using BlkT = LDVSSABlock;
4007344a3780SDimitry Andric using ValT = BlockValueNum;
4008344a3780SDimitry Andric using PhiT = LDVSSAPhi;
4009344a3780SDimitry Andric using BlkSucc_iterator = LDVSSABlockIterator;
4010344a3780SDimitry Andric
4011344a3780SDimitry Andric // Methods to access block successors -- dereferencing to our wrapper class.
BlkSucc_begin(BlkT * BB)4012344a3780SDimitry Andric static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); }
BlkSucc_end(BlkT * BB)4013344a3780SDimitry Andric static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); }
4014344a3780SDimitry Andric
4015344a3780SDimitry Andric /// Iterator for PHI operands.
4016344a3780SDimitry Andric class PHI_iterator {
4017344a3780SDimitry Andric private:
4018344a3780SDimitry Andric LDVSSAPhi *PHI;
4019344a3780SDimitry Andric unsigned Idx;
4020344a3780SDimitry Andric
4021344a3780SDimitry Andric public:
PHI_iterator(LDVSSAPhi * P)4022344a3780SDimitry Andric explicit PHI_iterator(LDVSSAPhi *P) // begin iterator
4023344a3780SDimitry Andric : PHI(P), Idx(0) {}
PHI_iterator(LDVSSAPhi * P,bool)4024344a3780SDimitry Andric PHI_iterator(LDVSSAPhi *P, bool) // end iterator
4025344a3780SDimitry Andric : PHI(P), Idx(PHI->IncomingValues.size()) {}
4026344a3780SDimitry Andric
operator ++()4027344a3780SDimitry Andric PHI_iterator &operator++() {
4028344a3780SDimitry Andric Idx++;
4029344a3780SDimitry Andric return *this;
4030344a3780SDimitry Andric }
operator ==(const PHI_iterator & X) const4031344a3780SDimitry Andric bool operator==(const PHI_iterator &X) const { return Idx == X.Idx; }
operator !=(const PHI_iterator & X) const4032344a3780SDimitry Andric bool operator!=(const PHI_iterator &X) const { return !operator==(X); }
4033344a3780SDimitry Andric
getIncomingValue()4034344a3780SDimitry Andric BlockValueNum getIncomingValue() { return PHI->IncomingValues[Idx].second; }
4035344a3780SDimitry Andric
getIncomingBlock()4036344a3780SDimitry Andric LDVSSABlock *getIncomingBlock() { return PHI->IncomingValues[Idx].first; }
4037344a3780SDimitry Andric };
4038344a3780SDimitry Andric
PHI_begin(PhiT * PHI)4039344a3780SDimitry Andric static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
4040344a3780SDimitry Andric
PHI_end(PhiT * PHI)4041344a3780SDimitry Andric static inline PHI_iterator PHI_end(PhiT *PHI) {
4042344a3780SDimitry Andric return PHI_iterator(PHI, true);
4043344a3780SDimitry Andric }
4044344a3780SDimitry Andric
4045344a3780SDimitry Andric /// FindPredecessorBlocks - Put the predecessors of BB into the Preds
4046344a3780SDimitry Andric /// vector.
FindPredecessorBlocks(LDVSSABlock * BB,SmallVectorImpl<LDVSSABlock * > * Preds)4047344a3780SDimitry Andric static void FindPredecessorBlocks(LDVSSABlock *BB,
4048344a3780SDimitry Andric SmallVectorImpl<LDVSSABlock *> *Preds) {
4049c0981da4SDimitry Andric for (MachineBasicBlock *Pred : BB->BB.predecessors())
4050c0981da4SDimitry Andric Preds->push_back(BB->Updater.getSSALDVBlock(Pred));
4051344a3780SDimitry Andric }
4052344a3780SDimitry Andric
4053ac9a064cSDimitry Andric /// GetPoisonVal - Normally creates an IMPLICIT_DEF instruction with a new
4054344a3780SDimitry Andric /// register. For LiveDebugValues, represents a block identified as not having
4055344a3780SDimitry Andric /// any DBG_PHI predecessors.
GetPoisonVal(LDVSSABlock * BB,LDVSSAUpdater * Updater)4056ac9a064cSDimitry Andric static BlockValueNum GetPoisonVal(LDVSSABlock *BB, LDVSSAUpdater *Updater) {
4057344a3780SDimitry Andric // Create a value number for this block -- it needs to be unique and in the
4058ac9a064cSDimitry Andric // "poison" collection, so that we know it's not real. Use a number
4059344a3780SDimitry Andric // representing a PHI into this block.
4060344a3780SDimitry Andric BlockValueNum Num = ValueIDNum(BB->BB.getNumber(), 0, Updater->Loc).asU64();
4061ac9a064cSDimitry Andric Updater->PoisonMap[&BB->BB] = Num;
4062344a3780SDimitry Andric return Num;
4063344a3780SDimitry Andric }
4064344a3780SDimitry Andric
4065344a3780SDimitry Andric /// CreateEmptyPHI - Create a (representation of a) PHI in the given block.
4066344a3780SDimitry Andric /// SSAUpdater will populate it with information about incoming values. The
4067344a3780SDimitry Andric /// value number of this PHI is whatever the machine value number problem
4068344a3780SDimitry Andric /// solution determined it to be. This includes non-phi values if SSAUpdater
4069344a3780SDimitry Andric /// tries to create a PHI where the incoming values are identical.
CreateEmptyPHI(LDVSSABlock * BB,unsigned NumPreds,LDVSSAUpdater * Updater)4070344a3780SDimitry Andric static BlockValueNum CreateEmptyPHI(LDVSSABlock *BB, unsigned NumPreds,
4071344a3780SDimitry Andric LDVSSAUpdater *Updater) {
4072344a3780SDimitry Andric BlockValueNum PHIValNum = Updater->getValue(BB);
4073344a3780SDimitry Andric LDVSSAPhi *PHI = BB->newPHI(PHIValNum);
4074344a3780SDimitry Andric Updater->PHIs[PHIValNum] = PHI;
4075344a3780SDimitry Andric return PHIValNum;
4076344a3780SDimitry Andric }
4077344a3780SDimitry Andric
4078344a3780SDimitry Andric /// AddPHIOperand - Add the specified value as an operand of the PHI for
4079344a3780SDimitry Andric /// the specified predecessor block.
AddPHIOperand(LDVSSAPhi * PHI,BlockValueNum Val,LDVSSABlock * Pred)4080344a3780SDimitry Andric static void AddPHIOperand(LDVSSAPhi *PHI, BlockValueNum Val, LDVSSABlock *Pred) {
4081344a3780SDimitry Andric PHI->IncomingValues.push_back(std::make_pair(Pred, Val));
4082344a3780SDimitry Andric }
4083344a3780SDimitry Andric
4084344a3780SDimitry Andric /// ValueIsPHI - Check if the instruction that defines the specified value
4085344a3780SDimitry Andric /// is a PHI instruction.
ValueIsPHI(BlockValueNum Val,LDVSSAUpdater * Updater)4086344a3780SDimitry Andric static LDVSSAPhi *ValueIsPHI(BlockValueNum Val, LDVSSAUpdater *Updater) {
40877fa27ce4SDimitry Andric return Updater->PHIs.lookup(Val);
4088344a3780SDimitry Andric }
4089344a3780SDimitry Andric
4090344a3780SDimitry Andric /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
4091344a3780SDimitry Andric /// operands, i.e., it was just added.
ValueIsNewPHI(BlockValueNum Val,LDVSSAUpdater * Updater)4092344a3780SDimitry Andric static LDVSSAPhi *ValueIsNewPHI(BlockValueNum Val, LDVSSAUpdater *Updater) {
4093344a3780SDimitry Andric LDVSSAPhi *PHI = ValueIsPHI(Val, Updater);
4094344a3780SDimitry Andric if (PHI && PHI->IncomingValues.size() == 0)
4095344a3780SDimitry Andric return PHI;
4096344a3780SDimitry Andric return nullptr;
4097344a3780SDimitry Andric }
4098344a3780SDimitry Andric
4099344a3780SDimitry Andric /// GetPHIValue - For the specified PHI instruction, return the value
4100344a3780SDimitry Andric /// that it defines.
GetPHIValue(LDVSSAPhi * PHI)4101344a3780SDimitry Andric static BlockValueNum GetPHIValue(LDVSSAPhi *PHI) { return PHI->PHIValNum; }
4102344a3780SDimitry Andric };
4103344a3780SDimitry Andric
4104344a3780SDimitry Andric } // end namespace llvm
4105344a3780SDimitry Andric
resolveDbgPHIs(MachineFunction & MF,const FuncValueTable & MLiveOuts,const FuncValueTable & MLiveIns,MachineInstr & Here,uint64_t InstrNum)4106e3b55780SDimitry Andric std::optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIs(
4107312c0ed1SDimitry Andric MachineFunction &MF, const FuncValueTable &MLiveOuts,
4108312c0ed1SDimitry Andric const FuncValueTable &MLiveIns, MachineInstr &Here, uint64_t InstrNum) {
4109145449b1SDimitry Andric // This function will be called twice per DBG_INSTR_REF, and might end up
4110145449b1SDimitry Andric // computing lots of SSA information: memoize it.
4111e3b55780SDimitry Andric auto SeenDbgPHIIt = SeenDbgPHIs.find(std::make_pair(&Here, InstrNum));
4112145449b1SDimitry Andric if (SeenDbgPHIIt != SeenDbgPHIs.end())
4113145449b1SDimitry Andric return SeenDbgPHIIt->second;
4114145449b1SDimitry Andric
4115e3b55780SDimitry Andric std::optional<ValueIDNum> Result =
4116145449b1SDimitry Andric resolveDbgPHIsImpl(MF, MLiveOuts, MLiveIns, Here, InstrNum);
4117e3b55780SDimitry Andric SeenDbgPHIs.insert({std::make_pair(&Here, InstrNum), Result});
4118145449b1SDimitry Andric return Result;
4119145449b1SDimitry Andric }
4120145449b1SDimitry Andric
resolveDbgPHIsImpl(MachineFunction & MF,const FuncValueTable & MLiveOuts,const FuncValueTable & MLiveIns,MachineInstr & Here,uint64_t InstrNum)4121e3b55780SDimitry Andric std::optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIsImpl(
4122312c0ed1SDimitry Andric MachineFunction &MF, const FuncValueTable &MLiveOuts,
4123312c0ed1SDimitry Andric const FuncValueTable &MLiveIns, MachineInstr &Here, uint64_t InstrNum) {
4124344a3780SDimitry Andric // Pick out records of DBG_PHI instructions that have been observed. If there
4125344a3780SDimitry Andric // are none, then we cannot compute a value number.
4126344a3780SDimitry Andric auto RangePair = std::equal_range(DebugPHINumToValue.begin(),
4127344a3780SDimitry Andric DebugPHINumToValue.end(), InstrNum);
4128344a3780SDimitry Andric auto LowerIt = RangePair.first;
4129344a3780SDimitry Andric auto UpperIt = RangePair.second;
4130344a3780SDimitry Andric
4131344a3780SDimitry Andric // No DBG_PHI means there can be no location.
4132344a3780SDimitry Andric if (LowerIt == UpperIt)
4133e3b55780SDimitry Andric return std::nullopt;
4134344a3780SDimitry Andric
4135145449b1SDimitry Andric // If any DBG_PHIs referred to a location we didn't understand, don't try to
4136145449b1SDimitry Andric // compute a value. There might be scenarios where we could recover a value
4137145449b1SDimitry Andric // for some range of DBG_INSTR_REFs, but at this point we can have high
4138145449b1SDimitry Andric // confidence that we've seen a bug.
4139145449b1SDimitry Andric auto DBGPHIRange = make_range(LowerIt, UpperIt);
4140145449b1SDimitry Andric for (const DebugPHIRecord &DBG_PHI : DBGPHIRange)
4141145449b1SDimitry Andric if (!DBG_PHI.ValueRead)
4142e3b55780SDimitry Andric return std::nullopt;
4143145449b1SDimitry Andric
4144344a3780SDimitry Andric // If there's only one DBG_PHI, then that is our value number.
4145344a3780SDimitry Andric if (std::distance(LowerIt, UpperIt) == 1)
4146145449b1SDimitry Andric return *LowerIt->ValueRead;
4147344a3780SDimitry Andric
4148344a3780SDimitry Andric // Pick out the location (physreg, slot) where any PHIs must occur. It's
4149344a3780SDimitry Andric // technically possible for us to merge values in different registers in each
4150344a3780SDimitry Andric // block, but highly unlikely that LLVM will generate such code after register
4151344a3780SDimitry Andric // allocation.
4152145449b1SDimitry Andric LocIdx Loc = *LowerIt->ReadLoc;
4153344a3780SDimitry Andric
4154344a3780SDimitry Andric // We have several DBG_PHIs, and a use position (the Here inst). All each
4155344a3780SDimitry Andric // DBG_PHI does is identify a value at a program position. We can treat each
4156344a3780SDimitry Andric // DBG_PHI like it's a Def of a value, and the use position is a Use of a
4157344a3780SDimitry Andric // value, just like SSA. We use the bulk-standard LLVM SSA updater class to
4158344a3780SDimitry Andric // determine which Def is used at the Use, and any PHIs that happen along
4159344a3780SDimitry Andric // the way.
4160344a3780SDimitry Andric // Adapted LLVM SSA Updater:
4161344a3780SDimitry Andric LDVSSAUpdater Updater(Loc, MLiveIns);
4162344a3780SDimitry Andric // Map of which Def or PHI is the current value in each block.
4163344a3780SDimitry Andric DenseMap<LDVSSABlock *, BlockValueNum> AvailableValues;
4164344a3780SDimitry Andric // Set of PHIs that we have created along the way.
4165344a3780SDimitry Andric SmallVector<LDVSSAPhi *, 8> CreatedPHIs;
4166344a3780SDimitry Andric
4167344a3780SDimitry Andric // Each existing DBG_PHI is a Def'd value under this model. Record these Defs
4168344a3780SDimitry Andric // for the SSAUpdater.
4169344a3780SDimitry Andric for (const auto &DBG_PHI : DBGPHIRange) {
4170344a3780SDimitry Andric LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB);
4171145449b1SDimitry Andric const ValueIDNum &Num = *DBG_PHI.ValueRead;
4172344a3780SDimitry Andric AvailableValues.insert(std::make_pair(Block, Num.asU64()));
4173344a3780SDimitry Andric }
4174344a3780SDimitry Andric
4175344a3780SDimitry Andric LDVSSABlock *HereBlock = Updater.getSSALDVBlock(Here.getParent());
4176344a3780SDimitry Andric const auto &AvailIt = AvailableValues.find(HereBlock);
4177344a3780SDimitry Andric if (AvailIt != AvailableValues.end()) {
4178344a3780SDimitry Andric // Actually, we already know what the value is -- the Use is in the same
4179344a3780SDimitry Andric // block as the Def.
4180344a3780SDimitry Andric return ValueIDNum::fromU64(AvailIt->second);
4181344a3780SDimitry Andric }
4182344a3780SDimitry Andric
4183344a3780SDimitry Andric // Otherwise, we must use the SSA Updater. It will identify the value number
4184344a3780SDimitry Andric // that we are to use, and the PHIs that must happen along the way.
4185344a3780SDimitry Andric SSAUpdaterImpl<LDVSSAUpdater> Impl(&Updater, &AvailableValues, &CreatedPHIs);
4186344a3780SDimitry Andric BlockValueNum ResultInt = Impl.GetValue(Updater.getSSALDVBlock(Here.getParent()));
4187344a3780SDimitry Andric ValueIDNum Result = ValueIDNum::fromU64(ResultInt);
4188344a3780SDimitry Andric
4189344a3780SDimitry Andric // We have the number for a PHI, or possibly live-through value, to be used
4190344a3780SDimitry Andric // at this Use. There are a number of things we have to check about it though:
4191344a3780SDimitry Andric // * Does any PHI use an 'Undef' (like an IMPLICIT_DEF) value? If so, this
4192344a3780SDimitry Andric // Use was not completely dominated by DBG_PHIs and we should abort.
4193344a3780SDimitry Andric // * Are the Defs or PHIs clobbered in a block? SSAUpdater isn't aware that
4194344a3780SDimitry Andric // we've left SSA form. Validate that the inputs to each PHI are the
4195344a3780SDimitry Andric // expected values.
4196344a3780SDimitry Andric // * Is a PHI we've created actually a merging of values, or are all the
4197344a3780SDimitry Andric // predecessor values the same, leading to a non-PHI machine value number?
4198344a3780SDimitry Andric // (SSAUpdater doesn't know that either). Remap validated PHIs into the
4199344a3780SDimitry Andric // the ValidatedValues collection below to sort this out.
4200344a3780SDimitry Andric DenseMap<LDVSSABlock *, ValueIDNum> ValidatedValues;
4201344a3780SDimitry Andric
4202344a3780SDimitry Andric // Define all the input DBG_PHI values in ValidatedValues.
4203344a3780SDimitry Andric for (const auto &DBG_PHI : DBGPHIRange) {
4204344a3780SDimitry Andric LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB);
4205145449b1SDimitry Andric const ValueIDNum &Num = *DBG_PHI.ValueRead;
4206344a3780SDimitry Andric ValidatedValues.insert(std::make_pair(Block, Num));
4207344a3780SDimitry Andric }
4208344a3780SDimitry Andric
4209344a3780SDimitry Andric // Sort PHIs to validate into RPO-order.
4210344a3780SDimitry Andric SmallVector<LDVSSAPhi *, 8> SortedPHIs;
4211344a3780SDimitry Andric for (auto &PHI : CreatedPHIs)
4212344a3780SDimitry Andric SortedPHIs.push_back(PHI);
4213344a3780SDimitry Andric
42144b4fe385SDimitry Andric llvm::sort(SortedPHIs, [&](LDVSSAPhi *A, LDVSSAPhi *B) {
4215344a3780SDimitry Andric return BBToOrder[&A->getParent()->BB] < BBToOrder[&B->getParent()->BB];
4216344a3780SDimitry Andric });
4217344a3780SDimitry Andric
4218344a3780SDimitry Andric for (auto &PHI : SortedPHIs) {
421999aabd70SDimitry Andric ValueIDNum ThisBlockValueNum = MLiveIns[PHI->ParentBlock->BB][Loc.asU64()];
4220344a3780SDimitry Andric
4221344a3780SDimitry Andric // Are all these things actually defined?
4222344a3780SDimitry Andric for (auto &PHIIt : PHI->IncomingValues) {
4223344a3780SDimitry Andric // Any undef input means DBG_PHIs didn't dominate the use point.
4224ac9a064cSDimitry Andric if (Updater.PoisonMap.contains(&PHIIt.first->BB))
4225e3b55780SDimitry Andric return std::nullopt;
4226344a3780SDimitry Andric
4227344a3780SDimitry Andric ValueIDNum ValueToCheck;
422899aabd70SDimitry Andric const ValueTable &BlockLiveOuts = MLiveOuts[PHIIt.first->BB];
4229344a3780SDimitry Andric
4230344a3780SDimitry Andric auto VVal = ValidatedValues.find(PHIIt.first);
4231344a3780SDimitry Andric if (VVal == ValidatedValues.end()) {
4232344a3780SDimitry Andric // We cross a loop, and this is a backedge. LLVMs tail duplication
4233344a3780SDimitry Andric // happens so late that DBG_PHI instructions should not be able to
4234344a3780SDimitry Andric // migrate into loops -- meaning we can only be live-through this
4235344a3780SDimitry Andric // loop.
4236344a3780SDimitry Andric ValueToCheck = ThisBlockValueNum;
4237344a3780SDimitry Andric } else {
4238344a3780SDimitry Andric // Does the block have as a live-out, in the location we're examining,
4239344a3780SDimitry Andric // the value that we expect? If not, it's been moved or clobbered.
4240344a3780SDimitry Andric ValueToCheck = VVal->second;
4241344a3780SDimitry Andric }
4242344a3780SDimitry Andric
4243344a3780SDimitry Andric if (BlockLiveOuts[Loc.asU64()] != ValueToCheck)
4244e3b55780SDimitry Andric return std::nullopt;
4245344a3780SDimitry Andric }
4246344a3780SDimitry Andric
4247344a3780SDimitry Andric // Record this value as validated.
4248344a3780SDimitry Andric ValidatedValues.insert({PHI->ParentBlock, ThisBlockValueNum});
4249344a3780SDimitry Andric }
4250344a3780SDimitry Andric
4251344a3780SDimitry Andric // All the PHIs are valid: we can return what the SSAUpdater said our value
4252344a3780SDimitry Andric // number was.
4253344a3780SDimitry Andric return Result;
4254344a3780SDimitry Andric }
4255