1ae6f7882SJeremy Morse //===- InstrRefBasedImpl.cpp - Tracking Debug Value MIs -------------------===//
2ae6f7882SJeremy Morse //
3ae6f7882SJeremy Morse // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4ae6f7882SJeremy Morse // See https://llvm.org/LICENSE.txt for license information.
5ae6f7882SJeremy Morse // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ae6f7882SJeremy Morse //
7ae6f7882SJeremy Morse //===----------------------------------------------------------------------===//
8ae6f7882SJeremy Morse /// \file InstrRefBasedImpl.cpp
9ae6f7882SJeremy Morse ///
10ae6f7882SJeremy Morse /// This is a separate implementation of LiveDebugValues, see
11ae6f7882SJeremy Morse /// LiveDebugValues.cpp and VarLocBasedImpl.cpp for more information.
12ae6f7882SJeremy Morse ///
13ae6f7882SJeremy Morse /// This pass propagates variable locations between basic blocks, resolving
14a3936a6cSJeremy Morse /// control flow conflicts between them. The problem is SSA construction, where
15a3936a6cSJeremy Morse /// each debug instruction assigns the *value* that a variable has, and every
16a3936a6cSJeremy Morse /// instruction where the variable is in scope uses that variable. The resulting
17a3936a6cSJeremy Morse /// map of instruction-to-value is then translated into a register (or spill)
18a3936a6cSJeremy Morse /// location for each variable over each instruction.
19ae6f7882SJeremy Morse ///
20a3936a6cSJeremy Morse /// The primary difference from normal SSA construction is that we cannot
21a3936a6cSJeremy Morse /// _create_ PHI values that contain variable values. CodeGen has already
22a3936a6cSJeremy Morse /// completed, and we can't alter it just to make debug-info complete. Thus:
23a3936a6cSJeremy Morse /// we can identify function positions where we would like a PHI value for a
24a3936a6cSJeremy Morse /// variable, but must search the MachineFunction to see whether such a PHI is
25a3936a6cSJeremy Morse /// available. If no such PHI exists, the variable location must be dropped.
26ae6f7882SJeremy Morse ///
27a3936a6cSJeremy Morse /// To achieve this, we perform two kinds of analysis. First, we identify
28ae6f7882SJeremy Morse /// every value defined by every instruction (ignoring those that only move
29a3936a6cSJeremy Morse /// another value), then re-compute an SSA-form representation of the
30a3936a6cSJeremy Morse /// MachineFunction, using value propagation to eliminate any un-necessary
31a3936a6cSJeremy Morse /// PHI values. This gives us a map of every value computed in the function,
32a3936a6cSJeremy Morse /// and its location within the register file / stack.
33ae6f7882SJeremy Morse ///
34a3936a6cSJeremy Morse /// Secondly, for each variable we perform the same analysis, where each debug
35a3936a6cSJeremy Morse /// instruction is considered a def, and every instruction where the variable
36a3936a6cSJeremy Morse /// is in lexical scope as a use. Value propagation is used again to eliminate
37a3936a6cSJeremy Morse /// any un-necessary PHIs. This gives us a map of each variable to the value
38a3936a6cSJeremy Morse /// it should have in a block.
39ae6f7882SJeremy Morse ///
40a3936a6cSJeremy Morse /// Once both are complete, we have two maps for each block:
41a3936a6cSJeremy Morse ///  * Variables to the values they should have,
42a3936a6cSJeremy Morse ///  * Values to the register / spill slot they are located in.
43a3936a6cSJeremy Morse /// After which we can marry-up variable values with a location, and emit
44a3936a6cSJeremy Morse /// DBG_VALUE instructions specifying those locations. Variable locations may
45a3936a6cSJeremy Morse /// be dropped in this process due to the desired variable value not being
46a3936a6cSJeremy Morse /// resident in any machine location, or because there is no PHI value in any
47a3936a6cSJeremy Morse /// location that accurately represents the desired value.  The building of
48a3936a6cSJeremy Morse /// location lists for each block is left to DbgEntityHistoryCalculator.
49ae6f7882SJeremy Morse ///
50a3936a6cSJeremy Morse /// This pass is kept efficient because the size of the first SSA problem
51a3936a6cSJeremy Morse /// is proportional to the working-set size of the function, which the compiler
52a3936a6cSJeremy Morse /// tries to keep small. (It's also proportional to the number of blocks).
53a3936a6cSJeremy Morse /// Additionally, we repeatedly perform the second SSA problem analysis with
54a3936a6cSJeremy Morse /// only the variables and blocks in a single lexical scope, exploiting their
55a3936a6cSJeremy Morse /// locality.
56ae6f7882SJeremy Morse ///
57ae6f7882SJeremy Morse /// ### Terminology
58ae6f7882SJeremy Morse ///
59ae6f7882SJeremy Morse /// A machine location is a register or spill slot, a value is something that's
60ae6f7882SJeremy Morse /// defined by an instruction or PHI node, while a variable value is the value
61ae6f7882SJeremy Morse /// assigned to a variable. A variable location is a machine location, that must
62ae6f7882SJeremy Morse /// contain the appropriate variable value. A value that is a PHI node is
63ae6f7882SJeremy Morse /// occasionally called an mphi.
64ae6f7882SJeremy Morse ///
65a3936a6cSJeremy Morse /// The first SSA problem is the "machine value location" problem,
66ae6f7882SJeremy Morse /// because we're determining which machine locations contain which values.
67ae6f7882SJeremy Morse /// The "locations" are constant: what's unknown is what value they contain.
68ae6f7882SJeremy Morse ///
69a3936a6cSJeremy Morse /// The second SSA problem (the one for variables) is the "variable value
70ae6f7882SJeremy Morse /// problem", because it's determining what values a variable has, rather than
71a3936a6cSJeremy Morse /// what location those values are placed in.
72ae6f7882SJeremy Morse ///
73ae6f7882SJeremy Morse /// TODO:
74ae6f7882SJeremy Morse ///   Overlapping fragments
75ae6f7882SJeremy Morse ///   Entry values
76ae6f7882SJeremy Morse ///   Add back DEBUG statements for debugging this
77ae6f7882SJeremy Morse ///   Collect statistics
78ae6f7882SJeremy Morse ///
79ae6f7882SJeremy Morse //===----------------------------------------------------------------------===//
80ae6f7882SJeremy Morse 
81ae6f7882SJeremy Morse #include "llvm/ADT/DenseMap.h"
82ae6f7882SJeremy Morse #include "llvm/ADT/PostOrderIterator.h"
83010108bbSJeremy Morse #include "llvm/ADT/STLExtras.h"
84ae6f7882SJeremy Morse #include "llvm/ADT/SmallPtrSet.h"
85ae6f7882SJeremy Morse #include "llvm/ADT/SmallSet.h"
86ae6f7882SJeremy Morse #include "llvm/ADT/SmallVector.h"
87989f1c72Sserge-sans-paille #include "llvm/BinaryFormat/Dwarf.h"
88ae6f7882SJeremy Morse #include "llvm/CodeGen/LexicalScopes.h"
89ae6f7882SJeremy Morse #include "llvm/CodeGen/MachineBasicBlock.h"
90a3936a6cSJeremy Morse #include "llvm/CodeGen/MachineDominators.h"
91ae6f7882SJeremy Morse #include "llvm/CodeGen/MachineFrameInfo.h"
92ae6f7882SJeremy Morse #include "llvm/CodeGen/MachineFunction.h"
93ae6f7882SJeremy Morse #include "llvm/CodeGen/MachineInstr.h"
94ae6f7882SJeremy Morse #include "llvm/CodeGen/MachineInstrBuilder.h"
951575583fSJeremy Morse #include "llvm/CodeGen/MachineInstrBundle.h"
96ae6f7882SJeremy Morse #include "llvm/CodeGen/MachineMemOperand.h"
97ae6f7882SJeremy Morse #include "llvm/CodeGen/MachineOperand.h"
98ae6f7882SJeremy Morse #include "llvm/CodeGen/PseudoSourceValue.h"
99ae6f7882SJeremy Morse #include "llvm/CodeGen/TargetFrameLowering.h"
100ae6f7882SJeremy Morse #include "llvm/CodeGen/TargetInstrInfo.h"
101ae6f7882SJeremy Morse #include "llvm/CodeGen/TargetLowering.h"
102ae6f7882SJeremy Morse #include "llvm/CodeGen/TargetPassConfig.h"
103ae6f7882SJeremy Morse #include "llvm/CodeGen/TargetRegisterInfo.h"
104ae6f7882SJeremy Morse #include "llvm/CodeGen/TargetSubtargetInfo.h"
105ae6f7882SJeremy Morse #include "llvm/Config/llvm-config.h"
106ae6f7882SJeremy Morse #include "llvm/IR/DebugInfoMetadata.h"
107ae6f7882SJeremy Morse #include "llvm/IR/DebugLoc.h"
108ae6f7882SJeremy Morse #include "llvm/IR/Function.h"
109ae6f7882SJeremy Morse #include "llvm/MC/MCRegisterInfo.h"
110ae6f7882SJeremy Morse #include "llvm/Support/Casting.h"
111ae6f7882SJeremy Morse #include "llvm/Support/Compiler.h"
112ae6f7882SJeremy Morse #include "llvm/Support/Debug.h"
113989f1c72Sserge-sans-paille #include "llvm/Support/GenericIteratedDominanceFrontier.h"
11484a11209SSander de Smalen #include "llvm/Support/TypeSize.h"
115ae6f7882SJeremy Morse #include "llvm/Support/raw_ostream.h"
1161575583fSJeremy Morse #include "llvm/Target/TargetMachine.h"
117010108bbSJeremy Morse #include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
118ae6f7882SJeremy Morse #include <algorithm>
119ae6f7882SJeremy Morse #include <cassert>
120989f1c72Sserge-sans-paille #include <climits>
121ae6f7882SJeremy Morse #include <cstdint>
122ae6f7882SJeremy Morse #include <functional>
123ae6f7882SJeremy Morse #include <queue>
124ae6f7882SJeremy Morse #include <tuple>
125ae6f7882SJeremy Morse #include <utility>
126ae6f7882SJeremy Morse #include <vector>
127ae6f7882SJeremy Morse 
128838b4a53SJeremy Morse #include "InstrRefBasedImpl.h"
129ae6f7882SJeremy Morse #include "LiveDebugValues.h"
130ae6f7882SJeremy Morse 
131ae6f7882SJeremy Morse using namespace llvm;
132838b4a53SJeremy Morse using namespace LiveDebugValues;
133ae6f7882SJeremy Morse 
134010108bbSJeremy Morse // SSAUpdaterImple sets DEBUG_TYPE, change it.
135010108bbSJeremy Morse #undef DEBUG_TYPE
136ae6f7882SJeremy Morse #define DEBUG_TYPE "livedebugvalues"
137ae6f7882SJeremy Morse 
138ae6f7882SJeremy Morse // Act more like the VarLoc implementation, by propagating some locations too
139ae6f7882SJeremy Morse // far and ignoring some transfers.
140ae6f7882SJeremy Morse static cl::opt<bool> EmulateOldLDV("emulate-old-livedebugvalues", cl::Hidden,
141ae6f7882SJeremy Morse                                    cl::desc("Act like old LiveDebugValues did"),
142ae6f7882SJeremy Morse                                    cl::init(false));
143ae6f7882SJeremy Morse 
14414aaaa12SJeremy Morse // Limit for the maximum number of stack slots we should track, past which we
14514aaaa12SJeremy Morse // will ignore any spills. InstrRefBasedLDV gathers detailed information on all
14614aaaa12SJeremy Morse // stack slots which leads to high memory consumption, and in some scenarios
14714aaaa12SJeremy Morse // (such as asan with very many locals) the working set of the function can be
14814aaaa12SJeremy Morse // very large, causing many spills. In these scenarios, it is very unlikely that
14914aaaa12SJeremy Morse // the developer has hundreds of variables live at the same time that they're
15014aaaa12SJeremy Morse // carefully thinking about -- instead, they probably autogenerated the code.
15114aaaa12SJeremy Morse // When this happens, gracefully stop tracking excess spill slots, rather than
15214aaaa12SJeremy Morse // consuming all the developer's memory.
15314aaaa12SJeremy Morse static cl::opt<unsigned>
15414aaaa12SJeremy Morse     StackWorkingSetLimit("livedebugvalues-max-stack-slots", cl::Hidden,
15514aaaa12SJeremy Morse                          cl::desc("livedebugvalues-stack-ws-limit"),
15614aaaa12SJeremy Morse                          cl::init(250));
15714aaaa12SJeremy Morse 
158ae6f7882SJeremy Morse /// Tracker for converting machine value locations and variable values into
159ae6f7882SJeremy Morse /// variable locations (the output of LiveDebugValues), recorded as DBG_VALUEs
160ae6f7882SJeremy Morse /// specifying block live-in locations and transfers within blocks.
161ae6f7882SJeremy Morse ///
162ae6f7882SJeremy Morse /// Operating on a per-block basis, this class takes a (pre-loaded) MLocTracker
163ae6f7882SJeremy Morse /// and must be initialized with the set of variable values that are live-in to
164ae6f7882SJeremy Morse /// the block. The caller then repeatedly calls process(). TransferTracker picks
165ae6f7882SJeremy Morse /// out variable locations for the live-in variable values (if there _is_ a
166ae6f7882SJeremy Morse /// location) and creates the corresponding DBG_VALUEs. Then, as the block is
167ae6f7882SJeremy Morse /// stepped through, transfers of values between machine locations are
168ae6f7882SJeremy Morse /// identified and if profitable, a DBG_VALUE created.
169ae6f7882SJeremy Morse ///
170ae6f7882SJeremy Morse /// This is where debug use-before-defs would be resolved: a variable with an
171ae6f7882SJeremy Morse /// unavailable value could materialize in the middle of a block, when the
172ae6f7882SJeremy Morse /// value becomes available. Or, we could detect clobbers and re-specify the
173ae6f7882SJeremy Morse /// variable in a backup location. (XXX these are unimplemented).
174ae6f7882SJeremy Morse class TransferTracker {
175ae6f7882SJeremy Morse public:
176ae6f7882SJeremy Morse   const TargetInstrInfo *TII;
1771575583fSJeremy Morse   const TargetLowering *TLI;
178ae6f7882SJeremy Morse   /// This machine location tracker is assumed to always contain the up-to-date
179ae6f7882SJeremy Morse   /// value mapping for all machine locations. TransferTracker only reads
180ae6f7882SJeremy Morse   /// information from it. (XXX make it const?)
181ae6f7882SJeremy Morse   MLocTracker *MTracker;
182ae6f7882SJeremy Morse   MachineFunction &MF;
1831575583fSJeremy Morse   bool ShouldEmitDebugEntryValues;
184ae6f7882SJeremy Morse 
185ae6f7882SJeremy Morse   /// Record of all changes in variable locations at a block position. Awkwardly
186ae6f7882SJeremy Morse   /// we allow inserting either before or after the point: MBB != nullptr
187ae6f7882SJeremy Morse   /// indicates it's before, otherwise after.
188ae6f7882SJeremy Morse   struct Transfer {
1891575583fSJeremy Morse     MachineBasicBlock::instr_iterator Pos; /// Position to insert DBG_VALUes
190ae6f7882SJeremy Morse     MachineBasicBlock *MBB; /// non-null if we should insert after.
191ae6f7882SJeremy Morse     SmallVector<MachineInstr *, 4> Insts; /// Vector of DBG_VALUEs to insert.
192ae6f7882SJeremy Morse   };
193ae6f7882SJeremy Morse 
19459d90fe8SFangrui Song   struct LocAndProperties {
195ae6f7882SJeremy Morse     LocIdx Loc;
196ae6f7882SJeremy Morse     DbgValueProperties Properties;
19759d90fe8SFangrui Song   };
198ae6f7882SJeremy Morse 
199ae6f7882SJeremy Morse   /// Collection of transfers (DBG_VALUEs) to be inserted.
200ae6f7882SJeremy Morse   SmallVector<Transfer, 32> Transfers;
201ae6f7882SJeremy Morse 
202ae6f7882SJeremy Morse   /// Local cache of what-value-is-in-what-LocIdx. Used to identify differences
203ae6f7882SJeremy Morse   /// between TransferTrackers view of variable locations and MLocTrackers. For
204ae6f7882SJeremy Morse   /// example, MLocTracker observes all clobbers, but TransferTracker lazily
205ae6f7882SJeremy Morse   /// does not.
2064136897bSJeremy Morse   SmallVector<ValueIDNum, 32> VarLocs;
207ae6f7882SJeremy Morse 
208ae6f7882SJeremy Morse   /// Map from LocIdxes to which DebugVariables are based that location.
209ae6f7882SJeremy Morse   /// Mantained while stepping through the block. Not accurate if
210ae6f7882SJeremy Morse   /// VarLocs[Idx] != MTracker->LocIdxToIDNum[Idx].
2114136897bSJeremy Morse   DenseMap<LocIdx, SmallSet<DebugVariable, 4>> ActiveMLocs;
212ae6f7882SJeremy Morse 
213ae6f7882SJeremy Morse   /// Map from DebugVariable to it's current location and qualifying meta
214ae6f7882SJeremy Morse   /// information. To be used in conjunction with ActiveMLocs to construct
215ae6f7882SJeremy Morse   /// enough information for the DBG_VALUEs for a particular LocIdx.
216ae6f7882SJeremy Morse   DenseMap<DebugVariable, LocAndProperties> ActiveVLocs;
217ae6f7882SJeremy Morse 
218ae6f7882SJeremy Morse   /// Temporary cache of DBG_VALUEs to be entered into the Transfers collection.
219ae6f7882SJeremy Morse   SmallVector<MachineInstr *, 4> PendingDbgValues;
220ae6f7882SJeremy Morse 
221b1b2c6abSJeremy Morse   /// Record of a use-before-def: created when a value that's live-in to the
222b1b2c6abSJeremy Morse   /// current block isn't available in any machine location, but it will be
223b1b2c6abSJeremy Morse   /// defined in this block.
224b1b2c6abSJeremy Morse   struct UseBeforeDef {
225b1b2c6abSJeremy Morse     /// Value of this variable, def'd in block.
226b1b2c6abSJeremy Morse     ValueIDNum ID;
227b1b2c6abSJeremy Morse     /// Identity of this variable.
228b1b2c6abSJeremy Morse     DebugVariable Var;
229b1b2c6abSJeremy Morse     /// Additional variable properties.
230b1b2c6abSJeremy Morse     DbgValueProperties Properties;
231b1b2c6abSJeremy Morse   };
232b1b2c6abSJeremy Morse 
233b1b2c6abSJeremy Morse   /// Map from instruction index (within the block) to the set of UseBeforeDefs
234b1b2c6abSJeremy Morse   /// that become defined at that instruction.
235b1b2c6abSJeremy Morse   DenseMap<unsigned, SmallVector<UseBeforeDef, 1>> UseBeforeDefs;
236b1b2c6abSJeremy Morse 
237b1b2c6abSJeremy Morse   /// The set of variables that are in UseBeforeDefs and can become a location
238b1b2c6abSJeremy Morse   /// once the relevant value is defined. An element being erased from this
239b1b2c6abSJeremy Morse   /// collection prevents the use-before-def materializing.
240b1b2c6abSJeremy Morse   DenseSet<DebugVariable> UseBeforeDefVariables;
241b1b2c6abSJeremy Morse 
242ae6f7882SJeremy Morse   const TargetRegisterInfo &TRI;
243ae6f7882SJeremy Morse   const BitVector &CalleeSavedRegs;
244ae6f7882SJeremy Morse 
TransferTracker(const TargetInstrInfo * TII,MLocTracker * MTracker,MachineFunction & MF,const TargetRegisterInfo & TRI,const BitVector & CalleeSavedRegs,const TargetPassConfig & TPC)245ae6f7882SJeremy Morse   TransferTracker(const TargetInstrInfo *TII, MLocTracker *MTracker,
246ae6f7882SJeremy Morse                   MachineFunction &MF, const TargetRegisterInfo &TRI,
2471575583fSJeremy Morse                   const BitVector &CalleeSavedRegs, const TargetPassConfig &TPC)
248ae6f7882SJeremy Morse       : TII(TII), MTracker(MTracker), MF(MF), TRI(TRI),
2491575583fSJeremy Morse         CalleeSavedRegs(CalleeSavedRegs) {
2501575583fSJeremy Morse     TLI = MF.getSubtarget().getTargetLowering();
2511575583fSJeremy Morse     auto &TM = TPC.getTM<TargetMachine>();
2521575583fSJeremy Morse     ShouldEmitDebugEntryValues = TM.Options.ShouldEmitDebugEntryValues();
2531575583fSJeremy Morse   }
254ae6f7882SJeremy Morse 
255ae6f7882SJeremy Morse   /// Load object with live-in variable values. \p mlocs contains the live-in
256ae6f7882SJeremy Morse   /// values in each machine location, while \p vlocs the live-in variable
257ae6f7882SJeremy Morse   /// values. This method picks variable locations for the live-in variables,
258ae6f7882SJeremy Morse   /// creates DBG_VALUEs and puts them in #Transfers, then prepares the other
259ae6f7882SJeremy Morse   /// object fields to track variable locations as we step through the block.
260ae6f7882SJeremy Morse   /// FIXME: could just examine mloctracker instead of passing in \p mlocs?
2610d51b6abSNikita Popov   void
loadInlocs(MachineBasicBlock & MBB,ValueTable & MLocs,const SmallVectorImpl<std::pair<DebugVariable,DbgValue>> & VLocs,unsigned NumLocs)262ab49dce0SJeremy Morse   loadInlocs(MachineBasicBlock &MBB, ValueTable &MLocs,
2630d51b6abSNikita Popov              const SmallVectorImpl<std::pair<DebugVariable, DbgValue>> &VLocs,
264ae6f7882SJeremy Morse              unsigned NumLocs) {
265ae6f7882SJeremy Morse     ActiveMLocs.clear();
266ae6f7882SJeremy Morse     ActiveVLocs.clear();
267ae6f7882SJeremy Morse     VarLocs.clear();
268ae6f7882SJeremy Morse     VarLocs.reserve(NumLocs);
269b1b2c6abSJeremy Morse     UseBeforeDefs.clear();
270b1b2c6abSJeremy Morse     UseBeforeDefVariables.clear();
271ae6f7882SJeremy Morse 
272ae6f7882SJeremy Morse     auto isCalleeSaved = [&](LocIdx L) {
273ae6f7882SJeremy Morse       unsigned Reg = MTracker->LocIdxToLocID[L];
274ae6f7882SJeremy Morse       if (Reg >= MTracker->NumRegs)
275ae6f7882SJeremy Morse         return false;
276ae6f7882SJeremy Morse       for (MCRegAliasIterator RAI(Reg, &TRI, true); RAI.isValid(); ++RAI)
277ae6f7882SJeremy Morse         if (CalleeSavedRegs.test(*RAI))
278ae6f7882SJeremy Morse           return true;
279ae6f7882SJeremy Morse       return false;
280ae6f7882SJeremy Morse     };
281ae6f7882SJeremy Morse 
282ae6f7882SJeremy Morse     // Map of the preferred location for each value.
283cbaae614SNikita Popov     DenseMap<ValueIDNum, LocIdx> ValueToLoc;
28491fb66cfSJeremy Morse 
28591fb66cfSJeremy Morse     // Initialized the preferred-location map with illegal locations, to be
28691fb66cfSJeremy Morse     // filled in later.
2879e6d1f4bSKazu Hirata     for (const auto &VLoc : VLocs)
28891fb66cfSJeremy Morse       if (VLoc.second.Kind == DbgValue::Def)
28991fb66cfSJeremy Morse         ValueToLoc.insert({VLoc.second.ID, LocIdx::MakeIllegalLoc()});
29091fb66cfSJeremy Morse 
2914136897bSJeremy Morse     ActiveMLocs.reserve(VLocs.size());
2924136897bSJeremy Morse     ActiveVLocs.reserve(VLocs.size());
293ae6f7882SJeremy Morse 
294ae6f7882SJeremy Morse     // Produce a map of value numbers to the current machine locs they live
295ae6f7882SJeremy Morse     // in. When emulating VarLocBasedImpl, there should only be one
296ae6f7882SJeremy Morse     // location; when not, we get to pick.
297ae6f7882SJeremy Morse     for (auto Location : MTracker->locations()) {
298ae6f7882SJeremy Morse       LocIdx Idx = Location.Idx;
299ae6f7882SJeremy Morse       ValueIDNum &VNum = MLocs[Idx.asU64()];
300ae6f7882SJeremy Morse       VarLocs.push_back(VNum);
301764e52f0SEugene Zhulenev 
30291fb66cfSJeremy Morse       // Is there a variable that wants a location for this value? If not, skip.
30391fb66cfSJeremy Morse       auto VIt = ValueToLoc.find(VNum);
30491fb66cfSJeremy Morse       if (VIt == ValueToLoc.end())
305764e52f0SEugene Zhulenev         continue;
306764e52f0SEugene Zhulenev 
30791fb66cfSJeremy Morse       LocIdx CurLoc = VIt->second;
308ae6f7882SJeremy Morse       // In order of preference, pick:
309ae6f7882SJeremy Morse       //  * Callee saved registers,
310ae6f7882SJeremy Morse       //  * Other registers,
311ae6f7882SJeremy Morse       //  * Spill slots.
31291fb66cfSJeremy Morse       if (CurLoc.isIllegal() || MTracker->isSpill(CurLoc) ||
31391fb66cfSJeremy Morse           (!isCalleeSaved(CurLoc) && isCalleeSaved(Idx.asU64()))) {
314ae6f7882SJeremy Morse         // Insert, or overwrite if insertion failed.
31591fb66cfSJeremy Morse         VIt->second = Idx;
316ae6f7882SJeremy Morse       }
317ae6f7882SJeremy Morse     }
318ae6f7882SJeremy Morse 
319ae6f7882SJeremy Morse     // Now map variables to their picked LocIdxes.
3200d51b6abSNikita Popov     for (const auto &Var : VLocs) {
321ae6f7882SJeremy Morse       if (Var.second.Kind == DbgValue::Const) {
322ae6f7882SJeremy Morse         PendingDbgValues.push_back(
323b5426cedSJeremy Morse             emitMOLoc(*Var.second.MO, Var.first, Var.second.Properties));
324ae6f7882SJeremy Morse         continue;
325ae6f7882SJeremy Morse       }
326ae6f7882SJeremy Morse 
327ae6f7882SJeremy Morse       // If the value has no location, we can't make a variable location.
328b1b2c6abSJeremy Morse       const ValueIDNum &Num = Var.second.ID;
329b1b2c6abSJeremy Morse       auto ValuesPreferredLoc = ValueToLoc.find(Num);
33091fb66cfSJeremy Morse       if (ValuesPreferredLoc->second.isIllegal()) {
331b1b2c6abSJeremy Morse         // If it's a def that occurs in this block, register it as a
332b1b2c6abSJeremy Morse         // use-before-def to be resolved as we step through the block.
333b1b2c6abSJeremy Morse         if (Num.getBlock() == (unsigned)MBB.getNumber() && !Num.isPHI())
334b1b2c6abSJeremy Morse           addUseBeforeDef(Var.first, Var.second.Properties, Num);
3351575583fSJeremy Morse         else
3361575583fSJeremy Morse           recoverAsEntryValue(Var.first, Var.second.Properties, Num);
337ae6f7882SJeremy Morse         continue;
338b1b2c6abSJeremy Morse       }
339ae6f7882SJeremy Morse 
340ae6f7882SJeremy Morse       LocIdx M = ValuesPreferredLoc->second;
341ae6f7882SJeremy Morse       auto NewValue = LocAndProperties{M, Var.second.Properties};
342ae6f7882SJeremy Morse       auto Result = ActiveVLocs.insert(std::make_pair(Var.first, NewValue));
343ae6f7882SJeremy Morse       if (!Result.second)
344ae6f7882SJeremy Morse         Result.first->second = NewValue;
345ae6f7882SJeremy Morse       ActiveMLocs[M].insert(Var.first);
346ae6f7882SJeremy Morse       PendingDbgValues.push_back(
347ae6f7882SJeremy Morse           MTracker->emitLoc(M, Var.first, Var.second.Properties));
348ae6f7882SJeremy Morse     }
349ae6f7882SJeremy Morse     flushDbgValues(MBB.begin(), &MBB);
350ae6f7882SJeremy Morse   }
351ae6f7882SJeremy Morse 
352b1b2c6abSJeremy Morse   /// Record that \p Var has value \p ID, a value that becomes available
353b1b2c6abSJeremy Morse   /// later in the function.
addUseBeforeDef(const DebugVariable & Var,const DbgValueProperties & Properties,ValueIDNum ID)354b1b2c6abSJeremy Morse   void addUseBeforeDef(const DebugVariable &Var,
355b1b2c6abSJeremy Morse                        const DbgValueProperties &Properties, ValueIDNum ID) {
356b1b2c6abSJeremy Morse     UseBeforeDef UBD = {ID, Var, Properties};
357b1b2c6abSJeremy Morse     UseBeforeDefs[ID.getInst()].push_back(UBD);
358b1b2c6abSJeremy Morse     UseBeforeDefVariables.insert(Var);
359b1b2c6abSJeremy Morse   }
360b1b2c6abSJeremy Morse 
361b1b2c6abSJeremy Morse   /// After the instruction at index \p Inst and position \p pos has been
362b1b2c6abSJeremy Morse   /// processed, check whether it defines a variable value in a use-before-def.
363b1b2c6abSJeremy Morse   /// If so, and the variable value hasn't changed since the start of the
364b1b2c6abSJeremy Morse   /// block, create a DBG_VALUE.
checkInstForNewValues(unsigned Inst,MachineBasicBlock::iterator pos)365b1b2c6abSJeremy Morse   void checkInstForNewValues(unsigned Inst, MachineBasicBlock::iterator pos) {
366b1b2c6abSJeremy Morse     auto MIt = UseBeforeDefs.find(Inst);
367b1b2c6abSJeremy Morse     if (MIt == UseBeforeDefs.end())
368b1b2c6abSJeremy Morse       return;
369b1b2c6abSJeremy Morse 
370b1b2c6abSJeremy Morse     for (auto &Use : MIt->second) {
371b1b2c6abSJeremy Morse       LocIdx L = Use.ID.getLoc();
372b1b2c6abSJeremy Morse 
373b1b2c6abSJeremy Morse       // If something goes very wrong, we might end up labelling a COPY
374b1b2c6abSJeremy Morse       // instruction or similar with an instruction number, where it doesn't
375b1b2c6abSJeremy Morse       // actually define a new value, instead it moves a value. In case this
376b1b2c6abSJeremy Morse       // happens, discard.
377d9eebe3cSJeremy Morse       if (MTracker->readMLoc(L) != Use.ID)
378b1b2c6abSJeremy Morse         continue;
379b1b2c6abSJeremy Morse 
380b1b2c6abSJeremy Morse       // If a different debug instruction defined the variable value / location
381b1b2c6abSJeremy Morse       // since the start of the block, don't materialize this use-before-def.
382b1b2c6abSJeremy Morse       if (!UseBeforeDefVariables.count(Use.Var))
383b1b2c6abSJeremy Morse         continue;
384b1b2c6abSJeremy Morse 
385b1b2c6abSJeremy Morse       PendingDbgValues.push_back(MTracker->emitLoc(L, Use.Var, Use.Properties));
386b1b2c6abSJeremy Morse     }
387b1b2c6abSJeremy Morse     flushDbgValues(pos, nullptr);
388b1b2c6abSJeremy Morse   }
389b1b2c6abSJeremy Morse 
390ae6f7882SJeremy Morse   /// Helper to move created DBG_VALUEs into Transfers collection.
flushDbgValues(MachineBasicBlock::iterator Pos,MachineBasicBlock * MBB)391ae6f7882SJeremy Morse   void flushDbgValues(MachineBasicBlock::iterator Pos, MachineBasicBlock *MBB) {
3921575583fSJeremy Morse     if (PendingDbgValues.size() == 0)
3931575583fSJeremy Morse       return;
3941575583fSJeremy Morse 
3951575583fSJeremy Morse     // Pick out the instruction start position.
3961575583fSJeremy Morse     MachineBasicBlock::instr_iterator BundleStart;
3971575583fSJeremy Morse     if (MBB && Pos == MBB->begin())
3981575583fSJeremy Morse       BundleStart = MBB->instr_begin();
3991575583fSJeremy Morse     else
4001575583fSJeremy Morse       BundleStart = getBundleStart(Pos->getIterator());
4011575583fSJeremy Morse 
4021575583fSJeremy Morse     Transfers.push_back({BundleStart, MBB, PendingDbgValues});
403ae6f7882SJeremy Morse     PendingDbgValues.clear();
404ae6f7882SJeremy Morse   }
4051575583fSJeremy Morse 
isEntryValueVariable(const DebugVariable & Var,const DIExpression * Expr) const4061575583fSJeremy Morse   bool isEntryValueVariable(const DebugVariable &Var,
4071575583fSJeremy Morse                             const DIExpression *Expr) const {
4081575583fSJeremy Morse     if (!Var.getVariable()->isParameter())
4091575583fSJeremy Morse       return false;
4101575583fSJeremy Morse 
4111575583fSJeremy Morse     if (Var.getInlinedAt())
4121575583fSJeremy Morse       return false;
4131575583fSJeremy Morse 
4141575583fSJeremy Morse     if (Expr->getNumElements() > 0)
4151575583fSJeremy Morse       return false;
4161575583fSJeremy Morse 
4171575583fSJeremy Morse     return true;
4181575583fSJeremy Morse   }
4191575583fSJeremy Morse 
isEntryValueValue(const ValueIDNum & Val) const4201575583fSJeremy Morse   bool isEntryValueValue(const ValueIDNum &Val) const {
4211575583fSJeremy Morse     // Must be in entry block (block number zero), and be a PHI / live-in value.
4221575583fSJeremy Morse     if (Val.getBlock() || !Val.isPHI())
4231575583fSJeremy Morse       return false;
4241575583fSJeremy Morse 
4251575583fSJeremy Morse     // Entry values must enter in a register.
4261575583fSJeremy Morse     if (MTracker->isSpill(Val.getLoc()))
4271575583fSJeremy Morse       return false;
4281575583fSJeremy Morse 
4291575583fSJeremy Morse     Register SP = TLI->getStackPointerRegisterToSaveRestore();
4301575583fSJeremy Morse     Register FP = TRI.getFrameRegister(MF);
4311575583fSJeremy Morse     Register Reg = MTracker->LocIdxToLocID[Val.getLoc()];
4321575583fSJeremy Morse     return Reg != SP && Reg != FP;
4331575583fSJeremy Morse   }
4341575583fSJeremy Morse 
recoverAsEntryValue(const DebugVariable & Var,const DbgValueProperties & Prop,const ValueIDNum & Num)4350d51b6abSNikita Popov   bool recoverAsEntryValue(const DebugVariable &Var,
4360d51b6abSNikita Popov                            const DbgValueProperties &Prop,
4371575583fSJeremy Morse                            const ValueIDNum &Num) {
4381575583fSJeremy Morse     // Is this variable location a candidate to be an entry value. First,
4391575583fSJeremy Morse     // should we be trying this at all?
4401575583fSJeremy Morse     if (!ShouldEmitDebugEntryValues)
4411575583fSJeremy Morse       return false;
4421575583fSJeremy Morse 
4431575583fSJeremy Morse     // Is the variable appropriate for entry values (i.e., is a parameter).
4441575583fSJeremy Morse     if (!isEntryValueVariable(Var, Prop.DIExpr))
4451575583fSJeremy Morse       return false;
4461575583fSJeremy Morse 
4471575583fSJeremy Morse     // Is the value assigned to this variable still the entry value?
4481575583fSJeremy Morse     if (!isEntryValueValue(Num))
4491575583fSJeremy Morse       return false;
4501575583fSJeremy Morse 
4511575583fSJeremy Morse     // Emit a variable location using an entry value expression.
4521575583fSJeremy Morse     DIExpression *NewExpr =
4531575583fSJeremy Morse         DIExpression::prepend(Prop.DIExpr, DIExpression::EntryValue);
4541575583fSJeremy Morse     Register Reg = MTracker->LocIdxToLocID[Num.getLoc()];
4551575583fSJeremy Morse     MachineOperand MO = MachineOperand::CreateReg(Reg, false);
4561575583fSJeremy Morse 
4571575583fSJeremy Morse     PendingDbgValues.push_back(emitMOLoc(MO, Var, {NewExpr, Prop.Indirect}));
4581575583fSJeremy Morse     return true;
459ae6f7882SJeremy Morse   }
460ae6f7882SJeremy Morse 
46168f47157SJeremy Morse   /// Change a variable value after encountering a DBG_VALUE inside a block.
redefVar(const MachineInstr & MI)462ae6f7882SJeremy Morse   void redefVar(const MachineInstr &MI) {
463ae6f7882SJeremy Morse     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
464ae6f7882SJeremy Morse                       MI.getDebugLoc()->getInlinedAt());
46568f47157SJeremy Morse     DbgValueProperties Properties(MI);
46668f47157SJeremy Morse 
467ae6f7882SJeremy Morse     const MachineOperand &MO = MI.getOperand(0);
468ae6f7882SJeremy Morse 
46968f47157SJeremy Morse     // Ignore non-register locations, we don't transfer those.
47068f47157SJeremy Morse     if (!MO.isReg() || MO.getReg() == 0) {
471ae6f7882SJeremy Morse       auto It = ActiveVLocs.find(Var);
472ae6f7882SJeremy Morse       if (It != ActiveVLocs.end()) {
473ae6f7882SJeremy Morse         ActiveMLocs[It->second.Loc].erase(Var);
474ae6f7882SJeremy Morse         ActiveVLocs.erase(It);
47568f47157SJeremy Morse      }
476b1b2c6abSJeremy Morse       // Any use-before-defs no longer apply.
477b1b2c6abSJeremy Morse       UseBeforeDefVariables.erase(Var);
478ae6f7882SJeremy Morse       return;
479ae6f7882SJeremy Morse     }
480ae6f7882SJeremy Morse 
481ae6f7882SJeremy Morse     Register Reg = MO.getReg();
48268f47157SJeremy Morse     LocIdx NewLoc = MTracker->getRegMLoc(Reg);
48368f47157SJeremy Morse     redefVar(MI, Properties, NewLoc);
48468f47157SJeremy Morse   }
48568f47157SJeremy Morse 
48668f47157SJeremy Morse   /// Handle a change in variable location within a block. Terminate the
48768f47157SJeremy Morse   /// variables current location, and record the value it now refers to, so
48868f47157SJeremy Morse   /// that we can detect location transfers later on.
redefVar(const MachineInstr & MI,const DbgValueProperties & Properties,Optional<LocIdx> OptNewLoc)48968f47157SJeremy Morse   void redefVar(const MachineInstr &MI, const DbgValueProperties &Properties,
49068f47157SJeremy Morse                 Optional<LocIdx> OptNewLoc) {
49168f47157SJeremy Morse     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
49268f47157SJeremy Morse                       MI.getDebugLoc()->getInlinedAt());
493b1b2c6abSJeremy Morse     // Any use-before-defs no longer apply.
494b1b2c6abSJeremy Morse     UseBeforeDefVariables.erase(Var);
49568f47157SJeremy Morse 
49668f47157SJeremy Morse     // Erase any previous location,
49768f47157SJeremy Morse     auto It = ActiveVLocs.find(Var);
49868f47157SJeremy Morse     if (It != ActiveVLocs.end())
49968f47157SJeremy Morse       ActiveMLocs[It->second.Loc].erase(Var);
50068f47157SJeremy Morse 
50168f47157SJeremy Morse     // If there _is_ no new location, all we had to do was erase.
50268f47157SJeremy Morse     if (!OptNewLoc)
50368f47157SJeremy Morse       return;
50468f47157SJeremy Morse     LocIdx NewLoc = *OptNewLoc;
505ae6f7882SJeremy Morse 
506ae6f7882SJeremy Morse     // Check whether our local copy of values-by-location in #VarLocs is out of
507ae6f7882SJeremy Morse     // date. Wipe old tracking data for the location if it's been clobbered in
508ae6f7882SJeremy Morse     // the meantime.
509d9eebe3cSJeremy Morse     if (MTracker->readMLoc(NewLoc) != VarLocs[NewLoc.asU64()]) {
5109e6d1f4bSKazu Hirata       for (const auto &P : ActiveMLocs[NewLoc]) {
511ae6f7882SJeremy Morse         ActiveVLocs.erase(P);
512ae6f7882SJeremy Morse       }
51368f47157SJeremy Morse       ActiveMLocs[NewLoc.asU64()].clear();
514d9eebe3cSJeremy Morse       VarLocs[NewLoc.asU64()] = MTracker->readMLoc(NewLoc);
515ae6f7882SJeremy Morse     }
516ae6f7882SJeremy Morse 
51768f47157SJeremy Morse     ActiveMLocs[NewLoc].insert(Var);
518ae6f7882SJeremy Morse     if (It == ActiveVLocs.end()) {
51968f47157SJeremy Morse       ActiveVLocs.insert(
52068f47157SJeremy Morse           std::make_pair(Var, LocAndProperties{NewLoc, Properties}));
521ae6f7882SJeremy Morse     } else {
52268f47157SJeremy Morse       It->second.Loc = NewLoc;
523ae6f7882SJeremy Morse       It->second.Properties = Properties;
524ae6f7882SJeremy Morse     }
525ae6f7882SJeremy Morse   }
526ae6f7882SJeremy Morse 
52749555441SJeremy Morse   /// Account for a location \p mloc being clobbered. Examine the variable
52849555441SJeremy Morse   /// locations that will be terminated: and try to recover them by using
52949555441SJeremy Morse   /// another location. Optionally, given \p MakeUndef, emit a DBG_VALUE to
53049555441SJeremy Morse   /// explicitly terminate a location if it can't be recovered.
clobberMloc(LocIdx MLoc,MachineBasicBlock::iterator Pos,bool MakeUndef=true)53149555441SJeremy Morse   void clobberMloc(LocIdx MLoc, MachineBasicBlock::iterator Pos,
53249555441SJeremy Morse                    bool MakeUndef = true) {
533ae6f7882SJeremy Morse     auto ActiveMLocIt = ActiveMLocs.find(MLoc);
534ae6f7882SJeremy Morse     if (ActiveMLocIt == ActiveMLocs.end())
535ae6f7882SJeremy Morse       return;
536ae6f7882SJeremy Morse 
53749555441SJeremy Morse     // What was the old variable value?
53849555441SJeremy Morse     ValueIDNum OldValue = VarLocs[MLoc.asU64()];
539f9ac161aSStephen Tozer     clobberMloc(MLoc, OldValue, Pos, MakeUndef);
540f9ac161aSStephen Tozer   }
541f9ac161aSStephen Tozer   /// Overload that takes an explicit value \p OldValue for when the value in
542f9ac161aSStephen Tozer   /// \p MLoc has changed and the TransferTracker's locations have not been
543f9ac161aSStephen Tozer   /// updated yet.
clobberMloc(LocIdx MLoc,ValueIDNum OldValue,MachineBasicBlock::iterator Pos,bool MakeUndef=true)544f9ac161aSStephen Tozer   void clobberMloc(LocIdx MLoc, ValueIDNum OldValue,
545f9ac161aSStephen Tozer                    MachineBasicBlock::iterator Pos, bool MakeUndef = true) {
546f9ac161aSStephen Tozer     auto ActiveMLocIt = ActiveMLocs.find(MLoc);
547f9ac161aSStephen Tozer     if (ActiveMLocIt == ActiveMLocs.end())
548f9ac161aSStephen Tozer       return;
549f9ac161aSStephen Tozer 
550ae6f7882SJeremy Morse     VarLocs[MLoc.asU64()] = ValueIDNum::EmptyValue;
551ae6f7882SJeremy Morse 
55249555441SJeremy Morse     // Examine the remaining variable locations: if we can find the same value
55349555441SJeremy Morse     // again, we can recover the location.
55449555441SJeremy Morse     Optional<LocIdx> NewLoc = None;
55549555441SJeremy Morse     for (auto Loc : MTracker->locations())
55649555441SJeremy Morse       if (Loc.Value == OldValue)
55749555441SJeremy Morse         NewLoc = Loc.Idx;
55849555441SJeremy Morse 
55949555441SJeremy Morse     // If there is no location, and we weren't asked to make the variable
56049555441SJeremy Morse     // explicitly undef, then stop here.
5611575583fSJeremy Morse     if (!NewLoc && !MakeUndef) {
5621575583fSJeremy Morse       // Try and recover a few more locations with entry values.
5639e6d1f4bSKazu Hirata       for (const auto &Var : ActiveMLocIt->second) {
5641575583fSJeremy Morse         auto &Prop = ActiveVLocs.find(Var)->second.Properties;
5651575583fSJeremy Morse         recoverAsEntryValue(Var, Prop, OldValue);
5661575583fSJeremy Morse       }
5671575583fSJeremy Morse       flushDbgValues(Pos, nullptr);
56849555441SJeremy Morse       return;
5691575583fSJeremy Morse     }
57049555441SJeremy Morse 
57149555441SJeremy Morse     // Examine all the variables based on this location.
57249555441SJeremy Morse     DenseSet<DebugVariable> NewMLocs;
5739e6d1f4bSKazu Hirata     for (const auto &Var : ActiveMLocIt->second) {
574ae6f7882SJeremy Morse       auto ActiveVLocIt = ActiveVLocs.find(Var);
57549555441SJeremy Morse       // Re-state the variable location: if there's no replacement then NewLoc
57649555441SJeremy Morse       // is None and a $noreg DBG_VALUE will be created. Otherwise, a DBG_VALUE
57749555441SJeremy Morse       // identifying the alternative location will be emitted.
5789cf31b8dSJeremy Morse       const DbgValueProperties &Properties = ActiveVLocIt->second.Properties;
57949555441SJeremy Morse       PendingDbgValues.push_back(MTracker->emitLoc(NewLoc, Var, Properties));
58049555441SJeremy Morse 
58149555441SJeremy Morse       // Update machine locations <=> variable locations maps. Defer updating
58249555441SJeremy Morse       // ActiveMLocs to avoid invalidaing the ActiveMLocIt iterator.
58349555441SJeremy Morse       if (!NewLoc) {
584ae6f7882SJeremy Morse         ActiveVLocs.erase(ActiveVLocIt);
58549555441SJeremy Morse       } else {
58649555441SJeremy Morse         ActiveVLocIt->second.Loc = *NewLoc;
58749555441SJeremy Morse         NewMLocs.insert(Var);
588ae6f7882SJeremy Morse       }
58949555441SJeremy Morse     }
59049555441SJeremy Morse 
59149555441SJeremy Morse     // Commit any deferred ActiveMLoc changes.
59249555441SJeremy Morse     if (!NewMLocs.empty())
59349555441SJeremy Morse       for (auto &Var : NewMLocs)
59449555441SJeremy Morse         ActiveMLocs[*NewLoc].insert(Var);
59549555441SJeremy Morse 
59649555441SJeremy Morse     // We lazily track what locations have which values; if we've found a new
59749555441SJeremy Morse     // location for the clobbered value, remember it.
59849555441SJeremy Morse     if (NewLoc)
59949555441SJeremy Morse       VarLocs[NewLoc->asU64()] = OldValue;
60049555441SJeremy Morse 
601ae6f7882SJeremy Morse     flushDbgValues(Pos, nullptr);
602ae6f7882SJeremy Morse 
6034136897bSJeremy Morse     // Re-find ActiveMLocIt, iterator could have been invalidated.
6044136897bSJeremy Morse     ActiveMLocIt = ActiveMLocs.find(MLoc);
605ae6f7882SJeremy Morse     ActiveMLocIt->second.clear();
606ae6f7882SJeremy Morse   }
607ae6f7882SJeremy Morse 
608ae6f7882SJeremy Morse   /// Transfer variables based on \p Src to be based on \p Dst. This handles
609ae6f7882SJeremy Morse   /// both register copies as well as spills and restores. Creates DBG_VALUEs
610ae6f7882SJeremy Morse   /// describing the movement.
transferMlocs(LocIdx Src,LocIdx Dst,MachineBasicBlock::iterator Pos)611ae6f7882SJeremy Morse   void transferMlocs(LocIdx Src, LocIdx Dst, MachineBasicBlock::iterator Pos) {
612ae6f7882SJeremy Morse     // Does Src still contain the value num we expect? If not, it's been
613ae6f7882SJeremy Morse     // clobbered in the meantime, and our variable locations are stale.
614d9eebe3cSJeremy Morse     if (VarLocs[Src.asU64()] != MTracker->readMLoc(Src))
615ae6f7882SJeremy Morse       return;
616ae6f7882SJeremy Morse 
617ae6f7882SJeremy Morse     // assert(ActiveMLocs[Dst].size() == 0);
618ae6f7882SJeremy Morse     //^^^ Legitimate scenario on account of un-clobbered slot being assigned to?
6194136897bSJeremy Morse 
6204136897bSJeremy Morse     // Move set of active variables from one location to another.
6214136897bSJeremy Morse     auto MovingVars = ActiveMLocs[Src];
6224136897bSJeremy Morse     ActiveMLocs[Dst] = MovingVars;
623ae6f7882SJeremy Morse     VarLocs[Dst.asU64()] = VarLocs[Src.asU64()];
624ae6f7882SJeremy Morse 
625ae6f7882SJeremy Morse     // For each variable based on Src; create a location at Dst.
6269e6d1f4bSKazu Hirata     for (const auto &Var : MovingVars) {
627ae6f7882SJeremy Morse       auto ActiveVLocIt = ActiveVLocs.find(Var);
628ae6f7882SJeremy Morse       assert(ActiveVLocIt != ActiveVLocs.end());
629ae6f7882SJeremy Morse       ActiveVLocIt->second.Loc = Dst;
630ae6f7882SJeremy Morse 
631ae6f7882SJeremy Morse       MachineInstr *MI =
632ae6f7882SJeremy Morse           MTracker->emitLoc(Dst, Var, ActiveVLocIt->second.Properties);
633ae6f7882SJeremy Morse       PendingDbgValues.push_back(MI);
634ae6f7882SJeremy Morse     }
635ae6f7882SJeremy Morse     ActiveMLocs[Src].clear();
636ae6f7882SJeremy Morse     flushDbgValues(Pos, nullptr);
637ae6f7882SJeremy Morse 
638ae6f7882SJeremy Morse     // XXX XXX XXX "pretend to be old LDV" means dropping all tracking data
639ae6f7882SJeremy Morse     // about the old location.
640ae6f7882SJeremy Morse     if (EmulateOldLDV)
641ae6f7882SJeremy Morse       VarLocs[Src.asU64()] = ValueIDNum::EmptyValue;
642ae6f7882SJeremy Morse   }
643ae6f7882SJeremy Morse 
emitMOLoc(const MachineOperand & MO,const DebugVariable & Var,const DbgValueProperties & Properties)644ae6f7882SJeremy Morse   MachineInstrBuilder emitMOLoc(const MachineOperand &MO,
645ae6f7882SJeremy Morse                                 const DebugVariable &Var,
646ae6f7882SJeremy Morse                                 const DbgValueProperties &Properties) {
647b5ad32efSFangrui Song     DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0,
648b5ad32efSFangrui Song                                   Var.getVariable()->getScope(),
649b5ad32efSFangrui Song                                   const_cast<DILocation *>(Var.getInlinedAt()));
650ae6f7882SJeremy Morse     auto MIB = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE));
651ae6f7882SJeremy Morse     MIB.add(MO);
652ae6f7882SJeremy Morse     if (Properties.Indirect)
653ae6f7882SJeremy Morse       MIB.addImm(0);
654ae6f7882SJeremy Morse     else
655ae6f7882SJeremy Morse       MIB.addReg(0);
656ae6f7882SJeremy Morse     MIB.addMetadata(Var.getVariable());
657ae6f7882SJeremy Morse     MIB.addMetadata(Properties.DIExpr);
658ae6f7882SJeremy Morse     return MIB;
659ae6f7882SJeremy Morse   }
660ae6f7882SJeremy Morse };
661ae6f7882SJeremy Morse 
662ae6f7882SJeremy Morse //===----------------------------------------------------------------------===//
663ae6f7882SJeremy Morse //            Implementation
664ae6f7882SJeremy Morse //===----------------------------------------------------------------------===//
665ae6f7882SJeremy Morse 
666ae6f7882SJeremy Morse ValueIDNum ValueIDNum::EmptyValue = {UINT_MAX, UINT_MAX, UINT_MAX};
6674136897bSJeremy Morse ValueIDNum ValueIDNum::TombstoneValue = {UINT_MAX, UINT_MAX, UINT_MAX - 1};
668ae6f7882SJeremy Morse 
669d9fa186aSJeremy Morse #ifndef NDEBUG
dump(const MLocTracker * MTrack) const670838b4a53SJeremy Morse void DbgValue::dump(const MLocTracker *MTrack) const {
671838b4a53SJeremy Morse   if (Kind == Const) {
672b5426cedSJeremy Morse     MO->dump();
673838b4a53SJeremy Morse   } else if (Kind == NoVal) {
674838b4a53SJeremy Morse     dbgs() << "NoVal(" << BlockNo << ")";
675b5426cedSJeremy Morse   } else if (Kind == VPHI) {
676b5426cedSJeremy Morse     dbgs() << "VPHI(" << BlockNo << "," << MTrack->IDAsString(ID) << ")";
677838b4a53SJeremy Morse   } else {
678838b4a53SJeremy Morse     assert(Kind == Def);
679838b4a53SJeremy Morse     dbgs() << MTrack->IDAsString(ID);
680838b4a53SJeremy Morse   }
681838b4a53SJeremy Morse   if (Properties.Indirect)
682838b4a53SJeremy Morse     dbgs() << " indir";
683838b4a53SJeremy Morse   if (Properties.DIExpr)
684838b4a53SJeremy Morse     dbgs() << " " << *Properties.DIExpr;
685838b4a53SJeremy Morse }
686d9fa186aSJeremy Morse #endif
687838b4a53SJeremy Morse 
MLocTracker(MachineFunction & MF,const TargetInstrInfo & TII,const TargetRegisterInfo & TRI,const TargetLowering & TLI)688838b4a53SJeremy Morse MLocTracker::MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII,
689838b4a53SJeremy Morse                          const TargetRegisterInfo &TRI,
690838b4a53SJeremy Morse                          const TargetLowering &TLI)
691838b4a53SJeremy Morse     : MF(MF), TII(TII), TRI(TRI), TLI(TLI),
692838b4a53SJeremy Morse       LocIdxToIDNum(ValueIDNum::EmptyValue), LocIdxToLocID(0) {
693838b4a53SJeremy Morse   NumRegs = TRI.getNumRegs();
694838b4a53SJeremy Morse   reset();
695838b4a53SJeremy Morse   LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc());
696838b4a53SJeremy Morse   assert(NumRegs < (1u << NUM_LOC_BITS)); // Detect bit packing failure
697838b4a53SJeremy Morse 
698838b4a53SJeremy Morse   // Always track SP. This avoids the implicit clobbering caused by regmasks
699838b4a53SJeremy Morse   // from affectings its values. (LiveDebugValues disbelieves calls and
700838b4a53SJeremy Morse   // regmasks that claim to clobber SP).
701838b4a53SJeremy Morse   Register SP = TLI.getStackPointerRegisterToSaveRestore();
702838b4a53SJeremy Morse   if (SP) {
703e7084ceaSJeremy Morse     unsigned ID = getLocID(SP);
704838b4a53SJeremy Morse     (void)lookupOrTrackRegister(ID);
705fbf269c7SJeremy Morse 
706fbf269c7SJeremy Morse     for (MCRegAliasIterator RAI(SP, &TRI, true); RAI.isValid(); ++RAI)
707fbf269c7SJeremy Morse       SPAliases.insert(*RAI);
708838b4a53SJeremy Morse   }
709e7084ceaSJeremy Morse 
710e7084ceaSJeremy Morse   // Build some common stack positions -- full registers being spilt to the
711e7084ceaSJeremy Morse   // stack.
712e7084ceaSJeremy Morse   StackSlotIdxes.insert({{8, 0}, 0});
713e7084ceaSJeremy Morse   StackSlotIdxes.insert({{16, 0}, 1});
714e7084ceaSJeremy Morse   StackSlotIdxes.insert({{32, 0}, 2});
715e7084ceaSJeremy Morse   StackSlotIdxes.insert({{64, 0}, 3});
716e7084ceaSJeremy Morse   StackSlotIdxes.insert({{128, 0}, 4});
717e7084ceaSJeremy Morse   StackSlotIdxes.insert({{256, 0}, 5});
718e7084ceaSJeremy Morse   StackSlotIdxes.insert({{512, 0}, 6});
719e7084ceaSJeremy Morse 
720e7084ceaSJeremy Morse   // Traverse all the subregister idxes, and ensure there's an index for them.
721e7084ceaSJeremy Morse   // Duplicates are no problem: we're interested in their position in the
722e7084ceaSJeremy Morse   // stack slot, we don't want to type the slot.
723e7084ceaSJeremy Morse   for (unsigned int I = 1; I < TRI.getNumSubRegIndices(); ++I) {
724e7084ceaSJeremy Morse     unsigned Size = TRI.getSubRegIdxSize(I);
725e7084ceaSJeremy Morse     unsigned Offs = TRI.getSubRegIdxOffset(I);
726e7084ceaSJeremy Morse     unsigned Idx = StackSlotIdxes.size();
727e7084ceaSJeremy Morse 
728e7084ceaSJeremy Morse     // Some subregs have -1, -2 and so forth fed into their fields, to mean
729e7084ceaSJeremy Morse     // special backend things. Ignore those.
730e7084ceaSJeremy Morse     if (Size > 60000 || Offs > 60000)
731e7084ceaSJeremy Morse       continue;
732e7084ceaSJeremy Morse 
733e7084ceaSJeremy Morse     StackSlotIdxes.insert({{Size, Offs}, Idx});
734e7084ceaSJeremy Morse   }
735e7084ceaSJeremy Morse 
73665d5becaSJeremy Morse   // There may also be strange register class sizes (think x86 fp80s).
73765d5becaSJeremy Morse   for (const TargetRegisterClass *RC : TRI.regclasses()) {
73865d5becaSJeremy Morse     unsigned Size = TRI.getRegSizeInBits(*RC);
73965d5becaSJeremy Morse 
74065d5becaSJeremy Morse     // We might see special reserved values as sizes, and classes for other
74165d5becaSJeremy Morse     // stuff the machine tries to model. If it's more than 512 bits, then it
74265d5becaSJeremy Morse     // is very unlikely to be a register than can be spilt.
74365d5becaSJeremy Morse     if (Size > 512)
74465d5becaSJeremy Morse       continue;
74565d5becaSJeremy Morse 
74665d5becaSJeremy Morse     unsigned Idx = StackSlotIdxes.size();
74765d5becaSJeremy Morse     StackSlotIdxes.insert({{Size, 0}, Idx});
74865d5becaSJeremy Morse   }
74965d5becaSJeremy Morse 
750e7084ceaSJeremy Morse   for (auto &Idx : StackSlotIdxes)
751e7084ceaSJeremy Morse     StackIdxesToPos[Idx.second] = Idx.first;
752e7084ceaSJeremy Morse 
753e7084ceaSJeremy Morse   NumSlotIdxes = StackSlotIdxes.size();
754838b4a53SJeremy Morse }
755838b4a53SJeremy Morse 
trackRegister(unsigned ID)756838b4a53SJeremy Morse LocIdx MLocTracker::trackRegister(unsigned ID) {
757838b4a53SJeremy Morse   assert(ID != 0);
758838b4a53SJeremy Morse   LocIdx NewIdx = LocIdx(LocIdxToIDNum.size());
759838b4a53SJeremy Morse   LocIdxToIDNum.grow(NewIdx);
760838b4a53SJeremy Morse   LocIdxToLocID.grow(NewIdx);
761838b4a53SJeremy Morse 
762838b4a53SJeremy Morse   // Default: it's an mphi.
763838b4a53SJeremy Morse   ValueIDNum ValNum = {CurBB, 0, NewIdx};
764838b4a53SJeremy Morse   // Was this reg ever touched by a regmask?
765838b4a53SJeremy Morse   for (const auto &MaskPair : reverse(Masks)) {
766838b4a53SJeremy Morse     if (MaskPair.first->clobbersPhysReg(ID)) {
767838b4a53SJeremy Morse       // There was an earlier def we skipped.
768838b4a53SJeremy Morse       ValNum = {CurBB, MaskPair.second, NewIdx};
769838b4a53SJeremy Morse       break;
770838b4a53SJeremy Morse     }
771838b4a53SJeremy Morse   }
772838b4a53SJeremy Morse 
773838b4a53SJeremy Morse   LocIdxToIDNum[NewIdx] = ValNum;
774838b4a53SJeremy Morse   LocIdxToLocID[NewIdx] = ID;
775838b4a53SJeremy Morse   return NewIdx;
776838b4a53SJeremy Morse }
777838b4a53SJeremy Morse 
writeRegMask(const MachineOperand * MO,unsigned CurBB,unsigned InstID)778838b4a53SJeremy Morse void MLocTracker::writeRegMask(const MachineOperand *MO, unsigned CurBB,
779838b4a53SJeremy Morse                                unsigned InstID) {
780838b4a53SJeremy Morse   // Def any register we track have that isn't preserved. The regmask
781838b4a53SJeremy Morse   // terminates the liveness of a register, meaning its value can't be
782838b4a53SJeremy Morse   // relied upon -- we represent this by giving it a new value.
783838b4a53SJeremy Morse   for (auto Location : locations()) {
784838b4a53SJeremy Morse     unsigned ID = LocIdxToLocID[Location.Idx];
785838b4a53SJeremy Morse     // Don't clobber SP, even if the mask says it's clobbered.
786fbf269c7SJeremy Morse     if (ID < NumRegs && !SPAliases.count(ID) && MO->clobbersPhysReg(ID))
787838b4a53SJeremy Morse       defReg(ID, CurBB, InstID);
788838b4a53SJeremy Morse   }
789838b4a53SJeremy Morse   Masks.push_back(std::make_pair(MO, InstID));
790838b4a53SJeremy Morse }
791838b4a53SJeremy Morse 
getOrTrackSpillLoc(SpillLoc L)79214aaaa12SJeremy Morse Optional<SpillLocationNo> MLocTracker::getOrTrackSpillLoc(SpillLoc L) {
793e7084ceaSJeremy Morse   SpillLocationNo SpillID(SpillLocs.idFor(L));
79414aaaa12SJeremy Morse 
795e7084ceaSJeremy Morse   if (SpillID.id() == 0) {
79614aaaa12SJeremy Morse     // If there is no location, and we have reached the limit of how many stack
79714aaaa12SJeremy Morse     // slots to track, then don't track this one.
79814aaaa12SJeremy Morse     if (SpillLocs.size() >= StackWorkingSetLimit)
79914aaaa12SJeremy Morse       return None;
80014aaaa12SJeremy Morse 
801e7084ceaSJeremy Morse     // Spill location is untracked: create record for this one, and all
802e7084ceaSJeremy Morse     // subregister slots too.
803e7084ceaSJeremy Morse     SpillID = SpillLocationNo(SpillLocs.insert(L));
804e7084ceaSJeremy Morse     for (unsigned StackIdx = 0; StackIdx < NumSlotIdxes; ++StackIdx) {
805e7084ceaSJeremy Morse       unsigned L = getSpillIDWithIdx(SpillID, StackIdx);
806838b4a53SJeremy Morse       LocIdx Idx = LocIdx(LocIdxToIDNum.size()); // New idx
807838b4a53SJeremy Morse       LocIdxToIDNum.grow(Idx);
808838b4a53SJeremy Morse       LocIdxToLocID.grow(Idx);
809838b4a53SJeremy Morse       LocIDToLocIdx.push_back(Idx);
810838b4a53SJeremy Morse       LocIdxToLocID[Idx] = L;
811e7084ceaSJeremy Morse       // Initialize to PHI value; corresponds to the location's live-in value
812e7084ceaSJeremy Morse       // during transfer function construction.
813e7084ceaSJeremy Morse       LocIdxToIDNum[Idx] = ValueIDNum(CurBB, 0, Idx);
814838b4a53SJeremy Morse     }
815838b4a53SJeremy Morse   }
816e7084ceaSJeremy Morse   return SpillID;
817e7084ceaSJeremy Morse }
818838b4a53SJeremy Morse 
LocIdxToName(LocIdx Idx) const819838b4a53SJeremy Morse std::string MLocTracker::LocIdxToName(LocIdx Idx) const {
820838b4a53SJeremy Morse   unsigned ID = LocIdxToLocID[Idx];
821e7084ceaSJeremy Morse   if (ID >= NumRegs) {
822e7084ceaSJeremy Morse     StackSlotPos Pos = locIDToSpillIdx(ID);
823e7084ceaSJeremy Morse     ID -= NumRegs;
824e7084ceaSJeremy Morse     unsigned Slot = ID / NumSlotIdxes;
825e7084ceaSJeremy Morse     return Twine("slot ")
826e7084ceaSJeremy Morse         .concat(Twine(Slot).concat(Twine(" sz ").concat(Twine(Pos.first)
827e7084ceaSJeremy Morse         .concat(Twine(" offs ").concat(Twine(Pos.second))))))
828e7084ceaSJeremy Morse         .str();
829e7084ceaSJeremy Morse   } else {
830838b4a53SJeremy Morse     return TRI.getRegAsmName(ID).str();
831838b4a53SJeremy Morse   }
832e7084ceaSJeremy Morse }
833838b4a53SJeremy Morse 
IDAsString(const ValueIDNum & Num) const834838b4a53SJeremy Morse std::string MLocTracker::IDAsString(const ValueIDNum &Num) const {
835838b4a53SJeremy Morse   std::string DefName = LocIdxToName(Num.getLoc());
836838b4a53SJeremy Morse   return Num.asString(DefName);
837838b4a53SJeremy Morse }
838838b4a53SJeremy Morse 
839d9fa186aSJeremy Morse #ifndef NDEBUG
dump()840838b4a53SJeremy Morse LLVM_DUMP_METHOD void MLocTracker::dump() {
841838b4a53SJeremy Morse   for (auto Location : locations()) {
842838b4a53SJeremy Morse     std::string MLocName = LocIdxToName(Location.Value.getLoc());
843838b4a53SJeremy Morse     std::string DefName = Location.Value.asString(MLocName);
844838b4a53SJeremy Morse     dbgs() << LocIdxToName(Location.Idx) << " --> " << DefName << "\n";
845838b4a53SJeremy Morse   }
846838b4a53SJeremy Morse }
847838b4a53SJeremy Morse 
dump_mloc_map()848838b4a53SJeremy Morse LLVM_DUMP_METHOD void MLocTracker::dump_mloc_map() {
849838b4a53SJeremy Morse   for (auto Location : locations()) {
850838b4a53SJeremy Morse     std::string foo = LocIdxToName(Location.Idx);
851838b4a53SJeremy Morse     dbgs() << "Idx " << Location.Idx.asU64() << " " << foo << "\n";
852838b4a53SJeremy Morse   }
853838b4a53SJeremy Morse }
854d9fa186aSJeremy Morse #endif
855838b4a53SJeremy Morse 
emitLoc(Optional<LocIdx> MLoc,const DebugVariable & Var,const DbgValueProperties & Properties)856838b4a53SJeremy Morse MachineInstrBuilder MLocTracker::emitLoc(Optional<LocIdx> MLoc,
857838b4a53SJeremy Morse                                          const DebugVariable &Var,
858838b4a53SJeremy Morse                                          const DbgValueProperties &Properties) {
859838b4a53SJeremy Morse   DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0,
860838b4a53SJeremy Morse                                 Var.getVariable()->getScope(),
861838b4a53SJeremy Morse                                 const_cast<DILocation *>(Var.getInlinedAt()));
862838b4a53SJeremy Morse   auto MIB = BuildMI(MF, DL, TII.get(TargetOpcode::DBG_VALUE));
863838b4a53SJeremy Morse 
864838b4a53SJeremy Morse   const DIExpression *Expr = Properties.DIExpr;
865838b4a53SJeremy Morse   if (!MLoc) {
866838b4a53SJeremy Morse     // No location -> DBG_VALUE $noreg
867838b4a53SJeremy Morse     MIB.addReg(0);
868838b4a53SJeremy Morse     MIB.addReg(0);
869838b4a53SJeremy Morse   } else if (LocIdxToLocID[*MLoc] >= NumRegs) {
870838b4a53SJeremy Morse     unsigned LocID = LocIdxToLocID[*MLoc];
871e7084ceaSJeremy Morse     SpillLocationNo SpillID = locIDToSpill(LocID);
872e7084ceaSJeremy Morse     StackSlotPos StackIdx = locIDToSpillIdx(LocID);
873e7084ceaSJeremy Morse     unsigned short Offset = StackIdx.second;
874838b4a53SJeremy Morse 
875e7084ceaSJeremy Morse     // TODO: support variables that are located in spill slots, with non-zero
876e7084ceaSJeremy Morse     // offsets from the start of the spill slot. It would require some more
877e7084ceaSJeremy Morse     // complex DIExpression calculations. This doesn't seem to be produced by
878e7084ceaSJeremy Morse     // LLVM right now, so don't try and support it.
879e7084ceaSJeremy Morse     // Accept no-subregister slots and subregisters where the offset is zero.
880e7084ceaSJeremy Morse     // The consumer should already have type information to work out how large
881e7084ceaSJeremy Morse     // the variable is.
882e7084ceaSJeremy Morse     if (Offset == 0) {
883e7084ceaSJeremy Morse       const SpillLoc &Spill = SpillLocs[SpillID.id()];
8844fe2ab52SZequan Wu       unsigned Base = Spill.SpillBase;
8854fe2ab52SZequan Wu       MIB.addReg(Base);
8864fe2ab52SZequan Wu 
887a975472fSJeremy Morse       // There are several ways we can dereference things, and several inputs
888a975472fSJeremy Morse       // to consider:
889a975472fSJeremy Morse       // * NRVO variables will appear with IsIndirect set, but should have
890a975472fSJeremy Morse       //   nothing else in their DIExpressions,
891a975472fSJeremy Morse       // * Variables with DW_OP_stack_value in their expr already need an
892a975472fSJeremy Morse       //   explicit dereference of the stack location,
893a975472fSJeremy Morse       // * Values that don't match the variable size need DW_OP_deref_size,
894a975472fSJeremy Morse       // * Everything else can just become a simple location expression.
895a975472fSJeremy Morse 
896a975472fSJeremy Morse       // We need to use deref_size whenever there's a mismatch between the
897a975472fSJeremy Morse       // size of value and the size of variable portion being read.
898a975472fSJeremy Morse       // Additionally, we should use it whenever dealing with stack_value
899a975472fSJeremy Morse       // fragments, to avoid the consumer having to determine the deref size
900a975472fSJeremy Morse       // from DW_OP_piece.
901a975472fSJeremy Morse       bool UseDerefSize = false;
902a975472fSJeremy Morse       unsigned ValueSizeInBits = getLocSizeInBits(*MLoc);
903a975472fSJeremy Morse       unsigned DerefSizeInBytes = ValueSizeInBits / 8;
904a975472fSJeremy Morse       if (auto Fragment = Var.getFragment()) {
905a975472fSJeremy Morse         unsigned VariableSizeInBits = Fragment->SizeInBits;
906a975472fSJeremy Morse         if (VariableSizeInBits != ValueSizeInBits || Expr->isComplex())
907a975472fSJeremy Morse           UseDerefSize = true;
908a975472fSJeremy Morse       } else if (auto Size = Var.getVariable()->getSizeInBits()) {
909a975472fSJeremy Morse         if (*Size != ValueSizeInBits) {
910a975472fSJeremy Morse           UseDerefSize = true;
911a975472fSJeremy Morse         }
912a975472fSJeremy Morse       }
913a975472fSJeremy Morse 
9144fe2ab52SZequan Wu       if (Properties.Indirect) {
915a975472fSJeremy Morse         // This is something like an NRVO variable, where the pointer has been
916a975472fSJeremy Morse         // spilt to the stack, or a dbg.addr pointing at a coroutine frame
917a975472fSJeremy Morse         // field. It should end up being a memory location, with the pointer
918a975472fSJeremy Morse         // to the variable loaded off the stack with a deref. It can't be a
919a975472fSJeremy Morse         // DW_OP_stack_value expression.
920a975472fSJeremy Morse         assert(!Expr->isImplicit());
921a975472fSJeremy Morse         Expr = TRI.prependOffsetExpression(
922a975472fSJeremy Morse             Expr, DIExpression::ApplyOffset | DIExpression::DerefAfter,
923a975472fSJeremy Morse             Spill.SpillOffset);
924a975472fSJeremy Morse         MIB.addImm(0);
925a975472fSJeremy Morse       } else if (UseDerefSize) {
926a975472fSJeremy Morse         // We're loading a value off the stack that's not the same size as the
927a975472fSJeremy Morse         // variable. Add / subtract stack offset, explicitly deref with a size,
928a975472fSJeremy Morse         // and add DW_OP_stack_value if not already present.
929a975472fSJeremy Morse         SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size,
930a975472fSJeremy Morse                                         DerefSizeInBytes};
931a975472fSJeremy Morse         Expr = DIExpression::prependOpcodes(Expr, Ops, true);
932a975472fSJeremy Morse         unsigned Flags = DIExpression::StackValue | DIExpression::ApplyOffset;
933a975472fSJeremy Morse         Expr = TRI.prependOffsetExpression(Expr, Flags, Spill.SpillOffset);
934a975472fSJeremy Morse         MIB.addReg(0);
935a975472fSJeremy Morse       } else if (Expr->isComplex()) {
936a975472fSJeremy Morse         // A variable with no size ambiguity, but with extra elements in it's
937a975472fSJeremy Morse         // expression. Manually dereference the stack location.
938a975472fSJeremy Morse         assert(Expr->isComplex());
939a975472fSJeremy Morse         Expr = TRI.prependOffsetExpression(
940a975472fSJeremy Morse             Expr, DIExpression::ApplyOffset | DIExpression::DerefAfter,
941a975472fSJeremy Morse             Spill.SpillOffset);
942a975472fSJeremy Morse         MIB.addReg(0);
943a975472fSJeremy Morse       } else {
944a975472fSJeremy Morse         // A plain value that has been spilt to the stack, with no further
945a975472fSJeremy Morse         // context. Request a location expression, marking the DBG_VALUE as
946a975472fSJeremy Morse         // IsIndirect.
947a975472fSJeremy Morse         Expr = TRI.prependOffsetExpression(Expr, DIExpression::ApplyOffset,
948a975472fSJeremy Morse                                            Spill.SpillOffset);
949a975472fSJeremy Morse         MIB.addImm(0);
950536b9eb3SJeremy Morse       }
951838b4a53SJeremy Morse     } else {
952e7084ceaSJeremy Morse       // This is a stack location with a weird subregister offset: emit an undef
953e7084ceaSJeremy Morse       // DBG_VALUE instead.
954e7084ceaSJeremy Morse       MIB.addReg(0);
955e7084ceaSJeremy Morse       MIB.addReg(0);
956e7084ceaSJeremy Morse     }
957e7084ceaSJeremy Morse   } else {
958e7084ceaSJeremy Morse     // Non-empty, non-stack slot, must be a plain register.
959838b4a53SJeremy Morse     unsigned LocID = LocIdxToLocID[*MLoc];
960838b4a53SJeremy Morse     MIB.addReg(LocID);
961838b4a53SJeremy Morse     if (Properties.Indirect)
962838b4a53SJeremy Morse       MIB.addImm(0);
963838b4a53SJeremy Morse     else
964838b4a53SJeremy Morse       MIB.addReg(0);
965838b4a53SJeremy Morse   }
966838b4a53SJeremy Morse 
967838b4a53SJeremy Morse   MIB.addMetadata(Var.getVariable());
968838b4a53SJeremy Morse   MIB.addMetadata(Expr);
969838b4a53SJeremy Morse   return MIB;
970838b4a53SJeremy Morse }
971838b4a53SJeremy Morse 
972ae6f7882SJeremy Morse /// Default construct and initialize the pass.
9733a8c5148SKazu Hirata InstrRefBasedLDV::InstrRefBasedLDV() = default;
974ae6f7882SJeremy Morse 
isCalleeSaved(LocIdx L) const975838b4a53SJeremy Morse bool InstrRefBasedLDV::isCalleeSaved(LocIdx L) const {
976838b4a53SJeremy Morse   unsigned Reg = MTracker->LocIdxToLocID[L];
977838b4a53SJeremy Morse   for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
978838b4a53SJeremy Morse     if (CalleeSavedRegs.test(*RAI))
979838b4a53SJeremy Morse       return true;
980838b4a53SJeremy Morse   return false;
981838b4a53SJeremy Morse }
982838b4a53SJeremy Morse 
983ae6f7882SJeremy Morse //===----------------------------------------------------------------------===//
984ae6f7882SJeremy Morse //            Debug Range Extension Implementation
985ae6f7882SJeremy Morse //===----------------------------------------------------------------------===//
986ae6f7882SJeremy Morse 
987ae6f7882SJeremy Morse #ifndef NDEBUG
988ae6f7882SJeremy Morse // Something to restore in the future.
989ae6f7882SJeremy Morse // void InstrRefBasedLDV::printVarLocInMBB(..)
990ae6f7882SJeremy Morse #endif
991ae6f7882SJeremy Morse 
99214aaaa12SJeremy Morse Optional<SpillLocationNo>
extractSpillBaseRegAndOffset(const MachineInstr & MI)993ae6f7882SJeremy Morse InstrRefBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
994ae6f7882SJeremy Morse   assert(MI.hasOneMemOperand() &&
995ae6f7882SJeremy Morse          "Spill instruction does not have exactly one memory operand?");
996ae6f7882SJeremy Morse   auto MMOI = MI.memoperands_begin();
997ae6f7882SJeremy Morse   const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
998ae6f7882SJeremy Morse   assert(PVal->kind() == PseudoSourceValue::FixedStack &&
999ae6f7882SJeremy Morse          "Inconsistent memory operand in spill instruction");
1000ae6f7882SJeremy Morse   int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
1001ae6f7882SJeremy Morse   const MachineBasicBlock *MBB = MI.getParent();
1002ae6f7882SJeremy Morse   Register Reg;
1003d57bba7cSSander de Smalen   StackOffset Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
1004e7084ceaSJeremy Morse   return MTracker->getOrTrackSpillLoc({Reg, Offset});
1005ae6f7882SJeremy Morse }
1006ae6f7882SJeremy Morse 
100714aaaa12SJeremy Morse Optional<LocIdx>
findLocationForMemOperand(const MachineInstr & MI)100814aaaa12SJeremy Morse InstrRefBasedLDV::findLocationForMemOperand(const MachineInstr &MI) {
100914aaaa12SJeremy Morse   Optional<SpillLocationNo> SpillLoc = extractSpillBaseRegAndOffset(MI);
101014aaaa12SJeremy Morse   if (!SpillLoc)
101114aaaa12SJeremy Morse     return None;
1012ee3eee71SJeremy Morse 
1013ee3eee71SJeremy Morse   // Where in the stack slot is this value defined -- i.e., what size of value
1014ee3eee71SJeremy Morse   // is this? An important question, because it could be loaded into a register
1015ee3eee71SJeremy Morse   // from the stack at some point. Happily the memory operand will tell us
1016ee3eee71SJeremy Morse   // the size written to the stack.
1017ee3eee71SJeremy Morse   auto *MemOperand = *MI.memoperands_begin();
1018ee3eee71SJeremy Morse   unsigned SizeInBits = MemOperand->getSizeInBits();
1019ee3eee71SJeremy Morse 
1020ee3eee71SJeremy Morse   // Find that position in the stack indexes we're tracking.
1021ee3eee71SJeremy Morse   auto IdxIt = MTracker->StackSlotIdxes.find({SizeInBits, 0});
1022ee3eee71SJeremy Morse   if (IdxIt == MTracker->StackSlotIdxes.end())
1023ee3eee71SJeremy Morse     // That index is not tracked. This is suprising, and unlikely to ever
1024ee3eee71SJeremy Morse     // occur, but the safe action is to indicate the variable is optimised out.
1025ee3eee71SJeremy Morse     return None;
1026ee3eee71SJeremy Morse 
102714aaaa12SJeremy Morse   unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillLoc, IdxIt->second);
1028ee3eee71SJeremy Morse   return MTracker->getSpillMLoc(SpillID);
1029ee3eee71SJeremy Morse }
1030ee3eee71SJeremy Morse 
1031ae6f7882SJeremy Morse /// End all previous ranges related to @MI and start a new range from @MI
1032ae6f7882SJeremy Morse /// if it is a DBG_VALUE instr.
transferDebugValue(const MachineInstr & MI)1033ae6f7882SJeremy Morse bool InstrRefBasedLDV::transferDebugValue(const MachineInstr &MI) {
1034ae6f7882SJeremy Morse   if (!MI.isDebugValue())
1035ae6f7882SJeremy Morse     return false;
1036ae6f7882SJeremy Morse 
1037ae6f7882SJeremy Morse   const DILocalVariable *Var = MI.getDebugVariable();
1038ae6f7882SJeremy Morse   const DIExpression *Expr = MI.getDebugExpression();
1039ae6f7882SJeremy Morse   const DILocation *DebugLoc = MI.getDebugLoc();
1040ae6f7882SJeremy Morse   const DILocation *InlinedAt = DebugLoc->getInlinedAt();
1041ae6f7882SJeremy Morse   assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
1042ae6f7882SJeremy Morse          "Expected inlined-at fields to agree");
1043ae6f7882SJeremy Morse 
1044ae6f7882SJeremy Morse   DebugVariable V(Var, Expr, InlinedAt);
104568f47157SJeremy Morse   DbgValueProperties Properties(MI);
1046ae6f7882SJeremy Morse 
1047ae6f7882SJeremy Morse   // If there are no instructions in this lexical scope, do no location tracking
1048ae6f7882SJeremy Morse   // at all, this variable shouldn't get a legitimate location range.
1049ae6f7882SJeremy Morse   auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
1050ae6f7882SJeremy Morse   if (Scope == nullptr)
1051ae6f7882SJeremy Morse     return true; // handled it; by doing nothing
1052ae6f7882SJeremy Morse 
1053ce8254d0SJeremy Morse   // For now, ignore DBG_VALUE_LISTs when extending ranges. Allow it to
1054ce8254d0SJeremy Morse   // contribute to locations in this block, but don't propagate further.
1055ce8254d0SJeremy Morse   // Interpret it like a DBG_VALUE $noreg.
1056ce8254d0SJeremy Morse   if (MI.isDebugValueList()) {
1057ce8254d0SJeremy Morse     if (VTracker)
1058ce8254d0SJeremy Morse       VTracker->defVar(MI, Properties, None);
1059ce8254d0SJeremy Morse     if (TTracker)
1060ce8254d0SJeremy Morse       TTracker->redefVar(MI, Properties, None);
1061ce8254d0SJeremy Morse     return true;
1062ce8254d0SJeremy Morse   }
1063ce8254d0SJeremy Morse 
1064ae6f7882SJeremy Morse   const MachineOperand &MO = MI.getOperand(0);
1065ae6f7882SJeremy Morse 
1066ae6f7882SJeremy Morse   // MLocTracker needs to know that this register is read, even if it's only
1067ae6f7882SJeremy Morse   // read by a debug inst.
1068ae6f7882SJeremy Morse   if (MO.isReg() && MO.getReg() != 0)
1069ae6f7882SJeremy Morse     (void)MTracker->readReg(MO.getReg());
1070ae6f7882SJeremy Morse 
1071ae6f7882SJeremy Morse   // If we're preparing for the second analysis (variables), the machine value
1072ae6f7882SJeremy Morse   // locations are already solved, and we report this DBG_VALUE and the value
1073ae6f7882SJeremy Morse   // it refers to to VLocTracker.
1074ae6f7882SJeremy Morse   if (VTracker) {
1075ae6f7882SJeremy Morse     if (MO.isReg()) {
1076ae6f7882SJeremy Morse       // Feed defVar the new variable location, or if this is a
1077ae6f7882SJeremy Morse       // DBG_VALUE $noreg, feed defVar None.
1078ae6f7882SJeremy Morse       if (MO.getReg())
107968f47157SJeremy Morse         VTracker->defVar(MI, Properties, MTracker->readReg(MO.getReg()));
1080ae6f7882SJeremy Morse       else
108168f47157SJeremy Morse         VTracker->defVar(MI, Properties, None);
1082ae6f7882SJeremy Morse     } else if (MI.getOperand(0).isImm() || MI.getOperand(0).isFPImm() ||
1083ae6f7882SJeremy Morse                MI.getOperand(0).isCImm()) {
1084ae6f7882SJeremy Morse       VTracker->defVar(MI, MI.getOperand(0));
1085ae6f7882SJeremy Morse     }
1086ae6f7882SJeremy Morse   }
1087ae6f7882SJeremy Morse 
1088ae6f7882SJeremy Morse   // If performing final tracking of transfers, report this variable definition
1089ae6f7882SJeremy Morse   // to the TransferTracker too.
1090ae6f7882SJeremy Morse   if (TTracker)
1091ae6f7882SJeremy Morse     TTracker->redefVar(MI);
1092ae6f7882SJeremy Morse   return true;
1093ae6f7882SJeremy Morse }
1094ae6f7882SJeremy Morse 
transferDebugInstrRef(MachineInstr & MI,const ValueTable * MLiveOuts,const ValueTable * MLiveIns)1095010108bbSJeremy Morse bool InstrRefBasedLDV::transferDebugInstrRef(MachineInstr &MI,
1096ab49dce0SJeremy Morse                                              const ValueTable *MLiveOuts,
1097ab49dce0SJeremy Morse                                              const ValueTable *MLiveIns) {
109868f47157SJeremy Morse   if (!MI.isDebugRef())
109968f47157SJeremy Morse     return false;
110068f47157SJeremy Morse 
110168f47157SJeremy Morse   // Only handle this instruction when we are building the variable value
110268f47157SJeremy Morse   // transfer function.
1103a80181a8SJeremy Morse   if (!VTracker && !TTracker)
110468f47157SJeremy Morse     return false;
110568f47157SJeremy Morse 
110668f47157SJeremy Morse   unsigned InstNo = MI.getOperand(0).getImm();
110768f47157SJeremy Morse   unsigned OpNo = MI.getOperand(1).getImm();
110868f47157SJeremy Morse 
110968f47157SJeremy Morse   const DILocalVariable *Var = MI.getDebugVariable();
111068f47157SJeremy Morse   const DIExpression *Expr = MI.getDebugExpression();
111168f47157SJeremy Morse   const DILocation *DebugLoc = MI.getDebugLoc();
111268f47157SJeremy Morse   const DILocation *InlinedAt = DebugLoc->getInlinedAt();
111368f47157SJeremy Morse   assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
111468f47157SJeremy Morse          "Expected inlined-at fields to agree");
111568f47157SJeremy Morse 
111668f47157SJeremy Morse   DebugVariable V(Var, Expr, InlinedAt);
111768f47157SJeremy Morse 
111868f47157SJeremy Morse   auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
111968f47157SJeremy Morse   if (Scope == nullptr)
112068f47157SJeremy Morse     return true; // Handled by doing nothing. This variable is never in scope.
112168f47157SJeremy Morse 
112268f47157SJeremy Morse   const MachineFunction &MF = *MI.getParent()->getParent();
112368f47157SJeremy Morse 
112468f47157SJeremy Morse   // Various optimizations may have happened to the value during codegen,
112568f47157SJeremy Morse   // recorded in the value substitution table. Apply any substitutions to
1126f551fb96SJeremy Morse   // the instruction / operand number in this DBG_INSTR_REF, and collect
1127f551fb96SJeremy Morse   // any subregister extractions performed during optimization.
1128f551fb96SJeremy Morse 
1129f551fb96SJeremy Morse   // Create dummy substitution with Src set, for lookup.
1130f551fb96SJeremy Morse   auto SoughtSub =
1131f551fb96SJeremy Morse       MachineFunction::DebugSubstitution({InstNo, OpNo}, {0, 0}, 0);
1132f551fb96SJeremy Morse 
1133e9641c91SJeremy Morse   SmallVector<unsigned, 4> SeenSubregs;
1134f551fb96SJeremy Morse   auto LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub);
1135f551fb96SJeremy Morse   while (LowerBoundIt != MF.DebugValueSubstitutions.end() &&
1136f551fb96SJeremy Morse          LowerBoundIt->Src == SoughtSub.Src) {
1137f551fb96SJeremy Morse     std::tie(InstNo, OpNo) = LowerBoundIt->Dest;
1138f551fb96SJeremy Morse     SoughtSub.Src = LowerBoundIt->Dest;
1139f551fb96SJeremy Morse     if (unsigned Subreg = LowerBoundIt->Subreg)
1140e9641c91SJeremy Morse       SeenSubregs.push_back(Subreg);
1141f551fb96SJeremy Morse     LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub);
114268f47157SJeremy Morse   }
114368f47157SJeremy Morse 
114468f47157SJeremy Morse   // Default machine value number is <None> -- if no instruction defines
114568f47157SJeremy Morse   // the corresponding value, it must have been optimized out.
114668f47157SJeremy Morse   Optional<ValueIDNum> NewID = None;
114768f47157SJeremy Morse 
114868f47157SJeremy Morse   // Try to lookup the instruction number, and find the machine value number
1149010108bbSJeremy Morse   // that it defines. It could be an instruction, or a PHI.
115068f47157SJeremy Morse   auto InstrIt = DebugInstrNumToInstr.find(InstNo);
1151010108bbSJeremy Morse   auto PHIIt = std::lower_bound(DebugPHINumToValue.begin(),
1152010108bbSJeremy Morse                                 DebugPHINumToValue.end(), InstNo);
115368f47157SJeremy Morse   if (InstrIt != DebugInstrNumToInstr.end()) {
115468f47157SJeremy Morse     const MachineInstr &TargetInstr = *InstrIt->second.first;
115568f47157SJeremy Morse     uint64_t BlockNo = TargetInstr.getParent()->getNumber();
115668f47157SJeremy Morse 
1157ee3eee71SJeremy Morse     // Pick out the designated operand. It might be a memory reference, if
1158ee3eee71SJeremy Morse     // a register def was folded into a stack store.
1159ee3eee71SJeremy Morse     if (OpNo == MachineFunction::DebugOperandMemNumber &&
1160ee3eee71SJeremy Morse         TargetInstr.hasOneMemOperand()) {
1161ee3eee71SJeremy Morse       Optional<LocIdx> L = findLocationForMemOperand(TargetInstr);
1162ee3eee71SJeremy Morse       if (L)
1163ee3eee71SJeremy Morse         NewID = ValueIDNum(BlockNo, InstrIt->second.second, *L);
1164ee3eee71SJeremy Morse     } else if (OpNo != MachineFunction::DebugOperandMemNumber) {
1165be5734ddSJeremy Morse       // Permit the debug-info to be completely wrong: identifying a nonexistant
1166be5734ddSJeremy Morse       // operand, or one that is not a register definition, means something
1167be5734ddSJeremy Morse       // unexpected happened during optimisation. Broken debug-info, however,
1168be5734ddSJeremy Morse       // shouldn't crash the compiler -- instead leave the variable value as
1169be5734ddSJeremy Morse       // None, which will make it appear "optimised out".
1170be5734ddSJeremy Morse       if (OpNo < TargetInstr.getNumOperands()) {
117168f47157SJeremy Morse         const MachineOperand &MO = TargetInstr.getOperand(OpNo);
117268f47157SJeremy Morse 
1173be5734ddSJeremy Morse         if (MO.isReg() && MO.isDef() && MO.getReg()) {
1174e7084ceaSJeremy Morse           unsigned LocID = MTracker->getLocID(MO.getReg());
117568f47157SJeremy Morse           LocIdx L = MTracker->LocIDToLocIdx[LocID];
117668f47157SJeremy Morse           NewID = ValueIDNum(BlockNo, InstrIt->second.second, L);
1177ee3eee71SJeremy Morse         }
1178be5734ddSJeremy Morse       }
1179be5734ddSJeremy Morse 
1180be5734ddSJeremy Morse       if (!NewID) {
1181be5734ddSJeremy Morse         LLVM_DEBUG(
1182be5734ddSJeremy Morse             { dbgs() << "Seen instruction reference to illegal operand\n"; });
1183be5734ddSJeremy Morse       }
1184be5734ddSJeremy Morse     }
1185ee3eee71SJeremy Morse     // else: NewID is left as None.
1186010108bbSJeremy Morse   } else if (PHIIt != DebugPHINumToValue.end() && PHIIt->InstrNum == InstNo) {
1187010108bbSJeremy Morse     // It's actually a PHI value. Which value it is might not be obvious, use
1188010108bbSJeremy Morse     // the resolver helper to find out.
1189010108bbSJeremy Morse     NewID = resolveDbgPHIs(*MI.getParent()->getParent(), MLiveOuts, MLiveIns,
1190010108bbSJeremy Morse                            MI, InstNo);
119168f47157SJeremy Morse   }
119268f47157SJeremy Morse 
1193e9641c91SJeremy Morse   // Apply any subregister extractions, in reverse. We might have seen code
1194e9641c91SJeremy Morse   // like this:
1195e9641c91SJeremy Morse   //    CALL64 @foo, implicit-def $rax
1196e9641c91SJeremy Morse   //    %0:gr64 = COPY $rax
1197e9641c91SJeremy Morse   //    %1:gr32 = COPY %0.sub_32bit
1198e9641c91SJeremy Morse   //    %2:gr16 = COPY %1.sub_16bit
1199e9641c91SJeremy Morse   //    %3:gr8  = COPY %2.sub_8bit
1200e9641c91SJeremy Morse   // In which case each copy would have been recorded as a substitution with
1201e9641c91SJeremy Morse   // a subregister qualifier. Apply those qualifiers now.
1202e9641c91SJeremy Morse   if (NewID && !SeenSubregs.empty()) {
1203e9641c91SJeremy Morse     unsigned Offset = 0;
1204e9641c91SJeremy Morse     unsigned Size = 0;
1205e9641c91SJeremy Morse 
1206e9641c91SJeremy Morse     // Look at each subregister that we passed through, and progressively
1207e9641c91SJeremy Morse     // narrow in, accumulating any offsets that occur. Substitutions should
1208e9641c91SJeremy Morse     // only ever be the same or narrower width than what they read from;
1209e9641c91SJeremy Morse     // iterate in reverse order so that we go from wide to small.
1210e9641c91SJeremy Morse     for (unsigned Subreg : reverse(SeenSubregs)) {
1211e9641c91SJeremy Morse       unsigned ThisSize = TRI->getSubRegIdxSize(Subreg);
1212e9641c91SJeremy Morse       unsigned ThisOffset = TRI->getSubRegIdxOffset(Subreg);
1213e9641c91SJeremy Morse       Offset += ThisOffset;
1214e9641c91SJeremy Morse       Size = (Size == 0) ? ThisSize : std::min(Size, ThisSize);
1215e9641c91SJeremy Morse     }
1216e9641c91SJeremy Morse 
1217e9641c91SJeremy Morse     // If that worked, look for an appropriate subregister with the register
1218e9641c91SJeremy Morse     // where the define happens. Don't look at values that were defined during
1219e9641c91SJeremy Morse     // a stack write: we can't currently express register locations within
1220e9641c91SJeremy Morse     // spills.
1221e9641c91SJeremy Morse     LocIdx L = NewID->getLoc();
1222e9641c91SJeremy Morse     if (NewID && !MTracker->isSpill(L)) {
1223e9641c91SJeremy Morse       // Find the register class for the register where this def happened.
1224e9641c91SJeremy Morse       // FIXME: no index for this?
1225e9641c91SJeremy Morse       Register Reg = MTracker->LocIdxToLocID[L];
1226e9641c91SJeremy Morse       const TargetRegisterClass *TRC = nullptr;
12279e6d1f4bSKazu Hirata       for (const auto *TRCI : TRI->regclasses())
1228e9641c91SJeremy Morse         if (TRCI->contains(Reg))
1229e9641c91SJeremy Morse           TRC = TRCI;
1230e9641c91SJeremy Morse       assert(TRC && "Couldn't find target register class?");
1231e9641c91SJeremy Morse 
1232e9641c91SJeremy Morse       // If the register we have isn't the right size or in the right place,
1233e9641c91SJeremy Morse       // Try to find a subregister inside it.
1234e9641c91SJeremy Morse       unsigned MainRegSize = TRI->getRegSizeInBits(*TRC);
1235e9641c91SJeremy Morse       if (Size != MainRegSize || Offset) {
1236e9641c91SJeremy Morse         // Enumerate all subregisters, searching.
1237e9641c91SJeremy Morse         Register NewReg = 0;
1238e9641c91SJeremy Morse         for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) {
1239e9641c91SJeremy Morse           unsigned Subreg = TRI->getSubRegIndex(Reg, *SRI);
1240e9641c91SJeremy Morse           unsigned SubregSize = TRI->getSubRegIdxSize(Subreg);
1241e9641c91SJeremy Morse           unsigned SubregOffset = TRI->getSubRegIdxOffset(Subreg);
1242e9641c91SJeremy Morse           if (SubregSize == Size && SubregOffset == Offset) {
1243e9641c91SJeremy Morse             NewReg = *SRI;
1244e9641c91SJeremy Morse             break;
1245e9641c91SJeremy Morse           }
1246e9641c91SJeremy Morse         }
1247e9641c91SJeremy Morse 
1248e9641c91SJeremy Morse         // If we didn't find anything: there's no way to express our value.
1249e9641c91SJeremy Morse         if (!NewReg) {
1250e9641c91SJeremy Morse           NewID = None;
1251e9641c91SJeremy Morse         } else {
1252e9641c91SJeremy Morse           // Re-state the value as being defined within the subregister
1253e9641c91SJeremy Morse           // that we found.
1254e9641c91SJeremy Morse           LocIdx NewLoc = MTracker->lookupOrTrackRegister(NewReg);
1255e9641c91SJeremy Morse           NewID = ValueIDNum(NewID->getBlock(), NewID->getInst(), NewLoc);
1256e9641c91SJeremy Morse         }
1257e9641c91SJeremy Morse       }
1258e9641c91SJeremy Morse     } else {
1259e9641c91SJeremy Morse       // If we can't handle subregisters, unset the new value.
1260e9641c91SJeremy Morse       NewID = None;
1261e9641c91SJeremy Morse     }
1262e9641c91SJeremy Morse   }
1263e9641c91SJeremy Morse 
126468f47157SJeremy Morse   // We, we have a value number or None. Tell the variable value tracker about
126568f47157SJeremy Morse   // it. The rest of this LiveDebugValues implementation acts exactly the same
126668f47157SJeremy Morse   // for DBG_INSTR_REFs as DBG_VALUEs (just, the former can refer to values that
126768f47157SJeremy Morse   // aren't immediately available).
126868f47157SJeremy Morse   DbgValueProperties Properties(Expr, false);
1269a80181a8SJeremy Morse   if (VTracker)
127068f47157SJeremy Morse     VTracker->defVar(MI, Properties, NewID);
127168f47157SJeremy Morse 
127268f47157SJeremy Morse   // If we're on the final pass through the function, decompose this INSTR_REF
127368f47157SJeremy Morse   // into a plain DBG_VALUE.
127468f47157SJeremy Morse   if (!TTracker)
127568f47157SJeremy Morse     return true;
127668f47157SJeremy Morse 
127768f47157SJeremy Morse   // Pick a location for the machine value number, if such a location exists.
127868f47157SJeremy Morse   // (This information could be stored in TransferTracker to make it faster).
127968f47157SJeremy Morse   Optional<LocIdx> FoundLoc = None;
128068f47157SJeremy Morse   for (auto Location : MTracker->locations()) {
128168f47157SJeremy Morse     LocIdx CurL = Location.Idx;
1282d9eebe3cSJeremy Morse     ValueIDNum ID = MTracker->readMLoc(CurL);
128368f47157SJeremy Morse     if (NewID && ID == NewID) {
128468f47157SJeremy Morse       // If this is the first location with that value, pick it. Otherwise,
128568f47157SJeremy Morse       // consider whether it's a "longer term" location.
128668f47157SJeremy Morse       if (!FoundLoc) {
128768f47157SJeremy Morse         FoundLoc = CurL;
128868f47157SJeremy Morse         continue;
128968f47157SJeremy Morse       }
129068f47157SJeremy Morse 
129168f47157SJeremy Morse       if (MTracker->isSpill(CurL))
129268f47157SJeremy Morse         FoundLoc = CurL; // Spills are a longer term location.
129368f47157SJeremy Morse       else if (!MTracker->isSpill(*FoundLoc) &&
129468f47157SJeremy Morse                !MTracker->isSpill(CurL) &&
129568f47157SJeremy Morse                !isCalleeSaved(*FoundLoc) &&
129668f47157SJeremy Morse                isCalleeSaved(CurL))
129768f47157SJeremy Morse         FoundLoc = CurL; // Callee saved regs are longer term than normal.
129868f47157SJeremy Morse     }
129968f47157SJeremy Morse   }
130068f47157SJeremy Morse 
130168f47157SJeremy Morse   // Tell transfer tracker that the variable value has changed.
130268f47157SJeremy Morse   TTracker->redefVar(MI, Properties, FoundLoc);
130368f47157SJeremy Morse 
1304b1b2c6abSJeremy Morse   // If there was a value with no location; but the value is defined in a
1305b1b2c6abSJeremy Morse   // later instruction in this block, this is a block-local use-before-def.
1306b1b2c6abSJeremy Morse   if (!FoundLoc && NewID && NewID->getBlock() == CurBB &&
1307b1b2c6abSJeremy Morse       NewID->getInst() > CurInst)
1308b1b2c6abSJeremy Morse     TTracker->addUseBeforeDef(V, {MI.getDebugExpression(), false}, *NewID);
1309b1b2c6abSJeremy Morse 
131068f47157SJeremy Morse   // Produce a DBG_VALUE representing what this DBG_INSTR_REF meant.
131168f47157SJeremy Morse   // This DBG_VALUE is potentially a $noreg / undefined location, if
131268f47157SJeremy Morse   // FoundLoc is None.
131368f47157SJeremy Morse   // (XXX -- could morph the DBG_INSTR_REF in the future).
131468f47157SJeremy Morse   MachineInstr *DbgMI = MTracker->emitLoc(FoundLoc, V, Properties);
131568f47157SJeremy Morse   TTracker->PendingDbgValues.push_back(DbgMI);
131668f47157SJeremy Morse   TTracker->flushDbgValues(MI.getIterator(), nullptr);
1317010108bbSJeremy Morse   return true;
1318010108bbSJeremy Morse }
1319010108bbSJeremy Morse 
transferDebugPHI(MachineInstr & MI)1320010108bbSJeremy Morse bool InstrRefBasedLDV::transferDebugPHI(MachineInstr &MI) {
1321010108bbSJeremy Morse   if (!MI.isDebugPHI())
1322010108bbSJeremy Morse     return false;
1323010108bbSJeremy Morse 
1324010108bbSJeremy Morse   // Analyse these only when solving the machine value location problem.
1325010108bbSJeremy Morse   if (VTracker || TTracker)
1326010108bbSJeremy Morse     return true;
1327010108bbSJeremy Morse 
1328010108bbSJeremy Morse   // First operand is the value location, either a stack slot or register.
1329010108bbSJeremy Morse   // Second is the debug instruction number of the original PHI.
1330010108bbSJeremy Morse   const MachineOperand &MO = MI.getOperand(0);
1331010108bbSJeremy Morse   unsigned InstrNum = MI.getOperand(1).getImm();
1332010108bbSJeremy Morse 
1333ea29810cSKazu Hirata   auto EmitBadPHI = [this, &MI, InstrNum]() -> bool {
1334be5734ddSJeremy Morse     // Helper lambda to do any accounting when we fail to find a location for
1335be5734ddSJeremy Morse     // a DBG_PHI. This can happen if DBG_PHIs are malformed, or refer to a
1336be5734ddSJeremy Morse     // dead stack slot, for example.
1337be5734ddSJeremy Morse     // Record a DebugPHIRecord with an empty value + location.
1338be5734ddSJeremy Morse     DebugPHINumToValue.push_back({InstrNum, MI.getParent(), None, None});
1339be5734ddSJeremy Morse     return true;
1340be5734ddSJeremy Morse   };
1341be5734ddSJeremy Morse 
1342be5734ddSJeremy Morse   if (MO.isReg() && MO.getReg()) {
1343010108bbSJeremy Morse     // The value is whatever's currently in the register. Read and record it,
1344010108bbSJeremy Morse     // to be analysed later.
1345010108bbSJeremy Morse     Register Reg = MO.getReg();
1346010108bbSJeremy Morse     ValueIDNum Num = MTracker->readReg(Reg);
1347010108bbSJeremy Morse     auto PHIRec = DebugPHIRecord(
1348010108bbSJeremy Morse         {InstrNum, MI.getParent(), Num, MTracker->lookupOrTrackRegister(Reg)});
1349010108bbSJeremy Morse     DebugPHINumToValue.push_back(PHIRec);
1350e265644bSJeremy Morse 
1351e7084ceaSJeremy Morse     // Ensure this register is tracked.
1352e265644bSJeremy Morse     for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1353e265644bSJeremy Morse       MTracker->lookupOrTrackRegister(*RAI);
1354be5734ddSJeremy Morse   } else if (MO.isFI()) {
1355010108bbSJeremy Morse     // The value is whatever's in this stack slot.
1356010108bbSJeremy Morse     unsigned FI = MO.getIndex();
1357010108bbSJeremy Morse 
1358010108bbSJeremy Morse     // If the stack slot is dead, then this was optimized away.
1359010108bbSJeremy Morse     // FIXME: stack slot colouring should account for slots that get merged.
1360010108bbSJeremy Morse     if (MFI->isDeadObjectIndex(FI))
1361be5734ddSJeremy Morse       return EmitBadPHI();
1362010108bbSJeremy Morse 
1363e7084ceaSJeremy Morse     // Identify this spill slot, ensure it's tracked.
1364010108bbSJeremy Morse     Register Base;
1365010108bbSJeremy Morse     StackOffset Offs = TFI->getFrameIndexReference(*MI.getMF(), FI, Base);
1366010108bbSJeremy Morse     SpillLoc SL = {Base, Offs};
136714aaaa12SJeremy Morse     Optional<SpillLocationNo> SpillNo = MTracker->getOrTrackSpillLoc(SL);
136814aaaa12SJeremy Morse 
136914aaaa12SJeremy Morse     // We might be able to find a value, but have chosen not to, to avoid
137014aaaa12SJeremy Morse     // tracking too much stack information.
137114aaaa12SJeremy Morse     if (!SpillNo)
1372be5734ddSJeremy Morse       return EmitBadPHI();
1373010108bbSJeremy Morse 
137465d5becaSJeremy Morse     // Any stack location DBG_PHI should have an associate bit-size.
137565d5becaSJeremy Morse     assert(MI.getNumOperands() == 3 && "Stack DBG_PHI with no size?");
137665d5becaSJeremy Morse     unsigned slotBitSize = MI.getOperand(2).getImm();
1377e7084ceaSJeremy Morse 
137865d5becaSJeremy Morse     unsigned SpillID = MTracker->getLocID(*SpillNo, {slotBitSize, 0});
137965d5becaSJeremy Morse     LocIdx SpillLoc = MTracker->getSpillMLoc(SpillID);
138065d5becaSJeremy Morse     ValueIDNum Result = MTracker->readMLoc(SpillLoc);
1381010108bbSJeremy Morse 
1382010108bbSJeremy Morse     // Record this DBG_PHI for later analysis.
138365d5becaSJeremy Morse     auto DbgPHI = DebugPHIRecord({InstrNum, MI.getParent(), Result, SpillLoc});
1384010108bbSJeremy Morse     DebugPHINumToValue.push_back(DbgPHI);
1385be5734ddSJeremy Morse   } else {
1386be5734ddSJeremy Morse     // Else: if the operand is neither a legal register or a stack slot, then
1387be5734ddSJeremy Morse     // we're being fed illegal debug-info. Record an empty PHI, so that any
1388be5734ddSJeremy Morse     // debug users trying to read this number will be put off trying to
1389be5734ddSJeremy Morse     // interpret the value.
1390be5734ddSJeremy Morse     LLVM_DEBUG(
1391be5734ddSJeremy Morse         { dbgs() << "Seen DBG_PHI with unrecognised operand format\n"; });
1392be5734ddSJeremy Morse     return EmitBadPHI();
1393010108bbSJeremy Morse   }
139468f47157SJeremy Morse 
139568f47157SJeremy Morse   return true;
139668f47157SJeremy Morse }
139768f47157SJeremy Morse 
transferRegisterDef(MachineInstr & MI)1398ae6f7882SJeremy Morse void InstrRefBasedLDV::transferRegisterDef(MachineInstr &MI) {
1399ae6f7882SJeremy Morse   // Meta Instructions do not affect the debug liveness of any register they
1400ae6f7882SJeremy Morse   // define.
1401ae6f7882SJeremy Morse   if (MI.isImplicitDef()) {
1402ae6f7882SJeremy Morse     // Except when there's an implicit def, and the location it's defining has
1403ae6f7882SJeremy Morse     // no value number. The whole point of an implicit def is to announce that
1404ae6f7882SJeremy Morse     // the register is live, without be specific about it's value. So define
1405ae6f7882SJeremy Morse     // a value if there isn't one already.
1406ae6f7882SJeremy Morse     ValueIDNum Num = MTracker->readReg(MI.getOperand(0).getReg());
1407ae6f7882SJeremy Morse     // Has a legitimate value -> ignore the implicit def.
1408ae6f7882SJeremy Morse     if (Num.getLoc() != 0)
1409ae6f7882SJeremy Morse       return;
1410ae6f7882SJeremy Morse     // Otherwise, def it here.
1411ae6f7882SJeremy Morse   } else if (MI.isMetaInstruction())
1412ae6f7882SJeremy Morse     return;
1413ae6f7882SJeremy Morse 
1414bfadc5dcSJeremy Morse   // We always ignore SP defines on call instructions, they don't actually
1415bfadc5dcSJeremy Morse   // change the value of the stack pointer... except for win32's _chkstk. This
1416bfadc5dcSJeremy Morse   // is rare: filter quickly for the common case (no stack adjustments, not a
1417bfadc5dcSJeremy Morse   // call, etc). If it is a call that modifies SP, recognise the SP register
1418bfadc5dcSJeremy Morse   // defs.
1419bfadc5dcSJeremy Morse   bool CallChangesSP = false;
1420bfadc5dcSJeremy Morse   if (AdjustsStackInCalls && MI.isCall() && MI.getOperand(0).isSymbol() &&
1421bfadc5dcSJeremy Morse       !strcmp(MI.getOperand(0).getSymbolName(), StackProbeSymbolName.data()))
1422bfadc5dcSJeremy Morse     CallChangesSP = true;
1423bfadc5dcSJeremy Morse 
1424bfadc5dcSJeremy Morse   // Test whether we should ignore a def of this register due to it being part
1425bfadc5dcSJeremy Morse   // of the stack pointer.
1426bfadc5dcSJeremy Morse   auto IgnoreSPAlias = [this, &MI, CallChangesSP](Register R) -> bool {
1427bfadc5dcSJeremy Morse     if (CallChangesSP)
1428bfadc5dcSJeremy Morse       return false;
1429133e25f9SJeremy Morse     return MI.isCall() && MTracker->SPAliases.count(R);
1430133e25f9SJeremy Morse   };
1431133e25f9SJeremy Morse 
1432ae6f7882SJeremy Morse   // Find the regs killed by MI, and find regmasks of preserved regs.
1433ae6f7882SJeremy Morse   // Max out the number of statically allocated elements in `DeadRegs`, as this
1434ae6f7882SJeremy Morse   // prevents fallback to std::set::count() operations.
1435ae6f7882SJeremy Morse   SmallSet<uint32_t, 32> DeadRegs;
1436ae6f7882SJeremy Morse   SmallVector<const uint32_t *, 4> RegMasks;
1437ae6f7882SJeremy Morse   SmallVector<const MachineOperand *, 4> RegMaskPtrs;
1438ae6f7882SJeremy Morse   for (const MachineOperand &MO : MI.operands()) {
1439ae6f7882SJeremy Morse     // Determine whether the operand is a register def.
1440ae6f7882SJeremy Morse     if (MO.isReg() && MO.isDef() && MO.getReg() &&
1441ae6f7882SJeremy Morse         Register::isPhysicalRegister(MO.getReg()) &&
1442133e25f9SJeremy Morse         !IgnoreSPAlias(MO.getReg())) {
1443ae6f7882SJeremy Morse       // Remove ranges of all aliased registers.
1444ae6f7882SJeremy Morse       for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1445ae6f7882SJeremy Morse         // FIXME: Can we break out of this loop early if no insertion occurs?
1446ae6f7882SJeremy Morse         DeadRegs.insert(*RAI);
1447ae6f7882SJeremy Morse     } else if (MO.isRegMask()) {
1448ae6f7882SJeremy Morse       RegMasks.push_back(MO.getRegMask());
1449ae6f7882SJeremy Morse       RegMaskPtrs.push_back(&MO);
1450ae6f7882SJeremy Morse     }
1451ae6f7882SJeremy Morse   }
1452ae6f7882SJeremy Morse 
1453ae6f7882SJeremy Morse   // Tell MLocTracker about all definitions, of regmasks and otherwise.
1454ae6f7882SJeremy Morse   for (uint32_t DeadReg : DeadRegs)
1455ae6f7882SJeremy Morse     MTracker->defReg(DeadReg, CurBB, CurInst);
1456ae6f7882SJeremy Morse 
14579e6d1f4bSKazu Hirata   for (const auto *MO : RegMaskPtrs)
1458ae6f7882SJeremy Morse     MTracker->writeRegMask(MO, CurBB, CurInst);
145949555441SJeremy Morse 
1460ee3eee71SJeremy Morse   // If this instruction writes to a spill slot, def that slot.
1461ee3eee71SJeremy Morse   if (hasFoldedStackStore(MI)) {
146214aaaa12SJeremy Morse     if (Optional<SpillLocationNo> SpillNo = extractSpillBaseRegAndOffset(MI)) {
1463ee3eee71SJeremy Morse       for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) {
146414aaaa12SJeremy Morse         unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillNo, I);
1465ee3eee71SJeremy Morse         LocIdx L = MTracker->getSpillMLoc(SpillID);
1466ee3eee71SJeremy Morse         MTracker->setMLoc(L, ValueIDNum(CurBB, CurInst, L));
1467ee3eee71SJeremy Morse       }
1468ee3eee71SJeremy Morse     }
146914aaaa12SJeremy Morse   }
1470ee3eee71SJeremy Morse 
147149555441SJeremy Morse   if (!TTracker)
147249555441SJeremy Morse     return;
147349555441SJeremy Morse 
147449555441SJeremy Morse   // When committing variable values to locations: tell transfer tracker that
147549555441SJeremy Morse   // we've clobbered things. It may be able to recover the variable from a
147649555441SJeremy Morse   // different location.
147749555441SJeremy Morse 
147849555441SJeremy Morse   // Inform TTracker about any direct clobbers.
147949555441SJeremy Morse   for (uint32_t DeadReg : DeadRegs) {
148049555441SJeremy Morse     LocIdx Loc = MTracker->lookupOrTrackRegister(DeadReg);
148149555441SJeremy Morse     TTracker->clobberMloc(Loc, MI.getIterator(), false);
148249555441SJeremy Morse   }
148349555441SJeremy Morse 
148449555441SJeremy Morse   // Look for any clobbers performed by a register mask. Only test locations
148549555441SJeremy Morse   // that are actually being tracked.
14868e75536eSJeremy Morse   if (!RegMaskPtrs.empty()) {
148749555441SJeremy Morse     for (auto L : MTracker->locations()) {
148849555441SJeremy Morse       // Stack locations can't be clobbered by regmasks.
148949555441SJeremy Morse       if (MTracker->isSpill(L.Idx))
149049555441SJeremy Morse         continue;
149149555441SJeremy Morse 
149249555441SJeremy Morse       Register Reg = MTracker->LocIdxToLocID[L.Idx];
1493133e25f9SJeremy Morse       if (IgnoreSPAlias(Reg))
1494133e25f9SJeremy Morse         continue;
1495133e25f9SJeremy Morse 
14969e6d1f4bSKazu Hirata       for (const auto *MO : RegMaskPtrs)
149749555441SJeremy Morse         if (MO->clobbersPhysReg(Reg))
149849555441SJeremy Morse           TTracker->clobberMloc(L.Idx, MI.getIterator(), false);
149949555441SJeremy Morse     }
15008e75536eSJeremy Morse   }
1501ee3eee71SJeremy Morse 
1502ee3eee71SJeremy Morse   // Tell TTracker about any folded stack store.
1503ee3eee71SJeremy Morse   if (hasFoldedStackStore(MI)) {
150414aaaa12SJeremy Morse     if (Optional<SpillLocationNo> SpillNo = extractSpillBaseRegAndOffset(MI)) {
1505ee3eee71SJeremy Morse       for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) {
150614aaaa12SJeremy Morse         unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillNo, I);
1507ee3eee71SJeremy Morse         LocIdx L = MTracker->getSpillMLoc(SpillID);
1508ee3eee71SJeremy Morse         TTracker->clobberMloc(L, MI.getIterator(), true);
1509ee3eee71SJeremy Morse       }
1510ee3eee71SJeremy Morse     }
1511ae6f7882SJeremy Morse   }
151214aaaa12SJeremy Morse }
1513ae6f7882SJeremy Morse 
performCopy(Register SrcRegNum,Register DstRegNum)1514ae6f7882SJeremy Morse void InstrRefBasedLDV::performCopy(Register SrcRegNum, Register DstRegNum) {
1515d9eebe3cSJeremy Morse   // In all circumstances, re-def all aliases. It's definitely a new value now.
1516d9eebe3cSJeremy Morse   for (MCRegAliasIterator RAI(DstRegNum, TRI, true); RAI.isValid(); ++RAI)
1517d9eebe3cSJeremy Morse     MTracker->defReg(*RAI, CurBB, CurInst);
1518ae6f7882SJeremy Morse 
1519d9eebe3cSJeremy Morse   ValueIDNum SrcValue = MTracker->readReg(SrcRegNum);
1520ae6f7882SJeremy Morse   MTracker->setReg(DstRegNum, SrcValue);
1521ae6f7882SJeremy Morse 
1522d9eebe3cSJeremy Morse   // Copy subregisters from one location to another.
1523ae6f7882SJeremy Morse   for (MCSubRegIndexIterator SRI(SrcRegNum, TRI); SRI.isValid(); ++SRI) {
1524ae6f7882SJeremy Morse     unsigned SrcSubReg = SRI.getSubReg();
1525ae6f7882SJeremy Morse     unsigned SubRegIdx = SRI.getSubRegIndex();
1526ae6f7882SJeremy Morse     unsigned DstSubReg = TRI->getSubReg(DstRegNum, SubRegIdx);
1527ae6f7882SJeremy Morse     if (!DstSubReg)
1528ae6f7882SJeremy Morse       continue;
1529ae6f7882SJeremy Morse 
1530ae6f7882SJeremy Morse     // Do copy. There are two matching subregisters, the source value should
1531ae6f7882SJeremy Morse     // have been def'd when the super-reg was, the latter might not be tracked
1532ae6f7882SJeremy Morse     // yet.
1533d9eebe3cSJeremy Morse     // This will force SrcSubReg to be tracked, if it isn't yet. Will read
1534d9eebe3cSJeremy Morse     // mphi values if it wasn't tracked.
1535d9eebe3cSJeremy Morse     LocIdx SrcL = MTracker->lookupOrTrackRegister(SrcSubReg);
1536d9eebe3cSJeremy Morse     LocIdx DstL = MTracker->lookupOrTrackRegister(DstSubReg);
1537d9eebe3cSJeremy Morse     (void)SrcL;
1538ae6f7882SJeremy Morse     (void)DstL;
1539d9eebe3cSJeremy Morse     ValueIDNum CpyValue = MTracker->readReg(SrcSubReg);
1540ae6f7882SJeremy Morse 
1541ae6f7882SJeremy Morse     MTracker->setReg(DstSubReg, CpyValue);
1542ae6f7882SJeremy Morse   }
1543ae6f7882SJeremy Morse }
1544ae6f7882SJeremy Morse 
154514aaaa12SJeremy Morse Optional<SpillLocationNo>
isSpillInstruction(const MachineInstr & MI,MachineFunction * MF)154614aaaa12SJeremy Morse InstrRefBasedLDV::isSpillInstruction(const MachineInstr &MI,
1547ae6f7882SJeremy Morse                                      MachineFunction *MF) {
1548ae6f7882SJeremy Morse   // TODO: Handle multiple stores folded into one.
1549ae6f7882SJeremy Morse   if (!MI.hasOneMemOperand())
155014aaaa12SJeremy Morse     return None;
1551ae6f7882SJeremy Morse 
1552ee3eee71SJeremy Morse   // Reject any memory operand that's aliased -- we can't guarantee its value.
1553ee3eee71SJeremy Morse   auto MMOI = MI.memoperands_begin();
1554ee3eee71SJeremy Morse   const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
1555ee3eee71SJeremy Morse   if (PVal->isAliased(MFI))
155614aaaa12SJeremy Morse     return None;
1557ee3eee71SJeremy Morse 
1558ae6f7882SJeremy Morse   if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
155914aaaa12SJeremy Morse     return None; // This is not a spill instruction, since no valid size was
1560ae6f7882SJeremy Morse                  // returned from either function.
1561ae6f7882SJeremy Morse 
156214aaaa12SJeremy Morse   return extractSpillBaseRegAndOffset(MI);
1563ae6f7882SJeremy Morse }
1564ae6f7882SJeremy Morse 
isLocationSpill(const MachineInstr & MI,MachineFunction * MF,unsigned & Reg)1565ae6f7882SJeremy Morse bool InstrRefBasedLDV::isLocationSpill(const MachineInstr &MI,
1566ae6f7882SJeremy Morse                                        MachineFunction *MF, unsigned &Reg) {
1567ae6f7882SJeremy Morse   if (!isSpillInstruction(MI, MF))
1568ae6f7882SJeremy Morse     return false;
1569ae6f7882SJeremy Morse 
1570ae6f7882SJeremy Morse   int FI;
1571ae6f7882SJeremy Morse   Reg = TII->isStoreToStackSlotPostFE(MI, FI);
1572ae6f7882SJeremy Morse   return Reg != 0;
1573ae6f7882SJeremy Morse }
1574ae6f7882SJeremy Morse 
1575e7084ceaSJeremy Morse Optional<SpillLocationNo>
isRestoreInstruction(const MachineInstr & MI,MachineFunction * MF,unsigned & Reg)1576ae6f7882SJeremy Morse InstrRefBasedLDV::isRestoreInstruction(const MachineInstr &MI,
1577ae6f7882SJeremy Morse                                        MachineFunction *MF, unsigned &Reg) {
1578ae6f7882SJeremy Morse   if (!MI.hasOneMemOperand())
1579ae6f7882SJeremy Morse     return None;
1580ae6f7882SJeremy Morse 
1581ae6f7882SJeremy Morse   // FIXME: Handle folded restore instructions with more than one memory
1582ae6f7882SJeremy Morse   // operand.
1583ae6f7882SJeremy Morse   if (MI.getRestoreSize(TII)) {
1584ae6f7882SJeremy Morse     Reg = MI.getOperand(0).getReg();
1585ae6f7882SJeremy Morse     return extractSpillBaseRegAndOffset(MI);
1586ae6f7882SJeremy Morse   }
1587ae6f7882SJeremy Morse   return None;
1588ae6f7882SJeremy Morse }
1589ae6f7882SJeremy Morse 
transferSpillOrRestoreInst(MachineInstr & MI)1590ae6f7882SJeremy Morse bool InstrRefBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI) {
1591ae6f7882SJeremy Morse   // XXX -- it's too difficult to implement VarLocBasedImpl's  stack location
1592ae6f7882SJeremy Morse   // limitations under the new model. Therefore, when comparing them, compare
1593ae6f7882SJeremy Morse   // versions that don't attempt spills or restores at all.
1594ae6f7882SJeremy Morse   if (EmulateOldLDV)
1595ae6f7882SJeremy Morse     return false;
1596ae6f7882SJeremy Morse 
1597e7084ceaSJeremy Morse   // Strictly limit ourselves to plain loads and stores, not all instructions
1598e7084ceaSJeremy Morse   // that can access the stack.
1599e7084ceaSJeremy Morse   int DummyFI = -1;
1600e7084ceaSJeremy Morse   if (!TII->isStoreToStackSlotPostFE(MI, DummyFI) &&
1601e7084ceaSJeremy Morse       !TII->isLoadFromStackSlotPostFE(MI, DummyFI))
1602e7084ceaSJeremy Morse     return false;
1603e7084ceaSJeremy Morse 
1604ae6f7882SJeremy Morse   MachineFunction *MF = MI.getMF();
1605ae6f7882SJeremy Morse   unsigned Reg;
1606ae6f7882SJeremy Morse 
1607ae6f7882SJeremy Morse   LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
1608ae6f7882SJeremy Morse 
1609ee3eee71SJeremy Morse   // Strictly limit ourselves to plain loads and stores, not all instructions
1610ee3eee71SJeremy Morse   // that can access the stack.
1611ee3eee71SJeremy Morse   int FIDummy;
1612ee3eee71SJeremy Morse   if (!TII->isStoreToStackSlotPostFE(MI, FIDummy) &&
1613ee3eee71SJeremy Morse       !TII->isLoadFromStackSlotPostFE(MI, FIDummy))
1614ee3eee71SJeremy Morse     return false;
1615ee3eee71SJeremy Morse 
1616ae6f7882SJeremy Morse   // First, if there are any DBG_VALUEs pointing at a spill slot that is
1617ae6f7882SJeremy Morse   // written to, terminate that variable location. The value in memory
1618ae6f7882SJeremy Morse   // will have changed. DbgEntityHistoryCalculator doesn't try to detect this.
161914aaaa12SJeremy Morse   if (Optional<SpillLocationNo> Loc = isSpillInstruction(MI, MF)) {
1620e7084ceaSJeremy Morse     // Un-set this location and clobber, so that earlier locations don't
1621e7084ceaSJeremy Morse     // continue past this store.
1622e7084ceaSJeremy Morse     for (unsigned SlotIdx = 0; SlotIdx < MTracker->NumSlotIdxes; ++SlotIdx) {
162314aaaa12SJeremy Morse       unsigned SpillID = MTracker->getSpillIDWithIdx(*Loc, SlotIdx);
1624e7084ceaSJeremy Morse       Optional<LocIdx> MLoc = MTracker->getSpillMLoc(SpillID);
1625e7084ceaSJeremy Morse       if (!MLoc)
1626e7084ceaSJeremy Morse         continue;
1627e7084ceaSJeremy Morse 
1628e7084ceaSJeremy Morse       // We need to over-write the stack slot with something (here, a def at
1629e7084ceaSJeremy Morse       // this instruction) to ensure no values are preserved in this stack slot
1630e7084ceaSJeremy Morse       // after the spill. It also prevents TTracker from trying to recover the
1631e7084ceaSJeremy Morse       // location and re-installing it in the same place.
1632e7084ceaSJeremy Morse       ValueIDNum Def(CurBB, CurInst, *MLoc);
1633e7084ceaSJeremy Morse       MTracker->setMLoc(*MLoc, Def);
1634e7084ceaSJeremy Morse       if (TTracker)
1635ae6f7882SJeremy Morse         TTracker->clobberMloc(*MLoc, MI.getIterator());
1636ae6f7882SJeremy Morse     }
1637ae6f7882SJeremy Morse   }
1638ae6f7882SJeremy Morse 
1639ae6f7882SJeremy Morse   // Try to recognise spill and restore instructions that may transfer a value.
1640ae6f7882SJeremy Morse   if (isLocationSpill(MI, MF, Reg)) {
164114aaaa12SJeremy Morse     // isLocationSpill returning true should guarantee we can extract a
164214aaaa12SJeremy Morse     // location.
164314aaaa12SJeremy Morse     SpillLocationNo Loc = *extractSpillBaseRegAndOffset(MI);
1644ae6f7882SJeremy Morse 
1645e7084ceaSJeremy Morse     auto DoTransfer = [&](Register SrcReg, unsigned SpillID) {
1646e7084ceaSJeremy Morse       auto ReadValue = MTracker->readReg(SrcReg);
1647e7084ceaSJeremy Morse       LocIdx DstLoc = MTracker->getSpillMLoc(SpillID);
1648e7084ceaSJeremy Morse       MTracker->setMLoc(DstLoc, ReadValue);
1649ae6f7882SJeremy Morse 
1650e7084ceaSJeremy Morse       if (TTracker) {
1651e7084ceaSJeremy Morse         LocIdx SrcLoc = MTracker->getRegMLoc(SrcReg);
1652e7084ceaSJeremy Morse         TTracker->transferMlocs(SrcLoc, DstLoc, MI.getIterator());
1653ae6f7882SJeremy Morse       }
1654e7084ceaSJeremy Morse     };
1655e7084ceaSJeremy Morse 
1656e7084ceaSJeremy Morse     // Then, transfer subreg bits.
1657e7084ceaSJeremy Morse     for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) {
1658e7084ceaSJeremy Morse       // Ensure this reg is tracked,
1659e7084ceaSJeremy Morse       (void)MTracker->lookupOrTrackRegister(*SRI);
1660e7084ceaSJeremy Morse       unsigned SubregIdx = TRI->getSubRegIndex(Reg, *SRI);
1661e7084ceaSJeremy Morse       unsigned SpillID = MTracker->getLocID(Loc, SubregIdx);
1662e7084ceaSJeremy Morse       DoTransfer(*SRI, SpillID);
1663e7084ceaSJeremy Morse     }
1664e7084ceaSJeremy Morse 
1665e7084ceaSJeremy Morse     // Directly lookup size of main source reg, and transfer.
1666e7084ceaSJeremy Morse     unsigned Size = TRI->getRegSizeInBits(Reg, *MRI);
1667e7084ceaSJeremy Morse     unsigned SpillID = MTracker->getLocID(Loc, {Size, 0});
1668e7084ceaSJeremy Morse     DoTransfer(Reg, SpillID);
1669e7084ceaSJeremy Morse   } else {
167014aaaa12SJeremy Morse     Optional<SpillLocationNo> Loc = isRestoreInstruction(MI, MF, Reg);
167114aaaa12SJeremy Morse     if (!Loc)
1672e7084ceaSJeremy Morse       return false;
1673e7084ceaSJeremy Morse 
1674e7084ceaSJeremy Morse     // Assumption: we're reading from the base of the stack slot, not some
1675e7084ceaSJeremy Morse     // offset into it. It seems very unlikely LLVM would ever generate
1676e7084ceaSJeremy Morse     // restores where this wasn't true. This then becomes a question of what
1677e7084ceaSJeremy Morse     // subregisters in the destination register line up with positions in the
1678e7084ceaSJeremy Morse     // stack slot.
1679e7084ceaSJeremy Morse 
1680e7084ceaSJeremy Morse     // Def all registers that alias the destination.
1681e7084ceaSJeremy Morse     for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1682e7084ceaSJeremy Morse       MTracker->defReg(*RAI, CurBB, CurInst);
1683e7084ceaSJeremy Morse 
1684e7084ceaSJeremy Morse     // Now find subregisters within the destination register, and load values
1685e7084ceaSJeremy Morse     // from stack slot positions.
1686e7084ceaSJeremy Morse     auto DoTransfer = [&](Register DestReg, unsigned SpillID) {
1687e7084ceaSJeremy Morse       LocIdx SrcIdx = MTracker->getSpillMLoc(SpillID);
1688e7084ceaSJeremy Morse       auto ReadValue = MTracker->readMLoc(SrcIdx);
1689e7084ceaSJeremy Morse       MTracker->setReg(DestReg, ReadValue);
1690e7084ceaSJeremy Morse     };
1691e7084ceaSJeremy Morse 
1692e7084ceaSJeremy Morse     for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) {
1693e7084ceaSJeremy Morse       unsigned Subreg = TRI->getSubRegIndex(Reg, *SRI);
169414aaaa12SJeremy Morse       unsigned SpillID = MTracker->getLocID(*Loc, Subreg);
1695e7084ceaSJeremy Morse       DoTransfer(*SRI, SpillID);
1696e7084ceaSJeremy Morse     }
1697e7084ceaSJeremy Morse 
1698e7084ceaSJeremy Morse     // Directly look up this registers slot idx by size, and transfer.
1699e7084ceaSJeremy Morse     unsigned Size = TRI->getRegSizeInBits(Reg, *MRI);
170014aaaa12SJeremy Morse     unsigned SpillID = MTracker->getLocID(*Loc, {Size, 0});
1701e7084ceaSJeremy Morse     DoTransfer(Reg, SpillID);
1702ae6f7882SJeremy Morse   }
1703ae6f7882SJeremy Morse   return true;
1704ae6f7882SJeremy Morse }
1705ae6f7882SJeremy Morse 
transferRegisterCopy(MachineInstr & MI)1706ae6f7882SJeremy Morse bool InstrRefBasedLDV::transferRegisterCopy(MachineInstr &MI) {
1707ae6f7882SJeremy Morse   auto DestSrc = TII->isCopyInstr(MI);
1708ae6f7882SJeremy Morse   if (!DestSrc)
1709ae6f7882SJeremy Morse     return false;
1710ae6f7882SJeremy Morse 
1711ae6f7882SJeremy Morse   const MachineOperand *DestRegOp = DestSrc->Destination;
1712ae6f7882SJeremy Morse   const MachineOperand *SrcRegOp = DestSrc->Source;
1713ae6f7882SJeremy Morse 
1714ae6f7882SJeremy Morse   auto isCalleeSavedReg = [&](unsigned Reg) {
1715ae6f7882SJeremy Morse     for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1716ae6f7882SJeremy Morse       if (CalleeSavedRegs.test(*RAI))
1717ae6f7882SJeremy Morse         return true;
1718ae6f7882SJeremy Morse     return false;
1719ae6f7882SJeremy Morse   };
1720ae6f7882SJeremy Morse 
1721ae6f7882SJeremy Morse   Register SrcReg = SrcRegOp->getReg();
1722ae6f7882SJeremy Morse   Register DestReg = DestRegOp->getReg();
1723ae6f7882SJeremy Morse 
1724ae6f7882SJeremy Morse   // Ignore identity copies. Yep, these make it as far as LiveDebugValues.
1725ae6f7882SJeremy Morse   if (SrcReg == DestReg)
1726ae6f7882SJeremy Morse     return true;
1727ae6f7882SJeremy Morse 
1728ae6f7882SJeremy Morse   // For emulating VarLocBasedImpl:
1729ae6f7882SJeremy Morse   // We want to recognize instructions where destination register is callee
1730ae6f7882SJeremy Morse   // saved register. If register that could be clobbered by the call is
1731ae6f7882SJeremy Morse   // included, there would be a great chance that it is going to be clobbered
1732ae6f7882SJeremy Morse   // soon. It is more likely that previous register, which is callee saved, is
1733ae6f7882SJeremy Morse   // going to stay unclobbered longer, even if it is killed.
1734ae6f7882SJeremy Morse   //
1735ae6f7882SJeremy Morse   // For InstrRefBasedImpl, we can track multiple locations per value, so
1736ae6f7882SJeremy Morse   // ignore this condition.
1737ae6f7882SJeremy Morse   if (EmulateOldLDV && !isCalleeSavedReg(DestReg))
1738ae6f7882SJeremy Morse     return false;
1739ae6f7882SJeremy Morse 
1740ae6f7882SJeremy Morse   // InstrRefBasedImpl only followed killing copies.
1741ae6f7882SJeremy Morse   if (EmulateOldLDV && !SrcRegOp->isKill())
1742ae6f7882SJeremy Morse     return false;
1743ae6f7882SJeremy Morse 
1744f9ac161aSStephen Tozer   // Before we update MTracker, remember which values were present in each of
1745f9ac161aSStephen Tozer   // the locations about to be overwritten, so that we can recover any
1746f9ac161aSStephen Tozer   // potentially clobbered variables.
1747f9ac161aSStephen Tozer   DenseMap<LocIdx, ValueIDNum> ClobberedLocs;
1748f9ac161aSStephen Tozer   if (TTracker) {
1749f9ac161aSStephen Tozer     for (MCRegAliasIterator RAI(DestReg, TRI, true); RAI.isValid(); ++RAI) {
1750f9ac161aSStephen Tozer       LocIdx ClobberedLoc = MTracker->getRegMLoc(*RAI);
1751f9ac161aSStephen Tozer       auto MLocIt = TTracker->ActiveMLocs.find(ClobberedLoc);
1752f9ac161aSStephen Tozer       // If ActiveMLocs isn't tracking this location or there are no variables
1753f9ac161aSStephen Tozer       // using it, don't bother remembering.
1754f9ac161aSStephen Tozer       if (MLocIt == TTracker->ActiveMLocs.end() || MLocIt->second.empty())
1755f9ac161aSStephen Tozer         continue;
1756f9ac161aSStephen Tozer       ValueIDNum Value = MTracker->readReg(*RAI);
1757f9ac161aSStephen Tozer       ClobberedLocs[ClobberedLoc] = Value;
1758f9ac161aSStephen Tozer     }
1759f9ac161aSStephen Tozer   }
1760f9ac161aSStephen Tozer 
1761ae6f7882SJeremy Morse   // Copy MTracker info, including subregs if available.
1762ae6f7882SJeremy Morse   InstrRefBasedLDV::performCopy(SrcReg, DestReg);
1763ae6f7882SJeremy Morse 
1764f9ac161aSStephen Tozer   // The copy might have clobbered variables based on the destination register.
1765f9ac161aSStephen Tozer   // Tell TTracker about it, passing the old ValueIDNum to search for
1766f9ac161aSStephen Tozer   // alternative locations (or else terminating those variables).
1767f9ac161aSStephen Tozer   if (TTracker) {
1768f9ac161aSStephen Tozer     for (auto LocVal : ClobberedLocs) {
1769f9ac161aSStephen Tozer       TTracker->clobberMloc(LocVal.first, LocVal.second, MI.getIterator(), false);
1770f9ac161aSStephen Tozer     }
1771f9ac161aSStephen Tozer   }
1772f9ac161aSStephen Tozer 
1773ae6f7882SJeremy Morse   // Only produce a transfer of DBG_VALUE within a block where old LDV
1774ae6f7882SJeremy Morse   // would have. We might make use of the additional value tracking in some
1775ae6f7882SJeremy Morse   // other way, later.
1776ae6f7882SJeremy Morse   if (TTracker && isCalleeSavedReg(DestReg) && SrcRegOp->isKill())
1777ae6f7882SJeremy Morse     TTracker->transferMlocs(MTracker->getRegMLoc(SrcReg),
1778ae6f7882SJeremy Morse                             MTracker->getRegMLoc(DestReg), MI.getIterator());
1779ae6f7882SJeremy Morse 
1780ae6f7882SJeremy Morse   // VarLocBasedImpl would quit tracking the old location after copying.
1781ae6f7882SJeremy Morse   if (EmulateOldLDV && SrcReg != DestReg)
1782ae6f7882SJeremy Morse     MTracker->defReg(SrcReg, CurBB, CurInst);
1783ae6f7882SJeremy Morse 
1784ae6f7882SJeremy Morse   return true;
1785ae6f7882SJeremy Morse }
1786ae6f7882SJeremy Morse 
1787ae6f7882SJeremy Morse /// Accumulate a mapping between each DILocalVariable fragment and other
1788ae6f7882SJeremy Morse /// fragments of that DILocalVariable which overlap. This reduces work during
1789ae6f7882SJeremy Morse /// the data-flow stage from "Find any overlapping fragments" to "Check if the
1790ae6f7882SJeremy Morse /// known-to-overlap fragments are present".
17910eee8445SJeremy Morse /// \param MI A previously unprocessed debug instruction to analyze for
1792ae6f7882SJeremy Morse ///           fragment usage.
accumulateFragmentMap(MachineInstr & MI)1793ae6f7882SJeremy Morse void InstrRefBasedLDV::accumulateFragmentMap(MachineInstr &MI) {
17940eee8445SJeremy Morse   assert(MI.isDebugValue() || MI.isDebugRef());
1795ae6f7882SJeremy Morse   DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(),
1796ae6f7882SJeremy Morse                       MI.getDebugLoc()->getInlinedAt());
1797ae6f7882SJeremy Morse   FragmentInfo ThisFragment = MIVar.getFragmentOrDefault();
1798ae6f7882SJeremy Morse 
1799ae6f7882SJeremy Morse   // If this is the first sighting of this variable, then we are guaranteed
1800ae6f7882SJeremy Morse   // there are currently no overlapping fragments either. Initialize the set
1801ae6f7882SJeremy Morse   // of seen fragments, record no overlaps for the current one, and return.
1802ae6f7882SJeremy Morse   auto SeenIt = SeenFragments.find(MIVar.getVariable());
1803ae6f7882SJeremy Morse   if (SeenIt == SeenFragments.end()) {
1804ae6f7882SJeremy Morse     SmallSet<FragmentInfo, 4> OneFragment;
1805ae6f7882SJeremy Morse     OneFragment.insert(ThisFragment);
1806ae6f7882SJeremy Morse     SeenFragments.insert({MIVar.getVariable(), OneFragment});
1807ae6f7882SJeremy Morse 
1808ae6f7882SJeremy Morse     OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
1809ae6f7882SJeremy Morse     return;
1810ae6f7882SJeremy Morse   }
1811ae6f7882SJeremy Morse 
1812ae6f7882SJeremy Morse   // If this particular Variable/Fragment pair already exists in the overlap
1813ae6f7882SJeremy Morse   // map, it has already been accounted for.
1814ae6f7882SJeremy Morse   auto IsInOLapMap =
1815ae6f7882SJeremy Morse       OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
1816ae6f7882SJeremy Morse   if (!IsInOLapMap.second)
1817ae6f7882SJeremy Morse     return;
1818ae6f7882SJeremy Morse 
1819ae6f7882SJeremy Morse   auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
1820ae6f7882SJeremy Morse   auto &AllSeenFragments = SeenIt->second;
1821ae6f7882SJeremy Morse 
1822ae6f7882SJeremy Morse   // Otherwise, examine all other seen fragments for this variable, with "this"
1823ae6f7882SJeremy Morse   // fragment being a previously unseen fragment. Record any pair of
1824ae6f7882SJeremy Morse   // overlapping fragments.
18259e6d1f4bSKazu Hirata   for (const auto &ASeenFragment : AllSeenFragments) {
1826ae6f7882SJeremy Morse     // Does this previously seen fragment overlap?
1827ae6f7882SJeremy Morse     if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
1828ae6f7882SJeremy Morse       // Yes: Mark the current fragment as being overlapped.
1829ae6f7882SJeremy Morse       ThisFragmentsOverlaps.push_back(ASeenFragment);
1830ae6f7882SJeremy Morse       // Mark the previously seen fragment as being overlapped by the current
1831ae6f7882SJeremy Morse       // one.
1832ae6f7882SJeremy Morse       auto ASeenFragmentsOverlaps =
1833ae6f7882SJeremy Morse           OverlapFragments.find({MIVar.getVariable(), ASeenFragment});
1834ae6f7882SJeremy Morse       assert(ASeenFragmentsOverlaps != OverlapFragments.end() &&
1835ae6f7882SJeremy Morse              "Previously seen var fragment has no vector of overlaps");
1836ae6f7882SJeremy Morse       ASeenFragmentsOverlaps->second.push_back(ThisFragment);
1837ae6f7882SJeremy Morse     }
1838ae6f7882SJeremy Morse   }
1839ae6f7882SJeremy Morse 
1840ae6f7882SJeremy Morse   AllSeenFragments.insert(ThisFragment);
1841ae6f7882SJeremy Morse }
1842ae6f7882SJeremy Morse 
process(MachineInstr & MI,const ValueTable * MLiveOuts,const ValueTable * MLiveIns)1843ab49dce0SJeremy Morse void InstrRefBasedLDV::process(MachineInstr &MI, const ValueTable *MLiveOuts,
1844ab49dce0SJeremy Morse                                const ValueTable *MLiveIns) {
1845ae6f7882SJeremy Morse   // Try to interpret an MI as a debug or transfer instruction. Only if it's
1846ae6f7882SJeremy Morse   // none of these should we interpret it's register defs as new value
1847ae6f7882SJeremy Morse   // definitions.
1848ae6f7882SJeremy Morse   if (transferDebugValue(MI))
1849ae6f7882SJeremy Morse     return;
1850010108bbSJeremy Morse   if (transferDebugInstrRef(MI, MLiveOuts, MLiveIns))
1851010108bbSJeremy Morse     return;
1852010108bbSJeremy Morse   if (transferDebugPHI(MI))
185368f47157SJeremy Morse     return;
1854ae6f7882SJeremy Morse   if (transferRegisterCopy(MI))
1855ae6f7882SJeremy Morse     return;
1856ae6f7882SJeremy Morse   if (transferSpillOrRestoreInst(MI))
1857ae6f7882SJeremy Morse     return;
1858ae6f7882SJeremy Morse   transferRegisterDef(MI);
1859ae6f7882SJeremy Morse }
1860ae6f7882SJeremy Morse 
produceMLocTransferFunction(MachineFunction & MF,SmallVectorImpl<MLocTransferMap> & MLocTransfer,unsigned MaxNumBlocks)1861ab93e710SJeremy Morse void InstrRefBasedLDV::produceMLocTransferFunction(
1862ae6f7882SJeremy Morse     MachineFunction &MF, SmallVectorImpl<MLocTransferMap> &MLocTransfer,
1863ab93e710SJeremy Morse     unsigned MaxNumBlocks) {
1864ae6f7882SJeremy Morse   // Because we try to optimize around register mask operands by ignoring regs
1865ae6f7882SJeremy Morse   // that aren't currently tracked, we set up something ugly for later: RegMask
1866ae6f7882SJeremy Morse   // operands that are seen earlier than the first use of a register, still need
1867ae6f7882SJeremy Morse   // to clobber that register in the transfer function. But this information
1868ae6f7882SJeremy Morse   // isn't actively recorded. Instead, we track each RegMask used in each block,
1869ae6f7882SJeremy Morse   // and accumulated the clobbered but untracked registers in each block into
1870ae6f7882SJeremy Morse   // the following bitvector. Later, if new values are tracked, we can add
1871ae6f7882SJeremy Morse   // appropriate clobbers.
1872ae6f7882SJeremy Morse   SmallVector<BitVector, 32> BlockMasks;
1873ae6f7882SJeremy Morse   BlockMasks.resize(MaxNumBlocks);
1874ae6f7882SJeremy Morse 
1875ae6f7882SJeremy Morse   // Reserve one bit per register for the masks described above.
1876ae6f7882SJeremy Morse   unsigned BVWords = MachineOperand::getRegMaskSize(TRI->getNumRegs());
1877ae6f7882SJeremy Morse   for (auto &BV : BlockMasks)
1878ae6f7882SJeremy Morse     BV.resize(TRI->getNumRegs(), true);
1879ae6f7882SJeremy Morse 
1880ae6f7882SJeremy Morse   // Step through all instructions and inhale the transfer function.
1881ae6f7882SJeremy Morse   for (auto &MBB : MF) {
1882ae6f7882SJeremy Morse     // Object fields that are read by trackers to know where we are in the
1883ae6f7882SJeremy Morse     // function.
1884ae6f7882SJeremy Morse     CurBB = MBB.getNumber();
1885ae6f7882SJeremy Morse     CurInst = 1;
1886ae6f7882SJeremy Morse 
1887ae6f7882SJeremy Morse     // Set all machine locations to a PHI value. For transfer function
1888ae6f7882SJeremy Morse     // production only, this signifies the live-in value to the block.
1889ae6f7882SJeremy Morse     MTracker->reset();
1890ae6f7882SJeremy Morse     MTracker->setMPhis(CurBB);
1891ae6f7882SJeremy Morse 
1892ae6f7882SJeremy Morse     // Step through each instruction in this block.
1893ae6f7882SJeremy Morse     for (auto &MI : MBB) {
1894ab49dce0SJeremy Morse       // Pass in an empty unique_ptr for the value tables when accumulating the
1895ab49dce0SJeremy Morse       // machine transfer function.
1896ab49dce0SJeremy Morse       process(MI, nullptr, nullptr);
1897ab49dce0SJeremy Morse 
1898ae6f7882SJeremy Morse       // Also accumulate fragment map.
18990eee8445SJeremy Morse       if (MI.isDebugValue() || MI.isDebugRef())
1900ae6f7882SJeremy Morse         accumulateFragmentMap(MI);
190168f47157SJeremy Morse 
190268f47157SJeremy Morse       // Create a map from the instruction number (if present) to the
190368f47157SJeremy Morse       // MachineInstr and its position.
1904cca049adSDjordje Todorovic       if (uint64_t InstrNo = MI.peekDebugInstrNum()) {
190568f47157SJeremy Morse         auto InstrAndPos = std::make_pair(&MI, CurInst);
190668f47157SJeremy Morse         auto InsertResult =
190768f47157SJeremy Morse             DebugInstrNumToInstr.insert(std::make_pair(InstrNo, InstrAndPos));
190868f47157SJeremy Morse 
190968f47157SJeremy Morse         // There should never be duplicate instruction numbers.
191068f47157SJeremy Morse         assert(InsertResult.second);
191168f47157SJeremy Morse         (void)InsertResult;
191268f47157SJeremy Morse       }
191368f47157SJeremy Morse 
1914ae6f7882SJeremy Morse       ++CurInst;
1915ae6f7882SJeremy Morse     }
1916ae6f7882SJeremy Morse 
1917ae6f7882SJeremy Morse     // Produce the transfer function, a map of machine location to new value. If
1918ae6f7882SJeremy Morse     // any machine location has the live-in phi value from the start of the
1919ae6f7882SJeremy Morse     // block, it's live-through and doesn't need recording in the transfer
1920ae6f7882SJeremy Morse     // function.
1921ae6f7882SJeremy Morse     for (auto Location : MTracker->locations()) {
1922ae6f7882SJeremy Morse       LocIdx Idx = Location.Idx;
1923ae6f7882SJeremy Morse       ValueIDNum &P = Location.Value;
1924ae6f7882SJeremy Morse       if (P.isPHI() && P.getLoc() == Idx.asU64())
1925ae6f7882SJeremy Morse         continue;
1926ae6f7882SJeremy Morse 
1927ae6f7882SJeremy Morse       // Insert-or-update.
1928ae6f7882SJeremy Morse       auto &TransferMap = MLocTransfer[CurBB];
1929ae6f7882SJeremy Morse       auto Result = TransferMap.insert(std::make_pair(Idx.asU64(), P));
1930ae6f7882SJeremy Morse       if (!Result.second)
1931ae6f7882SJeremy Morse         Result.first->second = P;
1932ae6f7882SJeremy Morse     }
1933ae6f7882SJeremy Morse 
1934ae6f7882SJeremy Morse     // Accumulate any bitmask operands into the clobberred reg mask for this
1935ae6f7882SJeremy Morse     // block.
1936ae6f7882SJeremy Morse     for (auto &P : MTracker->Masks) {
1937ae6f7882SJeremy Morse       BlockMasks[CurBB].clearBitsNotInMask(P.first->getRegMask(), BVWords);
1938ae6f7882SJeremy Morse     }
1939ae6f7882SJeremy Morse   }
1940ae6f7882SJeremy Morse 
1941ae6f7882SJeremy Morse   // Compute a bitvector of all the registers that are tracked in this block.
1942ae6f7882SJeremy Morse   BitVector UsedRegs(TRI->getNumRegs());
1943ae6f7882SJeremy Morse   for (auto Location : MTracker->locations()) {
1944ae6f7882SJeremy Morse     unsigned ID = MTracker->LocIdxToLocID[Location.Idx];
1945fbf269c7SJeremy Morse     // Ignore stack slots, and aliases of the stack pointer.
1946fbf269c7SJeremy Morse     if (ID >= TRI->getNumRegs() || MTracker->SPAliases.count(ID))
1947ae6f7882SJeremy Morse       continue;
1948ae6f7882SJeremy Morse     UsedRegs.set(ID);
1949ae6f7882SJeremy Morse   }
1950ae6f7882SJeremy Morse 
1951ae6f7882SJeremy Morse   // Check that any regmask-clobber of a register that gets tracked, is not
1952ae6f7882SJeremy Morse   // live-through in the transfer function. It needs to be clobbered at the
1953ae6f7882SJeremy Morse   // very least.
1954ae6f7882SJeremy Morse   for (unsigned int I = 0; I < MaxNumBlocks; ++I) {
1955ae6f7882SJeremy Morse     BitVector &BV = BlockMasks[I];
1956ae6f7882SJeremy Morse     BV.flip();
1957ae6f7882SJeremy Morse     BV &= UsedRegs;
1958ae6f7882SJeremy Morse     // This produces all the bits that we clobber, but also use. Check that
1959ae6f7882SJeremy Morse     // they're all clobbered or at least set in the designated transfer
1960ae6f7882SJeremy Morse     // elem.
1961ae6f7882SJeremy Morse     for (unsigned Bit : BV.set_bits()) {
1962e7084ceaSJeremy Morse       unsigned ID = MTracker->getLocID(Bit);
1963ae6f7882SJeremy Morse       LocIdx Idx = MTracker->LocIDToLocIdx[ID];
1964ae6f7882SJeremy Morse       auto &TransferMap = MLocTransfer[I];
1965ae6f7882SJeremy Morse 
1966ae6f7882SJeremy Morse       // Install a value representing the fact that this location is effectively
1967ae6f7882SJeremy Morse       // written to in this block. As there's no reserved value, instead use
1968ae6f7882SJeremy Morse       // a value number that is never generated. Pick the value number for the
1969ae6f7882SJeremy Morse       // first instruction in the block, def'ing this location, which we know
1970ae6f7882SJeremy Morse       // this block never used anyway.
1971ae6f7882SJeremy Morse       ValueIDNum NotGeneratedNum = ValueIDNum(I, 1, Idx);
1972ae6f7882SJeremy Morse       auto Result =
1973ae6f7882SJeremy Morse         TransferMap.insert(std::make_pair(Idx.asU64(), NotGeneratedNum));
1974ae6f7882SJeremy Morse       if (!Result.second) {
1975ae6f7882SJeremy Morse         ValueIDNum &ValueID = Result.first->second;
1976ae6f7882SJeremy Morse         if (ValueID.getBlock() == I && ValueID.isPHI())
1977ae6f7882SJeremy Morse           // It was left as live-through. Set it to clobbered.
1978ae6f7882SJeremy Morse           ValueID = NotGeneratedNum;
1979ae6f7882SJeremy Morse       }
1980ae6f7882SJeremy Morse     }
1981ae6f7882SJeremy Morse   }
1982ae6f7882SJeremy Morse }
1983ae6f7882SJeremy Morse 
mlocJoin(MachineBasicBlock & MBB,SmallPtrSet<const MachineBasicBlock *,16> & Visited,FuncValueTable & OutLocs,ValueTable & InLocs)1984a3936a6cSJeremy Morse bool InstrRefBasedLDV::mlocJoin(
1985a3936a6cSJeremy Morse     MachineBasicBlock &MBB, SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
1986ab49dce0SJeremy Morse     FuncValueTable &OutLocs, ValueTable &InLocs) {
1987ae6f7882SJeremy Morse   LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
1988ae6f7882SJeremy Morse   bool Changed = false;
1989ae6f7882SJeremy Morse 
1990a3936a6cSJeremy Morse   // Handle value-propagation when control flow merges on entry to a block. For
1991a3936a6cSJeremy Morse   // any location without a PHI already placed, the location has the same value
1992a3936a6cSJeremy Morse   // as its predecessors. If a PHI is placed, test to see whether it's now a
1993a3936a6cSJeremy Morse   // redundant PHI that we can eliminate.
1994a3936a6cSJeremy Morse 
1995ae6f7882SJeremy Morse   SmallVector<const MachineBasicBlock *, 8> BlockOrders;
19969e6d1f4bSKazu Hirata   for (auto *Pred : MBB.predecessors())
1997ae6f7882SJeremy Morse     BlockOrders.push_back(Pred);
1998ae6f7882SJeremy Morse 
1999ae6f7882SJeremy Morse   // Visit predecessors in RPOT order.
2000ae6f7882SJeremy Morse   auto Cmp = [&](const MachineBasicBlock *A, const MachineBasicBlock *B) {
2001ae6f7882SJeremy Morse     return BBToOrder.find(A)->second < BBToOrder.find(B)->second;
2002ae6f7882SJeremy Morse   };
20039bcc0d10SKazu Hirata   llvm::sort(BlockOrders, Cmp);
2004ae6f7882SJeremy Morse 
2005ae6f7882SJeremy Morse   // Skip entry block.
2006ae6f7882SJeremy Morse   if (BlockOrders.size() == 0)
2007a3936a6cSJeremy Morse     return false;
2008ae6f7882SJeremy Morse 
2009a3936a6cSJeremy Morse   // Step through all machine locations, look at each predecessor and test
2010a3936a6cSJeremy Morse   // whether we can eliminate redundant PHIs.
2011ae6f7882SJeremy Morse   for (auto Location : MTracker->locations()) {
2012ae6f7882SJeremy Morse     LocIdx Idx = Location.Idx;
2013a3936a6cSJeremy Morse 
2014ae6f7882SJeremy Morse     // Pick out the first predecessors live-out value for this location. It's
2015a3936a6cSJeremy Morse     // guaranteed to not be a backedge, as we order by RPO.
2016a3936a6cSJeremy Morse     ValueIDNum FirstVal = OutLocs[BlockOrders[0]->getNumber()][Idx.asU64()];
2017ae6f7882SJeremy Morse 
2018a3936a6cSJeremy Morse     // If we've already eliminated a PHI here, do no further checking, just
2019a3936a6cSJeremy Morse     // propagate the first live-in value into this block.
2020a3936a6cSJeremy Morse     if (InLocs[Idx.asU64()] != ValueIDNum(MBB.getNumber(), 0, Idx)) {
2021a3936a6cSJeremy Morse       if (InLocs[Idx.asU64()] != FirstVal) {
2022a3936a6cSJeremy Morse         InLocs[Idx.asU64()] = FirstVal;
2023a3936a6cSJeremy Morse         Changed |= true;
2024a3936a6cSJeremy Morse       }
2025a3936a6cSJeremy Morse       continue;
2026a3936a6cSJeremy Morse     }
2027a3936a6cSJeremy Morse 
2028a3936a6cSJeremy Morse     // We're now examining a PHI to see whether it's un-necessary. Loop around
2029a3936a6cSJeremy Morse     // the other live-in values and test whether they're all the same.
2030ae6f7882SJeremy Morse     bool Disagree = false;
2031ae6f7882SJeremy Morse     for (unsigned int I = 1; I < BlockOrders.size(); ++I) {
2032a3936a6cSJeremy Morse       const MachineBasicBlock *PredMBB = BlockOrders[I];
2033a3936a6cSJeremy Morse       const ValueIDNum &PredLiveOut =
2034a3936a6cSJeremy Morse           OutLocs[PredMBB->getNumber()][Idx.asU64()];
2035a3936a6cSJeremy Morse 
2036a3936a6cSJeremy Morse       // Incoming values agree, continue trying to eliminate this PHI.
2037a3936a6cSJeremy Morse       if (FirstVal == PredLiveOut)
2038a3936a6cSJeremy Morse         continue;
2039a3936a6cSJeremy Morse 
2040a3936a6cSJeremy Morse       // We can also accept a PHI value that feeds back into itself.
2041a3936a6cSJeremy Morse       if (PredLiveOut == ValueIDNum(MBB.getNumber(), 0, Idx))
2042a3936a6cSJeremy Morse         continue;
2043a3936a6cSJeremy Morse 
2044ae6f7882SJeremy Morse       // Live-out of a predecessor disagrees with the first predecessor.
2045ae6f7882SJeremy Morse       Disagree = true;
2046ae6f7882SJeremy Morse     }
2047ae6f7882SJeremy Morse 
2048a3936a6cSJeremy Morse     // No disagreement? No PHI. Otherwise, leave the PHI in live-ins.
2049a3936a6cSJeremy Morse     if (!Disagree) {
2050a3936a6cSJeremy Morse       InLocs[Idx.asU64()] = FirstVal;
2051ae6f7882SJeremy Morse       Changed |= true;
2052ae6f7882SJeremy Morse     }
2053ae6f7882SJeremy Morse   }
2054ae6f7882SJeremy Morse 
2055cca049adSDjordje Todorovic   // TODO: Reimplement NumInserted and NumRemoved.
2056a3936a6cSJeremy Morse   return Changed;
2057ae6f7882SJeremy Morse }
2058ae6f7882SJeremy Morse 
findStackIndexInterference(SmallVectorImpl<unsigned> & Slots)205997ddf49eSJeremy Morse void InstrRefBasedLDV::findStackIndexInterference(
206097ddf49eSJeremy Morse     SmallVectorImpl<unsigned> &Slots) {
206197ddf49eSJeremy Morse   // We could spend a bit of time finding the exact, minimal, set of stack
206297ddf49eSJeremy Morse   // indexes that interfere with each other, much like reg units. Or, we can
206397ddf49eSJeremy Morse   // rely on the fact that:
206497ddf49eSJeremy Morse   //  * The smallest / lowest index will interfere with everything at zero
206597ddf49eSJeremy Morse   //    offset, which will be the largest set of registers,
206697ddf49eSJeremy Morse   //  * Most indexes with non-zero offset will end up being interference units
206797ddf49eSJeremy Morse   //    anyway.
206897ddf49eSJeremy Morse   // So just pick those out and return them.
206997ddf49eSJeremy Morse 
207097ddf49eSJeremy Morse   // We can rely on a single-byte stack index existing already, because we
207197ddf49eSJeremy Morse   // initialize them in MLocTracker.
207297ddf49eSJeremy Morse   auto It = MTracker->StackSlotIdxes.find({8, 0});
207397ddf49eSJeremy Morse   assert(It != MTracker->StackSlotIdxes.end());
207497ddf49eSJeremy Morse   Slots.push_back(It->second);
207597ddf49eSJeremy Morse 
207697ddf49eSJeremy Morse   // Find anything that has a non-zero offset and add that too.
207797ddf49eSJeremy Morse   for (auto &Pair : MTracker->StackSlotIdxes) {
207897ddf49eSJeremy Morse     // Is offset zero? If so, ignore.
207997ddf49eSJeremy Morse     if (!Pair.first.second)
208097ddf49eSJeremy Morse       continue;
208197ddf49eSJeremy Morse     Slots.push_back(Pair.second);
208297ddf49eSJeremy Morse   }
208397ddf49eSJeremy Morse }
208497ddf49eSJeremy Morse 
placeMLocPHIs(MachineFunction & MF,SmallPtrSetImpl<MachineBasicBlock * > & AllBlocks,FuncValueTable & MInLocs,SmallVectorImpl<MLocTransferMap> & MLocTransfer)208597ddf49eSJeremy Morse void InstrRefBasedLDV::placeMLocPHIs(
208697ddf49eSJeremy Morse     MachineFunction &MF, SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
2087ab49dce0SJeremy Morse     FuncValueTable &MInLocs, SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
208897ddf49eSJeremy Morse   SmallVector<unsigned, 4> StackUnits;
208997ddf49eSJeremy Morse   findStackIndexInterference(StackUnits);
209097ddf49eSJeremy Morse 
2091fbf269c7SJeremy Morse   // To avoid repeatedly running the PHI placement algorithm, leverage the
2092fbf269c7SJeremy Morse   // fact that a def of register MUST also def its register units. Find the
2093fbf269c7SJeremy Morse   // units for registers, place PHIs for them, and then replicate them for
2094fbf269c7SJeremy Morse   // aliasing registers. Some inputs that are never def'd (DBG_PHIs of
2095fbf269c7SJeremy Morse   // arguments) don't lead to register units being tracked, just place PHIs for
209697ddf49eSJeremy Morse   // those registers directly. Stack slots have their own form of "unit",
209797ddf49eSJeremy Morse   // store them to one side.
2098fbf269c7SJeremy Morse   SmallSet<Register, 32> RegUnitsToPHIUp;
209997ddf49eSJeremy Morse   SmallSet<LocIdx, 32> NormalLocsToPHI;
210097ddf49eSJeremy Morse   SmallSet<SpillLocationNo, 32> StackSlots;
2101fbf269c7SJeremy Morse   for (auto Location : MTracker->locations()) {
2102fbf269c7SJeremy Morse     LocIdx L = Location.Idx;
2103fbf269c7SJeremy Morse     if (MTracker->isSpill(L)) {
210497ddf49eSJeremy Morse       StackSlots.insert(MTracker->locIDToSpill(MTracker->LocIdxToLocID[L]));
2105fbf269c7SJeremy Morse       continue;
2106fbf269c7SJeremy Morse     }
2107fbf269c7SJeremy Morse 
2108fbf269c7SJeremy Morse     Register R = MTracker->LocIdxToLocID[L];
2109fbf269c7SJeremy Morse     SmallSet<Register, 8> FoundRegUnits;
2110fbf269c7SJeremy Morse     bool AnyIllegal = false;
2111fbf269c7SJeremy Morse     for (MCRegUnitIterator RUI(R.asMCReg(), TRI); RUI.isValid(); ++RUI) {
2112fbf269c7SJeremy Morse       for (MCRegUnitRootIterator URoot(*RUI, TRI); URoot.isValid(); ++URoot){
2113fbf269c7SJeremy Morse         if (!MTracker->isRegisterTracked(*URoot)) {
2114fbf269c7SJeremy Morse           // Not all roots were loaded into the tracking map: this register
2115fbf269c7SJeremy Morse           // isn't actually def'd anywhere, we only read from it. Generate PHIs
2116fbf269c7SJeremy Morse           // for this reg, but don't iterate units.
2117fbf269c7SJeremy Morse           AnyIllegal = true;
2118fbf269c7SJeremy Morse         } else {
2119fbf269c7SJeremy Morse           FoundRegUnits.insert(*URoot);
2120fbf269c7SJeremy Morse         }
2121fbf269c7SJeremy Morse       }
2122fbf269c7SJeremy Morse     }
2123fbf269c7SJeremy Morse 
2124fbf269c7SJeremy Morse     if (AnyIllegal) {
212597ddf49eSJeremy Morse       NormalLocsToPHI.insert(L);
2126fbf269c7SJeremy Morse       continue;
2127fbf269c7SJeremy Morse     }
2128fbf269c7SJeremy Morse 
2129fbf269c7SJeremy Morse     RegUnitsToPHIUp.insert(FoundRegUnits.begin(), FoundRegUnits.end());
2130fbf269c7SJeremy Morse   }
2131fbf269c7SJeremy Morse 
2132fbf269c7SJeremy Morse   // Lambda to fetch PHIs for a given location, and write into the PHIBlocks
2133fbf269c7SJeremy Morse   // collection.
2134fbf269c7SJeremy Morse   SmallVector<MachineBasicBlock *, 32> PHIBlocks;
2135fbf269c7SJeremy Morse   auto CollectPHIsForLoc = [&](LocIdx L) {
2136fbf269c7SJeremy Morse     // Collect the set of defs.
2137fbf269c7SJeremy Morse     SmallPtrSet<MachineBasicBlock *, 32> DefBlocks;
2138fbf269c7SJeremy Morse     for (unsigned int I = 0; I < OrderToBB.size(); ++I) {
2139fbf269c7SJeremy Morse       MachineBasicBlock *MBB = OrderToBB[I];
2140fbf269c7SJeremy Morse       const auto &TransferFunc = MLocTransfer[MBB->getNumber()];
2141fbf269c7SJeremy Morse       if (TransferFunc.find(L) != TransferFunc.end())
2142fbf269c7SJeremy Morse         DefBlocks.insert(MBB);
2143fbf269c7SJeremy Morse     }
2144fbf269c7SJeremy Morse 
2145fbf269c7SJeremy Morse     // The entry block defs the location too: it's the live-in / argument value.
2146fbf269c7SJeremy Morse     // Only insert if there are other defs though; everything is trivially live
2147fbf269c7SJeremy Morse     // through otherwise.
2148fbf269c7SJeremy Morse     if (!DefBlocks.empty())
2149fbf269c7SJeremy Morse       DefBlocks.insert(&*MF.begin());
2150fbf269c7SJeremy Morse 
2151fbf269c7SJeremy Morse     // Ask the SSA construction algorithm where we should put PHIs. Clear
2152fbf269c7SJeremy Morse     // anything that might have been hanging around from earlier.
2153fbf269c7SJeremy Morse     PHIBlocks.clear();
2154fbf269c7SJeremy Morse     BlockPHIPlacement(AllBlocks, DefBlocks, PHIBlocks);
2155fbf269c7SJeremy Morse   };
2156fbf269c7SJeremy Morse 
215797ddf49eSJeremy Morse   auto InstallPHIsAtLoc = [&PHIBlocks, &MInLocs](LocIdx L) {
2158fbf269c7SJeremy Morse     for (const MachineBasicBlock *MBB : PHIBlocks)
2159fbf269c7SJeremy Morse       MInLocs[MBB->getNumber()][L.asU64()] = ValueIDNum(MBB->getNumber(), 0, L);
216097ddf49eSJeremy Morse   };
216197ddf49eSJeremy Morse 
216297ddf49eSJeremy Morse   // For locations with no reg units, just place PHIs.
216397ddf49eSJeremy Morse   for (LocIdx L : NormalLocsToPHI) {
216497ddf49eSJeremy Morse     CollectPHIsForLoc(L);
216597ddf49eSJeremy Morse     // Install those PHI values into the live-in value array.
216697ddf49eSJeremy Morse     InstallPHIsAtLoc(L);
216797ddf49eSJeremy Morse   }
216897ddf49eSJeremy Morse 
216997ddf49eSJeremy Morse   // For stack slots, calculate PHIs for the equivalent of the units, then
217097ddf49eSJeremy Morse   // install for each index.
217197ddf49eSJeremy Morse   for (SpillLocationNo Slot : StackSlots) {
217297ddf49eSJeremy Morse     for (unsigned Idx : StackUnits) {
217397ddf49eSJeremy Morse       unsigned SpillID = MTracker->getSpillIDWithIdx(Slot, Idx);
217497ddf49eSJeremy Morse       LocIdx L = MTracker->getSpillMLoc(SpillID);
217597ddf49eSJeremy Morse       CollectPHIsForLoc(L);
217697ddf49eSJeremy Morse       InstallPHIsAtLoc(L);
217797ddf49eSJeremy Morse 
217897ddf49eSJeremy Morse       // Find anything that aliases this stack index, install PHIs for it too.
217997ddf49eSJeremy Morse       unsigned Size, Offset;
218097ddf49eSJeremy Morse       std::tie(Size, Offset) = MTracker->StackIdxesToPos[Idx];
218197ddf49eSJeremy Morse       for (auto &Pair : MTracker->StackSlotIdxes) {
218297ddf49eSJeremy Morse         unsigned ThisSize, ThisOffset;
218397ddf49eSJeremy Morse         std::tie(ThisSize, ThisOffset) = Pair.first;
218497ddf49eSJeremy Morse         if (ThisSize + ThisOffset <= Offset || Size + Offset <= ThisOffset)
218597ddf49eSJeremy Morse           continue;
218697ddf49eSJeremy Morse 
218797ddf49eSJeremy Morse         unsigned ThisID = MTracker->getSpillIDWithIdx(Slot, Pair.second);
218897ddf49eSJeremy Morse         LocIdx ThisL = MTracker->getSpillMLoc(ThisID);
218997ddf49eSJeremy Morse         InstallPHIsAtLoc(ThisL);
219097ddf49eSJeremy Morse       }
219197ddf49eSJeremy Morse     }
2192fbf269c7SJeremy Morse   }
2193fbf269c7SJeremy Morse 
2194fbf269c7SJeremy Morse   // For reg units, place PHIs, and then place them for any aliasing registers.
2195fbf269c7SJeremy Morse   for (Register R : RegUnitsToPHIUp) {
2196fbf269c7SJeremy Morse     LocIdx L = MTracker->lookupOrTrackRegister(R);
2197fbf269c7SJeremy Morse     CollectPHIsForLoc(L);
2198fbf269c7SJeremy Morse 
2199fbf269c7SJeremy Morse     // Install those PHI values into the live-in value array.
220097ddf49eSJeremy Morse     InstallPHIsAtLoc(L);
2201fbf269c7SJeremy Morse 
2202fbf269c7SJeremy Morse     // Now find aliases and install PHIs for those.
2203fbf269c7SJeremy Morse     for (MCRegAliasIterator RAI(R, TRI, true); RAI.isValid(); ++RAI) {
2204fbf269c7SJeremy Morse       // Super-registers that are "above" the largest register read/written by
2205fbf269c7SJeremy Morse       // the function will alias, but will not be tracked.
2206fbf269c7SJeremy Morse       if (!MTracker->isRegisterTracked(*RAI))
2207fbf269c7SJeremy Morse         continue;
2208fbf269c7SJeremy Morse 
2209fbf269c7SJeremy Morse       LocIdx AliasLoc = MTracker->lookupOrTrackRegister(*RAI);
221097ddf49eSJeremy Morse       InstallPHIsAtLoc(AliasLoc);
2211fbf269c7SJeremy Morse     }
2212fbf269c7SJeremy Morse   }
2213fbf269c7SJeremy Morse }
2214fbf269c7SJeremy Morse 
buildMLocValueMap(MachineFunction & MF,FuncValueTable & MInLocs,FuncValueTable & MOutLocs,SmallVectorImpl<MLocTransferMap> & MLocTransfer)2215a3936a6cSJeremy Morse void InstrRefBasedLDV::buildMLocValueMap(
2216ab49dce0SJeremy Morse     MachineFunction &MF, FuncValueTable &MInLocs, FuncValueTable &MOutLocs,
2217ae6f7882SJeremy Morse     SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
2218ae6f7882SJeremy Morse   std::priority_queue<unsigned int, std::vector<unsigned int>,
2219ae6f7882SJeremy Morse                       std::greater<unsigned int>>
2220ae6f7882SJeremy Morse       Worklist, Pending;
2221ae6f7882SJeremy Morse 
2222ae6f7882SJeremy Morse   // We track what is on the current and pending worklist to avoid inserting
2223ae6f7882SJeremy Morse   // the same thing twice. We could avoid this with a custom priority queue,
2224ae6f7882SJeremy Morse   // but this is probably not worth it.
2225ae6f7882SJeremy Morse   SmallPtrSet<MachineBasicBlock *, 16> OnPending, OnWorklist;
2226ae6f7882SJeremy Morse 
2227a3936a6cSJeremy Morse   // Initialize worklist with every block to be visited. Also produce list of
2228a3936a6cSJeremy Morse   // all blocks.
2229a3936a6cSJeremy Morse   SmallPtrSet<MachineBasicBlock *, 32> AllBlocks;
2230ae6f7882SJeremy Morse   for (unsigned int I = 0; I < BBToOrder.size(); ++I) {
2231ae6f7882SJeremy Morse     Worklist.push(I);
2232ae6f7882SJeremy Morse     OnWorklist.insert(OrderToBB[I]);
2233a3936a6cSJeremy Morse     AllBlocks.insert(OrderToBB[I]);
2234ae6f7882SJeremy Morse   }
2235ae6f7882SJeremy Morse 
2236a3936a6cSJeremy Morse   // Initialize entry block to PHIs. These represent arguments.
2237a3936a6cSJeremy Morse   for (auto Location : MTracker->locations())
2238a3936a6cSJeremy Morse     MInLocs[0][Location.Idx.asU64()] = ValueIDNum(0, 0, Location.Idx);
2239a3936a6cSJeremy Morse 
2240ae6f7882SJeremy Morse   MTracker->reset();
2241ae6f7882SJeremy Morse 
2242a3936a6cSJeremy Morse   // Start by placing PHIs, using the usual SSA constructor algorithm. Consider
2243a3936a6cSJeremy Morse   // any machine-location that isn't live-through a block to be def'd in that
2244a3936a6cSJeremy Morse   // block.
2245fbf269c7SJeremy Morse   placeMLocPHIs(MF, AllBlocks, MInLocs, MLocTransfer);
2246a3936a6cSJeremy Morse 
2247a3936a6cSJeremy Morse   // Propagate values to eliminate redundant PHIs. At the same time, this
2248a3936a6cSJeremy Morse   // produces the table of Block x Location => Value for the entry to each
2249a3936a6cSJeremy Morse   // block.
2250a3936a6cSJeremy Morse   // The kind of PHIs we can eliminate are, for example, where one path in a
2251a3936a6cSJeremy Morse   // conditional spills and restores a register, and the register still has
2252a3936a6cSJeremy Morse   // the same value once control flow joins, unbeknowns to the PHI placement
2253a3936a6cSJeremy Morse   // code. Propagating values allows us to identify such un-necessary PHIs and
2254a3936a6cSJeremy Morse   // remove them.
2255ae6f7882SJeremy Morse   SmallPtrSet<const MachineBasicBlock *, 16> Visited;
2256ae6f7882SJeremy Morse   while (!Worklist.empty() || !Pending.empty()) {
2257ae6f7882SJeremy Morse     // Vector for storing the evaluated block transfer function.
2258ae6f7882SJeremy Morse     SmallVector<std::pair<LocIdx, ValueIDNum>, 32> ToRemap;
2259ae6f7882SJeremy Morse 
2260ae6f7882SJeremy Morse     while (!Worklist.empty()) {
2261ae6f7882SJeremy Morse       MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
2262ae6f7882SJeremy Morse       CurBB = MBB->getNumber();
2263ae6f7882SJeremy Morse       Worklist.pop();
2264ae6f7882SJeremy Morse 
2265ae6f7882SJeremy Morse       // Join the values in all predecessor blocks.
2266a3936a6cSJeremy Morse       bool InLocsChanged;
2267a3936a6cSJeremy Morse       InLocsChanged = mlocJoin(*MBB, Visited, MOutLocs, MInLocs[CurBB]);
2268ae6f7882SJeremy Morse       InLocsChanged |= Visited.insert(MBB).second;
2269ae6f7882SJeremy Morse 
2270ae6f7882SJeremy Morse       // Don't examine transfer function if we've visited this loc at least
2271ae6f7882SJeremy Morse       // once, and inlocs haven't changed.
2272ae6f7882SJeremy Morse       if (!InLocsChanged)
2273ae6f7882SJeremy Morse         continue;
2274ae6f7882SJeremy Morse 
2275ae6f7882SJeremy Morse       // Load the current set of live-ins into MLocTracker.
2276ae6f7882SJeremy Morse       MTracker->loadFromArray(MInLocs[CurBB], CurBB);
2277ae6f7882SJeremy Morse 
2278ae6f7882SJeremy Morse       // Each element of the transfer function can be a new def, or a read of
2279ae6f7882SJeremy Morse       // a live-in value. Evaluate each element, and store to "ToRemap".
2280ae6f7882SJeremy Morse       ToRemap.clear();
2281ae6f7882SJeremy Morse       for (auto &P : MLocTransfer[CurBB]) {
2282ae6f7882SJeremy Morse         if (P.second.getBlock() == CurBB && P.second.isPHI()) {
2283ae6f7882SJeremy Morse           // This is a movement of whatever was live in. Read it.
2284d9eebe3cSJeremy Morse           ValueIDNum NewID = MTracker->readMLoc(P.second.getLoc());
2285ae6f7882SJeremy Morse           ToRemap.push_back(std::make_pair(P.first, NewID));
2286ae6f7882SJeremy Morse         } else {
2287ae6f7882SJeremy Morse           // It's a def. Just set it.
2288ae6f7882SJeremy Morse           assert(P.second.getBlock() == CurBB);
2289ae6f7882SJeremy Morse           ToRemap.push_back(std::make_pair(P.first, P.second));
2290ae6f7882SJeremy Morse         }
2291ae6f7882SJeremy Morse       }
2292ae6f7882SJeremy Morse 
2293ae6f7882SJeremy Morse       // Commit the transfer function changes into mloc tracker, which
2294ae6f7882SJeremy Morse       // transforms the contents of the MLocTracker into the live-outs.
2295ae6f7882SJeremy Morse       for (auto &P : ToRemap)
2296ae6f7882SJeremy Morse         MTracker->setMLoc(P.first, P.second);
2297ae6f7882SJeremy Morse 
2298ae6f7882SJeremy Morse       // Now copy out-locs from mloc tracker into out-loc vector, checking
2299ae6f7882SJeremy Morse       // whether changes have occurred. These changes can have come from both
2300ae6f7882SJeremy Morse       // the transfer function, and mlocJoin.
2301ae6f7882SJeremy Morse       bool OLChanged = false;
2302ae6f7882SJeremy Morse       for (auto Location : MTracker->locations()) {
2303ae6f7882SJeremy Morse         OLChanged |= MOutLocs[CurBB][Location.Idx.asU64()] != Location.Value;
2304ae6f7882SJeremy Morse         MOutLocs[CurBB][Location.Idx.asU64()] = Location.Value;
2305ae6f7882SJeremy Morse       }
2306ae6f7882SJeremy Morse 
2307ae6f7882SJeremy Morse       MTracker->reset();
2308ae6f7882SJeremy Morse 
2309ae6f7882SJeremy Morse       // No need to examine successors again if out-locs didn't change.
2310ae6f7882SJeremy Morse       if (!OLChanged)
2311ae6f7882SJeremy Morse         continue;
2312ae6f7882SJeremy Morse 
2313ae6f7882SJeremy Morse       // All successors should be visited: put any back-edges on the pending
2314a3936a6cSJeremy Morse       // list for the next pass-through, and any other successors to be
2315a3936a6cSJeremy Morse       // visited this pass, if they're not going to be already.
23169e6d1f4bSKazu Hirata       for (auto *s : MBB->successors()) {
2317ae6f7882SJeremy Morse         // Does branching to this successor represent a back-edge?
2318ae6f7882SJeremy Morse         if (BBToOrder[s] > BBToOrder[MBB]) {
2319ae6f7882SJeremy Morse           // No: visit it during this dataflow iteration.
2320ae6f7882SJeremy Morse           if (OnWorklist.insert(s).second)
2321ae6f7882SJeremy Morse             Worklist.push(BBToOrder[s]);
2322ae6f7882SJeremy Morse         } else {
2323ae6f7882SJeremy Morse           // Yes: visit it on the next iteration.
2324ae6f7882SJeremy Morse           if (OnPending.insert(s).second)
2325ae6f7882SJeremy Morse             Pending.push(BBToOrder[s]);
2326ae6f7882SJeremy Morse         }
2327ae6f7882SJeremy Morse       }
2328ae6f7882SJeremy Morse     }
2329ae6f7882SJeremy Morse 
2330ae6f7882SJeremy Morse     Worklist.swap(Pending);
2331ae6f7882SJeremy Morse     std::swap(OnPending, OnWorklist);
2332ae6f7882SJeremy Morse     OnPending.clear();
2333ae6f7882SJeremy Morse     // At this point, pending must be empty, since it was just the empty
2334ae6f7882SJeremy Morse     // worklist
2335ae6f7882SJeremy Morse     assert(Pending.empty() && "Pending should be empty");
2336ae6f7882SJeremy Morse   }
2337ae6f7882SJeremy Morse 
2338a3936a6cSJeremy Morse   // Once all the live-ins don't change on mlocJoin(), we've eliminated all
2339a3936a6cSJeremy Morse   // redundant PHIs.
2340a3936a6cSJeremy Morse }
2341a3936a6cSJeremy Morse 
BlockPHIPlacement(const SmallPtrSetImpl<MachineBasicBlock * > & AllBlocks,const SmallPtrSetImpl<MachineBasicBlock * > & DefBlocks,SmallVectorImpl<MachineBasicBlock * > & PHIBlocks)2342a3936a6cSJeremy Morse void InstrRefBasedLDV::BlockPHIPlacement(
2343a3936a6cSJeremy Morse     const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
2344a3936a6cSJeremy Morse     const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks,
2345a3936a6cSJeremy Morse     SmallVectorImpl<MachineBasicBlock *> &PHIBlocks) {
2346a3936a6cSJeremy Morse   // Apply IDF calculator to the designated set of location defs, storing
2347a3936a6cSJeremy Morse   // required PHIs into PHIBlocks. Uses the dominator tree stored in the
2348a3936a6cSJeremy Morse   // InstrRefBasedLDV object.
2349e0b11c76SMarkus Böck   IDFCalculatorBase<MachineBasicBlock, false> IDF(DomTree->getBase());
2350a3936a6cSJeremy Morse 
2351a3936a6cSJeremy Morse   IDF.setLiveInBlocks(AllBlocks);
2352a3936a6cSJeremy Morse   IDF.setDefiningBlocks(DefBlocks);
2353a3936a6cSJeremy Morse   IDF.calculate(PHIBlocks);
2354ae6f7882SJeremy Morse }
2355ae6f7882SJeremy Morse 
pickVPHILoc(const MachineBasicBlock & MBB,const DebugVariable & Var,const LiveIdxT & LiveOuts,FuncValueTable & MOutLocs,const SmallVectorImpl<const MachineBasicBlock * > & BlockOrders)2356b5426cedSJeremy Morse Optional<ValueIDNum> InstrRefBasedLDV::pickVPHILoc(
2357b5426cedSJeremy Morse     const MachineBasicBlock &MBB, const DebugVariable &Var,
2358ab49dce0SJeremy Morse     const LiveIdxT &LiveOuts, FuncValueTable &MOutLocs,
2359b5426cedSJeremy Morse     const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) {
2360ae6f7882SJeremy Morse   // Collect a set of locations from predecessor where its live-out value can
2361ae6f7882SJeremy Morse   // be found.
2362ae6f7882SJeremy Morse   SmallVector<SmallVector<LocIdx, 4>, 8> Locs;
2363b5426cedSJeremy Morse   SmallVector<const DbgValueProperties *, 4> Properties;
2364ae6f7882SJeremy Morse   unsigned NumLocs = MTracker->getNumLocs();
2365b5426cedSJeremy Morse 
2366b5426cedSJeremy Morse   // No predecessors means no PHIs.
2367b5426cedSJeremy Morse   if (BlockOrders.empty())
2368b5426cedSJeremy Morse     return None;
2369ae6f7882SJeremy Morse 
23709e6d1f4bSKazu Hirata   for (const auto *p : BlockOrders) {
2371ae6f7882SJeremy Morse     unsigned ThisBBNum = p->getNumber();
237289950adeSJeremy Morse     auto OutValIt = LiveOuts.find(p);
237389950adeSJeremy Morse     if (OutValIt == LiveOuts.end())
237489950adeSJeremy Morse       // If we have a predecessor not in scope, we'll never find a PHI position.
2375b5426cedSJeremy Morse       return None;
237689950adeSJeremy Morse     const DbgValue &OutVal = *OutValIt->second;
2377ae6f7882SJeremy Morse 
2378ae6f7882SJeremy Morse     if (OutVal.Kind == DbgValue::Const || OutVal.Kind == DbgValue::NoVal)
2379ae6f7882SJeremy Morse       // Consts and no-values cannot have locations we can join on.
2380b5426cedSJeremy Morse       return None;
2381ae6f7882SJeremy Morse 
2382b5426cedSJeremy Morse     Properties.push_back(&OutVal.Properties);
2383b5426cedSJeremy Morse 
2384b5426cedSJeremy Morse     // Create new empty vector of locations.
2385b5426cedSJeremy Morse     Locs.resize(Locs.size() + 1);
2386b5426cedSJeremy Morse 
2387b5426cedSJeremy Morse     // If the live-in value is a def, find the locations where that value is
2388b5426cedSJeremy Morse     // present. Do the same for VPHIs where we know the VPHI value.
2389b5426cedSJeremy Morse     if (OutVal.Kind == DbgValue::Def ||
2390b5426cedSJeremy Morse         (OutVal.Kind == DbgValue::VPHI && OutVal.BlockNo != MBB.getNumber() &&
2391b5426cedSJeremy Morse          OutVal.ID != ValueIDNum::EmptyValue)) {
2392ae6f7882SJeremy Morse       ValueIDNum ValToLookFor = OutVal.ID;
2393ae6f7882SJeremy Morse       // Search the live-outs of the predecessor for the specified value.
2394ae6f7882SJeremy Morse       for (unsigned int I = 0; I < NumLocs; ++I) {
2395ae6f7882SJeremy Morse         if (MOutLocs[ThisBBNum][I] == ValToLookFor)
2396ae6f7882SJeremy Morse           Locs.back().push_back(LocIdx(I));
2397ae6f7882SJeremy Morse       }
2398b5426cedSJeremy Morse     } else {
2399b5426cedSJeremy Morse       assert(OutVal.Kind == DbgValue::VPHI);
2400b5426cedSJeremy Morse       // For VPHIs where we don't know the location, we definitely can't find
2401b5426cedSJeremy Morse       // a join loc.
2402b5426cedSJeremy Morse       if (OutVal.BlockNo != MBB.getNumber())
2403b5426cedSJeremy Morse         return None;
2404b5426cedSJeremy Morse 
2405b5426cedSJeremy Morse       // Otherwise: this is a VPHI on a backedge feeding back into itself, i.e.
2406b5426cedSJeremy Morse       // a value that's live-through the whole loop. (It has to be a backedge,
2407b5426cedSJeremy Morse       // because a block can't dominate itself). We can accept as a PHI location
2408b5426cedSJeremy Morse       // any location where the other predecessors agree, _and_ the machine
2409b5426cedSJeremy Morse       // locations feed back into themselves. Therefore, add all self-looping
2410b5426cedSJeremy Morse       // machine-value PHI locations.
2411b5426cedSJeremy Morse       for (unsigned int I = 0; I < NumLocs; ++I) {
2412b5426cedSJeremy Morse         ValueIDNum MPHI(MBB.getNumber(), 0, LocIdx(I));
2413b5426cedSJeremy Morse         if (MOutLocs[ThisBBNum][I] == MPHI)
2414b5426cedSJeremy Morse           Locs.back().push_back(LocIdx(I));
2415b5426cedSJeremy Morse       }
2416b5426cedSJeremy Morse     }
2417ae6f7882SJeremy Morse   }
2418ae6f7882SJeremy Morse 
2419b5426cedSJeremy Morse   // We should have found locations for all predecessors, or returned.
2420b5426cedSJeremy Morse   assert(Locs.size() == BlockOrders.size());
2421ae6f7882SJeremy Morse 
2422b5426cedSJeremy Morse   // Check that all properties are the same. We can't pick a location if they're
2423b5426cedSJeremy Morse   // not.
2424b5426cedSJeremy Morse   const DbgValueProperties *Properties0 = Properties[0];
24259e6d1f4bSKazu Hirata   for (const auto *Prop : Properties)
2426b5426cedSJeremy Morse     if (*Prop != *Properties0)
2427b5426cedSJeremy Morse       return None;
2428b5426cedSJeremy Morse 
2429ae6f7882SJeremy Morse   // Starting with the first set of locations, take the intersection with
2430ae6f7882SJeremy Morse   // subsequent sets.
2431b5426cedSJeremy Morse   SmallVector<LocIdx, 4> CandidateLocs = Locs[0];
2432b5426cedSJeremy Morse   for (unsigned int I = 1; I < Locs.size(); ++I) {
2433b5426cedSJeremy Morse     auto &LocVec = Locs[I];
2434b5426cedSJeremy Morse     SmallVector<LocIdx, 4> NewCandidates;
2435b5426cedSJeremy Morse     std::set_intersection(CandidateLocs.begin(), CandidateLocs.end(),
2436b5426cedSJeremy Morse                           LocVec.begin(), LocVec.end(), std::inserter(NewCandidates, NewCandidates.begin()));
2437b5426cedSJeremy Morse     CandidateLocs = NewCandidates;
2438ae6f7882SJeremy Morse   }
2439b5426cedSJeremy Morse   if (CandidateLocs.empty())
2440ae6f7882SJeremy Morse     return None;
2441ae6f7882SJeremy Morse 
2442ae6f7882SJeremy Morse   // We now have a set of LocIdxes that contain the right output value in
2443ae6f7882SJeremy Morse   // each of the predecessors. Pick the lowest; if there's a register loc,
2444ae6f7882SJeremy Morse   // that'll be it.
2445b5426cedSJeremy Morse   LocIdx L = *CandidateLocs.begin();
2446ae6f7882SJeremy Morse 
2447ae6f7882SJeremy Morse   // Return a PHI-value-number for the found location.
2448ae6f7882SJeremy Morse   ValueIDNum PHIVal = {(unsigned)MBB.getNumber(), 0, L};
2449b5426cedSJeremy Morse   return PHIVal;
2450ae6f7882SJeremy Morse }
2451ae6f7882SJeremy Morse 
vlocJoin(MachineBasicBlock & MBB,LiveIdxT & VLOCOutLocs,SmallPtrSet<const MachineBasicBlock *,8> & BlocksToExplore,DbgValue & LiveIn)2452b5426cedSJeremy Morse bool InstrRefBasedLDV::vlocJoin(
2453849b1794SJeremy Morse     MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs,
2454ae6f7882SJeremy Morse     SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
245589950adeSJeremy Morse     DbgValue &LiveIn) {
2456ae6f7882SJeremy Morse   LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
2457ae6f7882SJeremy Morse   bool Changed = false;
2458ae6f7882SJeremy Morse 
2459ae6f7882SJeremy Morse   // Order predecessors by RPOT order, for exploring them in that order.
24607925aa09SKazu Hirata   SmallVector<MachineBasicBlock *, 8> BlockOrders(MBB.predecessors());
2461ae6f7882SJeremy Morse 
2462ae6f7882SJeremy Morse   auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
2463ae6f7882SJeremy Morse     return BBToOrder[A] < BBToOrder[B];
2464ae6f7882SJeremy Morse   };
2465ae6f7882SJeremy Morse 
24669bcc0d10SKazu Hirata   llvm::sort(BlockOrders, Cmp);
2467ae6f7882SJeremy Morse 
2468ae6f7882SJeremy Morse   unsigned CurBlockRPONum = BBToOrder[&MBB];
2469ae6f7882SJeremy Morse 
2470b5426cedSJeremy Morse   // Collect all the incoming DbgValues for this variable, from predecessor
2471b5426cedSJeremy Morse   // live-out values.
2472ae6f7882SJeremy Morse   SmallVector<InValueT, 8> Values;
2473ae6f7882SJeremy Morse   bool Bail = false;
2474ea970661SJeremy Morse   int BackEdgesStart = 0;
24759e6d1f4bSKazu Hirata   for (auto *p : BlockOrders) {
2476ae6f7882SJeremy Morse     // If the predecessor isn't in scope / to be explored, we'll never be
2477ae6f7882SJeremy Morse     // able to join any locations.
2478805d5959SKazu Hirata     if (!BlocksToExplore.contains(p)) {
2479ae6f7882SJeremy Morse       Bail = true;
2480ae6f7882SJeremy Morse       break;
2481ae6f7882SJeremy Morse     }
2482ae6f7882SJeremy Morse 
248389950adeSJeremy Morse     // All Live-outs will have been initialized.
248489950adeSJeremy Morse     DbgValue &OutLoc = *VLOCOutLocs.find(p)->second;
2485ae6f7882SJeremy Morse 
2486ae6f7882SJeremy Morse     // Keep track of where back-edges begin in the Values vector. Relies on
2487ae6f7882SJeremy Morse     // BlockOrders being sorted by RPO.
2488ae6f7882SJeremy Morse     unsigned ThisBBRPONum = BBToOrder[p];
2489ae6f7882SJeremy Morse     if (ThisBBRPONum < CurBlockRPONum)
2490ae6f7882SJeremy Morse       ++BackEdgesStart;
2491ae6f7882SJeremy Morse 
249289950adeSJeremy Morse     Values.push_back(std::make_pair(p, &OutLoc));
2493ae6f7882SJeremy Morse   }
2494ae6f7882SJeremy Morse 
2495ae6f7882SJeremy Morse   // If there were no values, or one of the predecessors couldn't have a
2496ae6f7882SJeremy Morse   // value, then give up immediately. It's not safe to produce a live-in
2497b5426cedSJeremy Morse   // value. Leave as whatever it was before.
249889950adeSJeremy Morse   if (Bail || Values.size() == 0)
249989950adeSJeremy Morse     return false;
2500ae6f7882SJeremy Morse 
2501ae6f7882SJeremy Morse   // All (non-entry) blocks have at least one non-backedge predecessor.
2502ae6f7882SJeremy Morse   // Pick the variable value from the first of these, to compare against
2503ae6f7882SJeremy Morse   // all others.
2504ae6f7882SJeremy Morse   const DbgValue &FirstVal = *Values[0].second;
2505ae6f7882SJeremy Morse 
2506b5426cedSJeremy Morse   // If the old live-in value is not a PHI then either a) no PHI is needed
2507b5426cedSJeremy Morse   // here, or b) we eliminated the PHI that was here. If so, we can just
250889950adeSJeremy Morse   // propagate in the first parent's incoming value.
250989950adeSJeremy Morse   if (LiveIn.Kind != DbgValue::VPHI || LiveIn.BlockNo != MBB.getNumber()) {
251089950adeSJeremy Morse     Changed = LiveIn != FirstVal;
251189950adeSJeremy Morse     if (Changed)
251289950adeSJeremy Morse       LiveIn = FirstVal;
251389950adeSJeremy Morse     return Changed;
2514ae6f7882SJeremy Morse   }
2515ae6f7882SJeremy Morse 
2516b5426cedSJeremy Morse   // Scan for variable values that can never be resolved: if they have
2517b5426cedSJeremy Morse   // different DIExpressions, different indirectness, or are mixed constants /
2518b5426cedSJeremy Morse   // non-constants.
2519b5426cedSJeremy Morse   for (auto &V : Values) {
2520b5426cedSJeremy Morse     if (V.second->Properties != FirstVal.Properties)
252189950adeSJeremy Morse       return false;
2522b5426cedSJeremy Morse     if (V.second->Kind == DbgValue::NoVal)
252389950adeSJeremy Morse       return false;
2524b5426cedSJeremy Morse     if (V.second->Kind == DbgValue::Const && FirstVal.Kind != DbgValue::Const)
252589950adeSJeremy Morse       return false;
2526b5426cedSJeremy Morse   }
2527b5426cedSJeremy Morse 
2528b5426cedSJeremy Morse   // Try to eliminate this PHI. Do the incoming values all agree?
2529ae6f7882SJeremy Morse   bool Disagree = false;
2530ae6f7882SJeremy Morse   for (auto &V : Values) {
2531ae6f7882SJeremy Morse     if (*V.second == FirstVal)
2532ae6f7882SJeremy Morse       continue; // No disagreement.
2533ae6f7882SJeremy Morse 
2534b5426cedSJeremy Morse     // Eliminate if a backedge feeds a VPHI back into itself.
2535b5426cedSJeremy Morse     if (V.second->Kind == DbgValue::VPHI &&
2536b5426cedSJeremy Morse         V.second->BlockNo == MBB.getNumber() &&
2537b5426cedSJeremy Morse         // Is this a backedge?
2538b5426cedSJeremy Morse         std::distance(Values.begin(), &V) >= BackEdgesStart)
2539b5426cedSJeremy Morse       continue;
2540b5426cedSJeremy Morse 
2541ae6f7882SJeremy Morse     Disagree = true;
2542ae6f7882SJeremy Morse   }
2543ae6f7882SJeremy Morse 
2544b5426cedSJeremy Morse   // No disagreement -> live-through value.
2545b5426cedSJeremy Morse   if (!Disagree) {
254689950adeSJeremy Morse     Changed = LiveIn != FirstVal;
254789950adeSJeremy Morse     if (Changed)
254889950adeSJeremy Morse       LiveIn = FirstVal;
254989950adeSJeremy Morse     return Changed;
2550ae6f7882SJeremy Morse   } else {
2551b5426cedSJeremy Morse     // Otherwise use a VPHI.
255289950adeSJeremy Morse     DbgValue VPHI(MBB.getNumber(), FirstVal.Properties, DbgValue::VPHI);
255389950adeSJeremy Morse     Changed = LiveIn != VPHI;
255489950adeSJeremy Morse     if (Changed)
255589950adeSJeremy Morse       LiveIn = VPHI;
2556b5426cedSJeremy Morse     return Changed;
2557ae6f7882SJeremy Morse   }
255889950adeSJeremy Morse }
2559ae6f7882SJeremy Morse 
getBlocksForScope(const DILocation * DILoc,SmallPtrSetImpl<const MachineBasicBlock * > & BlocksToExplore,const SmallPtrSetImpl<MachineBasicBlock * > & AssignBlocks)25604a2cb013SJeremy Morse void InstrRefBasedLDV::getBlocksForScope(
25614a2cb013SJeremy Morse     const DILocation *DILoc,
25624a2cb013SJeremy Morse     SmallPtrSetImpl<const MachineBasicBlock *> &BlocksToExplore,
25634a2cb013SJeremy Morse     const SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks) {
25644a2cb013SJeremy Morse   // Get the set of "normal" in-lexical-scope blocks.
25654a2cb013SJeremy Morse   LS.getMachineBasicBlocks(DILoc, BlocksToExplore);
25664a2cb013SJeremy Morse 
25674a2cb013SJeremy Morse   // VarLoc LiveDebugValues tracks variable locations that are defined in
25684a2cb013SJeremy Morse   // blocks not in scope. This is something we could legitimately ignore, but
25694a2cb013SJeremy Morse   // lets allow it for now for the sake of coverage.
25704a2cb013SJeremy Morse   BlocksToExplore.insert(AssignBlocks.begin(), AssignBlocks.end());
25714a2cb013SJeremy Morse 
25724a2cb013SJeremy Morse   // Storage for artificial blocks we intend to add to BlocksToExplore.
25734a2cb013SJeremy Morse   DenseSet<const MachineBasicBlock *> ToAdd;
25744a2cb013SJeremy Morse 
25754a2cb013SJeremy Morse   // To avoid needlessly dropping large volumes of variable locations, propagate
25764a2cb013SJeremy Morse   // variables through aritifical blocks, i.e. those that don't have any
25774a2cb013SJeremy Morse   // instructions in scope at all. To accurately replicate VarLoc
25784a2cb013SJeremy Morse   // LiveDebugValues, this means exploring all artificial successors too.
25794a2cb013SJeremy Morse   // Perform a depth-first-search to enumerate those blocks.
25809e6d1f4bSKazu Hirata   for (const auto *MBB : BlocksToExplore) {
25814a2cb013SJeremy Morse     // Depth-first-search state: each node is a block and which successor
25824a2cb013SJeremy Morse     // we're currently exploring.
25834a2cb013SJeremy Morse     SmallVector<std::pair<const MachineBasicBlock *,
25844a2cb013SJeremy Morse                           MachineBasicBlock::const_succ_iterator>,
25854a2cb013SJeremy Morse                 8>
25864a2cb013SJeremy Morse         DFS;
25874a2cb013SJeremy Morse 
25884a2cb013SJeremy Morse     // Find any artificial successors not already tracked.
25894a2cb013SJeremy Morse     for (auto *succ : MBB->successors()) {
25904a2cb013SJeremy Morse       if (BlocksToExplore.count(succ))
25914a2cb013SJeremy Morse         continue;
25924a2cb013SJeremy Morse       if (!ArtificialBlocks.count(succ))
25934a2cb013SJeremy Morse         continue;
25944a2cb013SJeremy Morse       ToAdd.insert(succ);
25954a2cb013SJeremy Morse       DFS.push_back({succ, succ->succ_begin()});
25964a2cb013SJeremy Morse     }
25974a2cb013SJeremy Morse 
25984a2cb013SJeremy Morse     // Search all those blocks, depth first.
25994a2cb013SJeremy Morse     while (!DFS.empty()) {
26004a2cb013SJeremy Morse       const MachineBasicBlock *CurBB = DFS.back().first;
26014a2cb013SJeremy Morse       MachineBasicBlock::const_succ_iterator &CurSucc = DFS.back().second;
26024a2cb013SJeremy Morse       // Walk back if we've explored this blocks successors to the end.
26034a2cb013SJeremy Morse       if (CurSucc == CurBB->succ_end()) {
26044a2cb013SJeremy Morse         DFS.pop_back();
26054a2cb013SJeremy Morse         continue;
26064a2cb013SJeremy Morse       }
26074a2cb013SJeremy Morse 
26084a2cb013SJeremy Morse       // If the current successor is artificial and unexplored, descend into
26094a2cb013SJeremy Morse       // it.
26104a2cb013SJeremy Morse       if (!ToAdd.count(*CurSucc) && ArtificialBlocks.count(*CurSucc)) {
26114a2cb013SJeremy Morse         ToAdd.insert(*CurSucc);
26124a2cb013SJeremy Morse         DFS.push_back({*CurSucc, (*CurSucc)->succ_begin()});
26134a2cb013SJeremy Morse         continue;
26144a2cb013SJeremy Morse       }
26154a2cb013SJeremy Morse 
26164a2cb013SJeremy Morse       ++CurSucc;
26174a2cb013SJeremy Morse     }
26184a2cb013SJeremy Morse   };
26194a2cb013SJeremy Morse 
26204a2cb013SJeremy Morse   BlocksToExplore.insert(ToAdd.begin(), ToAdd.end());
26214a2cb013SJeremy Morse }
26224a2cb013SJeremy Morse 
buildVLocValueMap(const DILocation * DILoc,const SmallSet<DebugVariable,4> & VarsWeCareAbout,SmallPtrSetImpl<MachineBasicBlock * > & AssignBlocks,LiveInsT & Output,FuncValueTable & MOutLocs,FuncValueTable & MInLocs,SmallVectorImpl<VLocTracker> & AllTheVLocs)26234a2cb013SJeremy Morse void InstrRefBasedLDV::buildVLocValueMap(
26244a2cb013SJeremy Morse     const DILocation *DILoc, const SmallSet<DebugVariable, 4> &VarsWeCareAbout,
2625ae6f7882SJeremy Morse     SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, LiveInsT &Output,
2626ab49dce0SJeremy Morse     FuncValueTable &MOutLocs, FuncValueTable &MInLocs,
2627ae6f7882SJeremy Morse     SmallVectorImpl<VLocTracker> &AllTheVLocs) {
2628b5426cedSJeremy Morse   // This method is much like buildMLocValueMap: but focuses on a single
2629ae6f7882SJeremy Morse   // LexicalScope at a time. Pick out a set of blocks and variables that are
2630ae6f7882SJeremy Morse   // to have their value assignments solved, then run our dataflow algorithm
2631ae6f7882SJeremy Morse   // until a fixedpoint is reached.
2632ae6f7882SJeremy Morse   std::priority_queue<unsigned int, std::vector<unsigned int>,
2633ae6f7882SJeremy Morse                       std::greater<unsigned int>>
2634ae6f7882SJeremy Morse       Worklist, Pending;
2635ae6f7882SJeremy Morse   SmallPtrSet<MachineBasicBlock *, 16> OnWorklist, OnPending;
2636ae6f7882SJeremy Morse 
2637ae6f7882SJeremy Morse   // The set of blocks we'll be examining.
2638ae6f7882SJeremy Morse   SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
2639ae6f7882SJeremy Morse 
2640ae6f7882SJeremy Morse   // The order in which to examine them (RPO).
2641ae6f7882SJeremy Morse   SmallVector<MachineBasicBlock *, 8> BlockOrders;
2642ae6f7882SJeremy Morse 
2643ae6f7882SJeremy Morse   // RPO ordering function.
2644ae6f7882SJeremy Morse   auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
2645ae6f7882SJeremy Morse     return BBToOrder[A] < BBToOrder[B];
2646ae6f7882SJeremy Morse   };
2647ae6f7882SJeremy Morse 
26484a2cb013SJeremy Morse   getBlocksForScope(DILoc, BlocksToExplore, AssignBlocks);
2649ae6f7882SJeremy Morse 
2650ae6f7882SJeremy Morse   // Single block scope: not interesting! No propagation at all. Note that
2651ae6f7882SJeremy Morse   // this could probably go above ArtificialBlocks without damage, but
2652ae6f7882SJeremy Morse   // that then produces output differences from original-live-debug-values,
2653ae6f7882SJeremy Morse   // which propagates from a single block into many artificial ones.
2654ae6f7882SJeremy Morse   if (BlocksToExplore.size() == 1)
2655ae6f7882SJeremy Morse     return;
2656ae6f7882SJeremy Morse 
265789950adeSJeremy Morse   // Convert a const set to a non-const set. LexicalScopes
265889950adeSJeremy Morse   // getMachineBasicBlocks returns const MBB pointers, IDF wants mutable ones.
265989950adeSJeremy Morse   // (Neither of them mutate anything).
266089950adeSJeremy Morse   SmallPtrSet<MachineBasicBlock *, 8> MutBlocksToExplore;
266189950adeSJeremy Morse   for (const auto *MBB : BlocksToExplore)
266289950adeSJeremy Morse     MutBlocksToExplore.insert(const_cast<MachineBasicBlock *>(MBB));
266389950adeSJeremy Morse 
2664ae6f7882SJeremy Morse   // Picks out relevants blocks RPO order and sort them.
26659e6d1f4bSKazu Hirata   for (const auto *MBB : BlocksToExplore)
2666ae6f7882SJeremy Morse     BlockOrders.push_back(const_cast<MachineBasicBlock *>(MBB));
2667ae6f7882SJeremy Morse 
26689bcc0d10SKazu Hirata   llvm::sort(BlockOrders, Cmp);
2669ae6f7882SJeremy Morse   unsigned NumBlocks = BlockOrders.size();
2670ae6f7882SJeremy Morse 
2671ae6f7882SJeremy Morse   // Allocate some vectors for storing the live ins and live outs. Large.
267289950adeSJeremy Morse   SmallVector<DbgValue, 32> LiveIns, LiveOuts;
267389950adeSJeremy Morse   LiveIns.reserve(NumBlocks);
267489950adeSJeremy Morse   LiveOuts.reserve(NumBlocks);
2675ae6f7882SJeremy Morse 
2676b5426cedSJeremy Morse   // Initialize all values to start as NoVals. This signifies "it's live
2677b5426cedSJeremy Morse   // through, but we don't know what it is".
2678b5426cedSJeremy Morse   DbgValueProperties EmptyProperties(EmptyExpr, false);
267989950adeSJeremy Morse   for (unsigned int I = 0; I < NumBlocks; ++I) {
268089950adeSJeremy Morse     DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal);
268189950adeSJeremy Morse     LiveIns.push_back(EmptyDbgValue);
268289950adeSJeremy Morse     LiveOuts.push_back(EmptyDbgValue);
2683b5426cedSJeremy Morse   }
2684b5426cedSJeremy Morse 
2685ae6f7882SJeremy Morse   // Produce by-MBB indexes of live-in/live-outs, to ease lookup within
2686ae6f7882SJeremy Morse   // vlocJoin.
2687ae6f7882SJeremy Morse   LiveIdxT LiveOutIdx, LiveInIdx;
2688ae6f7882SJeremy Morse   LiveOutIdx.reserve(NumBlocks);
2689ae6f7882SJeremy Morse   LiveInIdx.reserve(NumBlocks);
2690ae6f7882SJeremy Morse   for (unsigned I = 0; I < NumBlocks; ++I) {
2691ae6f7882SJeremy Morse     LiveOutIdx[BlockOrders[I]] = &LiveOuts[I];
2692ae6f7882SJeremy Morse     LiveInIdx[BlockOrders[I]] = &LiveIns[I];
2693ae6f7882SJeremy Morse   }
2694ae6f7882SJeremy Morse 
269589950adeSJeremy Morse   // Loop over each variable and place PHIs for it, then propagate values
269689950adeSJeremy Morse   // between blocks. This keeps the locality of working on one lexical scope at
269789950adeSJeremy Morse   // at time, but avoids re-processing variable values because some other
269889950adeSJeremy Morse   // variable has been assigned.
26999e6d1f4bSKazu Hirata   for (const auto &Var : VarsWeCareAbout) {
270089950adeSJeremy Morse     // Re-initialize live-ins and live-outs, to clear the remains of previous
270189950adeSJeremy Morse     // variables live-ins / live-outs.
270289950adeSJeremy Morse     for (unsigned int I = 0; I < NumBlocks; ++I) {
270389950adeSJeremy Morse       DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal);
270489950adeSJeremy Morse       LiveIns[I] = EmptyDbgValue;
270589950adeSJeremy Morse       LiveOuts[I] = EmptyDbgValue;
2706849b1794SJeremy Morse     }
2707849b1794SJeremy Morse 
2708b5426cedSJeremy Morse     // Place PHIs for variable values, using the LLVM IDF calculator.
2709b5426cedSJeremy Morse     // Collect the set of blocks where variables are def'd.
2710b5426cedSJeremy Morse     SmallPtrSet<MachineBasicBlock *, 32> DefBlocks;
2711b5426cedSJeremy Morse     for (const MachineBasicBlock *ExpMBB : BlocksToExplore) {
2712b5426cedSJeremy Morse       auto &TransferFunc = AllTheVLocs[ExpMBB->getNumber()].Vars;
2713b5426cedSJeremy Morse       if (TransferFunc.find(Var) != TransferFunc.end())
2714b5426cedSJeremy Morse         DefBlocks.insert(const_cast<MachineBasicBlock *>(ExpMBB));
2715b5426cedSJeremy Morse     }
2716b5426cedSJeremy Morse 
2717b5426cedSJeremy Morse     SmallVector<MachineBasicBlock *, 32> PHIBlocks;
2718b5426cedSJeremy Morse 
2719c703d77aSJeremy Morse     // Request the set of PHIs we should insert for this variable. If there's
2720c703d77aSJeremy Morse     // only one value definition, things are very simple.
2721c703d77aSJeremy Morse     if (DefBlocks.size() == 1) {
2722c703d77aSJeremy Morse       placePHIsForSingleVarDefinition(MutBlocksToExplore, *DefBlocks.begin(),
2723c703d77aSJeremy Morse                                       AllTheVLocs, Var, Output);
2724c703d77aSJeremy Morse       continue;
2725c703d77aSJeremy Morse     }
2726c703d77aSJeremy Morse 
2727c703d77aSJeremy Morse     // Otherwise: we need to place PHIs through SSA and propagate values.
2728b5426cedSJeremy Morse     BlockPHIPlacement(MutBlocksToExplore, DefBlocks, PHIBlocks);
2729b5426cedSJeremy Morse 
2730b5426cedSJeremy Morse     // Insert PHIs into the per-block live-in tables for this variable.
2731b5426cedSJeremy Morse     for (MachineBasicBlock *PHIMBB : PHIBlocks) {
2732b5426cedSJeremy Morse       unsigned BlockNo = PHIMBB->getNumber();
273389950adeSJeremy Morse       DbgValue *LiveIn = LiveInIdx[PHIMBB];
273489950adeSJeremy Morse       *LiveIn = DbgValue(BlockNo, EmptyProperties, DbgValue::VPHI);
2735b5426cedSJeremy Morse     }
2736b5426cedSJeremy Morse 
2737ae6f7882SJeremy Morse     for (auto *MBB : BlockOrders) {
2738ae6f7882SJeremy Morse       Worklist.push(BBToOrder[MBB]);
2739ae6f7882SJeremy Morse       OnWorklist.insert(MBB);
2740ae6f7882SJeremy Morse     }
2741ae6f7882SJeremy Morse 
274289950adeSJeremy Morse     // Iterate over all the blocks we selected, propagating the variables value.
274389950adeSJeremy Morse     // This loop does two things:
2744b5426cedSJeremy Morse     //  * Eliminates un-necessary VPHIs in vlocJoin,
2745b5426cedSJeremy Morse     //  * Evaluates the blocks transfer function (i.e. variable assignments) and
2746b5426cedSJeremy Morse     //    stores the result to the blocks live-outs.
274789950adeSJeremy Morse     // Always evaluate the transfer function on the first iteration, and when
274889950adeSJeremy Morse     // the live-ins change thereafter.
2749ae6f7882SJeremy Morse     bool FirstTrip = true;
2750ae6f7882SJeremy Morse     while (!Worklist.empty() || !Pending.empty()) {
2751ae6f7882SJeremy Morse       while (!Worklist.empty()) {
2752ae6f7882SJeremy Morse         auto *MBB = OrderToBB[Worklist.top()];
2753ae6f7882SJeremy Morse         CurBB = MBB->getNumber();
2754ae6f7882SJeremy Morse         Worklist.pop();
2755ae6f7882SJeremy Morse 
275689950adeSJeremy Morse         auto LiveInsIt = LiveInIdx.find(MBB);
275789950adeSJeremy Morse         assert(LiveInsIt != LiveInIdx.end());
275889950adeSJeremy Morse         DbgValue *LiveIn = LiveInsIt->second;
2759ae6f7882SJeremy Morse 
2760ae6f7882SJeremy Morse         // Join values from predecessors. Updates LiveInIdx, and writes output
2761ae6f7882SJeremy Morse         // into JoinedInLocs.
2762849b1794SJeremy Morse         bool InLocsChanged =
27638dda516bSJeremy Morse             vlocJoin(*MBB, LiveOutIdx, BlocksToExplore, *LiveIn);
2764ae6f7882SJeremy Morse 
2765b5426cedSJeremy Morse         SmallVector<const MachineBasicBlock *, 8> Preds;
2766b5426cedSJeremy Morse         for (const auto *Pred : MBB->predecessors())
2767b5426cedSJeremy Morse           Preds.push_back(Pred);
2768ae6f7882SJeremy Morse 
276989950adeSJeremy Morse         // If this block's live-in value is a VPHI, try to pick a machine-value
277089950adeSJeremy Morse         // for it. This makes the machine-value available and propagated
277189950adeSJeremy Morse         // through all blocks by the time value propagation finishes. We can't
277289950adeSJeremy Morse         // do this any earlier as it needs to read the block live-outs.
277389950adeSJeremy Morse         if (LiveIn->Kind == DbgValue::VPHI && LiveIn->BlockNo == (int)CurBB) {
2774b5426cedSJeremy Morse           // There's a small possibility that on a preceeding path, a VPHI is
2775b5426cedSJeremy Morse           // eliminated and transitions from VPHI-with-location to
2776b5426cedSJeremy Morse           // live-through-value. As a result, the selected location of any VPHI
2777b5426cedSJeremy Morse           // might change, so we need to re-compute it on each iteration.
277889950adeSJeremy Morse           Optional<ValueIDNum> ValueNum =
277989950adeSJeremy Morse               pickVPHILoc(*MBB, Var, LiveOutIdx, MOutLocs, Preds);
2780ae6f7882SJeremy Morse 
2781b5426cedSJeremy Morse           if (ValueNum) {
278289950adeSJeremy Morse             InLocsChanged |= LiveIn->ID != *ValueNum;
278389950adeSJeremy Morse             LiveIn->ID = *ValueNum;
2784b5426cedSJeremy Morse           }
2785b5426cedSJeremy Morse         }
2786b5426cedSJeremy Morse 
2787b5426cedSJeremy Morse         if (!InLocsChanged && !FirstTrip)
2788ae6f7882SJeremy Morse           continue;
2789ae6f7882SJeremy Morse 
279089950adeSJeremy Morse         DbgValue *LiveOut = LiveOutIdx[MBB];
2791849b1794SJeremy Morse         bool OLChanged = false;
2792849b1794SJeremy Morse 
2793ae6f7882SJeremy Morse         // Do transfer function.
2794ab93e710SJeremy Morse         auto &VTracker = AllTheVLocs[MBB->getNumber()];
279589950adeSJeremy Morse         auto TransferIt = VTracker.Vars.find(Var);
279689950adeSJeremy Morse         if (TransferIt != VTracker.Vars.end()) {
2797ae6f7882SJeremy Morse           // Erase on empty transfer (DBG_VALUE $noreg).
279889950adeSJeremy Morse           if (TransferIt->second.Kind == DbgValue::Undef) {
2799849b1794SJeremy Morse             DbgValue NewVal(MBB->getNumber(), EmptyProperties, DbgValue::NoVal);
280089950adeSJeremy Morse             if (*LiveOut != NewVal) {
280189950adeSJeremy Morse               *LiveOut = NewVal;
2802849b1794SJeremy Morse               OLChanged = true;
2803849b1794SJeremy Morse             }
2804ae6f7882SJeremy Morse           } else {
2805ae6f7882SJeremy Morse             // Insert new variable value; or overwrite.
280689950adeSJeremy Morse             if (*LiveOut != TransferIt->second) {
280789950adeSJeremy Morse               *LiveOut = TransferIt->second;
2808849b1794SJeremy Morse               OLChanged = true;
2809849b1794SJeremy Morse             }
2810ae6f7882SJeremy Morse           }
281189950adeSJeremy Morse         } else {
281289950adeSJeremy Morse           // Just copy live-ins to live-outs, for anything not transferred.
281389950adeSJeremy Morse           if (*LiveOut != *LiveIn) {
281489950adeSJeremy Morse             *LiveOut = *LiveIn;
2815849b1794SJeremy Morse             OLChanged = true;
2816849b1794SJeremy Morse           }
2817849b1794SJeremy Morse         }
2818849b1794SJeremy Morse 
2819849b1794SJeremy Morse         // If no live-out value changed, there's no need to explore further.
2820849b1794SJeremy Morse         if (!OLChanged)
2821849b1794SJeremy Morse           continue;
2822ae6f7882SJeremy Morse 
2823ae6f7882SJeremy Morse         // We should visit all successors. Ensure we'll visit any non-backedge
2824ae6f7882SJeremy Morse         // successors during this dataflow iteration; book backedge successors
2825ae6f7882SJeremy Morse         // to be visited next time around.
28269e6d1f4bSKazu Hirata         for (auto *s : MBB->successors()) {
2827ae6f7882SJeremy Morse           // Ignore out of scope / not-to-be-explored successors.
2828ae6f7882SJeremy Morse           if (LiveInIdx.find(s) == LiveInIdx.end())
2829ae6f7882SJeremy Morse             continue;
2830ae6f7882SJeremy Morse 
2831ae6f7882SJeremy Morse           if (BBToOrder[s] > BBToOrder[MBB]) {
2832ae6f7882SJeremy Morse             if (OnWorklist.insert(s).second)
2833ae6f7882SJeremy Morse               Worklist.push(BBToOrder[s]);
2834ae6f7882SJeremy Morse           } else if (OnPending.insert(s).second && (FirstTrip || OLChanged)) {
2835ae6f7882SJeremy Morse             Pending.push(BBToOrder[s]);
2836ae6f7882SJeremy Morse           }
2837ae6f7882SJeremy Morse         }
2838ae6f7882SJeremy Morse       }
2839ae6f7882SJeremy Morse       Worklist.swap(Pending);
2840ae6f7882SJeremy Morse       std::swap(OnWorklist, OnPending);
2841ae6f7882SJeremy Morse       OnPending.clear();
2842ae6f7882SJeremy Morse       assert(Pending.empty());
2843ae6f7882SJeremy Morse       FirstTrip = false;
2844ae6f7882SJeremy Morse     }
2845ae6f7882SJeremy Morse 
2846b5426cedSJeremy Morse     // Save live-ins to output vector. Ignore any that are still marked as being
2847b5426cedSJeremy Morse     // VPHIs with no location -- those are variables that we know the value of,
2848b5426cedSJeremy Morse     // but are not actually available in the register file.
2849ae6f7882SJeremy Morse     for (auto *MBB : BlockOrders) {
285089950adeSJeremy Morse       DbgValue *BlockLiveIn = LiveInIdx[MBB];
285189950adeSJeremy Morse       if (BlockLiveIn->Kind == DbgValue::NoVal)
2852ae6f7882SJeremy Morse         continue;
285389950adeSJeremy Morse       if (BlockLiveIn->Kind == DbgValue::VPHI &&
285489950adeSJeremy Morse           BlockLiveIn->ID == ValueIDNum::EmptyValue)
2855b5426cedSJeremy Morse         continue;
285689950adeSJeremy Morse       if (BlockLiveIn->Kind == DbgValue::VPHI)
285789950adeSJeremy Morse         BlockLiveIn->Kind = DbgValue::Def;
28588dda516bSJeremy Morse       assert(BlockLiveIn->Properties.DIExpr->getFragmentInfo() ==
28598dda516bSJeremy Morse              Var.getFragment() && "Fragment info missing during value prop");
286089950adeSJeremy Morse       Output[MBB->getNumber()].push_back(std::make_pair(Var, *BlockLiveIn));
2861ae6f7882SJeremy Morse     }
286289950adeSJeremy Morse   } // Per-variable loop.
2863ae6f7882SJeremy Morse 
2864ae6f7882SJeremy Morse   BlockOrders.clear();
2865ae6f7882SJeremy Morse   BlocksToExplore.clear();
2866ae6f7882SJeremy Morse }
2867ae6f7882SJeremy Morse 
placePHIsForSingleVarDefinition(const SmallPtrSetImpl<MachineBasicBlock * > & InScopeBlocks,MachineBasicBlock * AssignMBB,SmallVectorImpl<VLocTracker> & AllTheVLocs,const DebugVariable & Var,LiveInsT & Output)2868c703d77aSJeremy Morse void InstrRefBasedLDV::placePHIsForSingleVarDefinition(
2869c703d77aSJeremy Morse     const SmallPtrSetImpl<MachineBasicBlock *> &InScopeBlocks,
2870c703d77aSJeremy Morse     MachineBasicBlock *AssignMBB, SmallVectorImpl<VLocTracker> &AllTheVLocs,
2871c703d77aSJeremy Morse     const DebugVariable &Var, LiveInsT &Output) {
2872c703d77aSJeremy Morse   // If there is a single definition of the variable, then working out it's
2873c703d77aSJeremy Morse   // value everywhere is very simple: it's every block dominated by the
2874c703d77aSJeremy Morse   // definition. At the dominance frontier, the usual algorithm would:
2875c703d77aSJeremy Morse   //  * Place PHIs,
2876c703d77aSJeremy Morse   //  * Propagate values into them,
2877c703d77aSJeremy Morse   //  * Find there's no incoming variable value from the other incoming branches
2878c703d77aSJeremy Morse   //    of the dominance frontier,
2879c703d77aSJeremy Morse   //  * Specify there's no variable value in blocks past the frontier.
2880c703d77aSJeremy Morse   // This is a common case, hence it's worth special-casing it.
2881c703d77aSJeremy Morse 
2882c703d77aSJeremy Morse   // Pick out the variables value from the block transfer function.
2883c703d77aSJeremy Morse   VLocTracker &VLocs = AllTheVLocs[AssignMBB->getNumber()];
2884c703d77aSJeremy Morse   auto ValueIt = VLocs.Vars.find(Var);
2885c703d77aSJeremy Morse   const DbgValue &Value = ValueIt->second;
2886c703d77aSJeremy Morse 
288743de3057SJeremy Morse   // If it's an explicit assignment of "undef", that means there is no location
288843de3057SJeremy Morse   // anyway, anywhere.
288943de3057SJeremy Morse   if (Value.Kind == DbgValue::Undef)
289043de3057SJeremy Morse     return;
289143de3057SJeremy Morse 
2892c703d77aSJeremy Morse   // Assign the variable value to entry to each dominated block that's in scope.
2893c703d77aSJeremy Morse   // Skip the definition block -- it's assigned the variable value in the middle
2894c703d77aSJeremy Morse   // of the block somewhere.
2895c703d77aSJeremy Morse   for (auto *ScopeBlock : InScopeBlocks) {
2896c703d77aSJeremy Morse     if (!DomTree->properlyDominates(AssignMBB, ScopeBlock))
2897c703d77aSJeremy Morse       continue;
2898c703d77aSJeremy Morse 
2899c703d77aSJeremy Morse     Output[ScopeBlock->getNumber()].push_back({Var, Value});
2900c703d77aSJeremy Morse   }
2901c703d77aSJeremy Morse 
2902c703d77aSJeremy Morse   // All blocks that aren't dominated have no live-in value, thus no variable
2903c703d77aSJeremy Morse   // value will be given to them.
2904c703d77aSJeremy Morse }
2905c703d77aSJeremy Morse 
29062ac06241SFangrui Song #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump_mloc_transfer(const MLocTransferMap & mloc_transfer) const2907ae6f7882SJeremy Morse void InstrRefBasedLDV::dump_mloc_transfer(
2908ae6f7882SJeremy Morse     const MLocTransferMap &mloc_transfer) const {
29099e6d1f4bSKazu Hirata   for (const auto &P : mloc_transfer) {
2910ae6f7882SJeremy Morse     std::string foo = MTracker->LocIdxToName(P.first);
2911ae6f7882SJeremy Morse     std::string bar = MTracker->IDAsString(P.second);
2912ae6f7882SJeremy Morse     dbgs() << "Loc " << foo << " --> " << bar << "\n";
2913ae6f7882SJeremy Morse   }
2914ae6f7882SJeremy Morse }
29152ac06241SFangrui Song #endif
2916ae6f7882SJeremy Morse 
initialSetup(MachineFunction & MF)2917ae6f7882SJeremy Morse void InstrRefBasedLDV::initialSetup(MachineFunction &MF) {
2918ae6f7882SJeremy Morse   // Build some useful data structures.
2919b5426cedSJeremy Morse 
2920b5426cedSJeremy Morse   LLVMContext &Context = MF.getFunction().getContext();
2921b5426cedSJeremy Morse   EmptyExpr = DIExpression::get(Context, {});
2922b5426cedSJeremy Morse 
2923ae6f7882SJeremy Morse   auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
2924ae6f7882SJeremy Morse     if (const DebugLoc &DL = MI.getDebugLoc())
2925ae6f7882SJeremy Morse       return DL.getLine() != 0;
2926ae6f7882SJeremy Morse     return false;
2927ae6f7882SJeremy Morse   };
2928ae6f7882SJeremy Morse   // Collect a set of all the artificial blocks.
2929ae6f7882SJeremy Morse   for (auto &MBB : MF)
2930ae6f7882SJeremy Morse     if (none_of(MBB.instrs(), hasNonArtificialLocation))
2931ae6f7882SJeremy Morse       ArtificialBlocks.insert(&MBB);
2932ae6f7882SJeremy Morse 
2933ae6f7882SJeremy Morse   // Compute mappings of block <=> RPO order.
2934ae6f7882SJeremy Morse   ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
2935ae6f7882SJeremy Morse   unsigned int RPONumber = 0;
2936d5adba10SKazu Hirata   for (MachineBasicBlock *MBB : RPOT) {
2937d5adba10SKazu Hirata     OrderToBB[RPONumber] = MBB;
2938d5adba10SKazu Hirata     BBToOrder[MBB] = RPONumber;
2939d5adba10SKazu Hirata     BBNumToRPO[MBB->getNumber()] = RPONumber;
2940ae6f7882SJeremy Morse     ++RPONumber;
2941ae6f7882SJeremy Morse   }
2942f551fb96SJeremy Morse 
2943f551fb96SJeremy Morse   // Order value substitutions by their "source" operand pair, for quick lookup.
2944f551fb96SJeremy Morse   llvm::sort(MF.DebugValueSubstitutions);
2945f551fb96SJeremy Morse 
2946f551fb96SJeremy Morse #ifdef EXPENSIVE_CHECKS
2947f551fb96SJeremy Morse   // As an expensive check, test whether there are any duplicate substitution
2948f551fb96SJeremy Morse   // sources in the collection.
2949f551fb96SJeremy Morse   if (MF.DebugValueSubstitutions.size() > 2) {
2950f551fb96SJeremy Morse     for (auto It = MF.DebugValueSubstitutions.begin();
2951f551fb96SJeremy Morse          It != std::prev(MF.DebugValueSubstitutions.end()); ++It) {
2952f551fb96SJeremy Morse       assert(It->Src != std::next(It)->Src && "Duplicate variable location "
2953f551fb96SJeremy Morse                                               "substitution seen");
2954f551fb96SJeremy Morse     }
2955f551fb96SJeremy Morse   }
2956f551fb96SJeremy Morse #endif
2957ae6f7882SJeremy Morse }
2958ae6f7882SJeremy Morse 
29599fd9d56dSJeremy Morse // Produce an "ejection map" for blocks, i.e., what's the highest-numbered
29609fd9d56dSJeremy Morse // lexical scope it's used in. When exploring in DFS order and we pass that
29619fd9d56dSJeremy Morse // scope, the block can be processed and any tracking information freed.
makeDepthFirstEjectionMap(SmallVectorImpl<unsigned> & EjectionMap,const ScopeToDILocT & ScopeToDILocation,ScopeToAssignBlocksT & ScopeToAssignBlocks)29629fd9d56dSJeremy Morse void InstrRefBasedLDV::makeDepthFirstEjectionMap(
29639fd9d56dSJeremy Morse     SmallVectorImpl<unsigned> &EjectionMap,
29649fd9d56dSJeremy Morse     const ScopeToDILocT &ScopeToDILocation,
29659fd9d56dSJeremy Morse     ScopeToAssignBlocksT &ScopeToAssignBlocks) {
29669fd9d56dSJeremy Morse   SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
29679fd9d56dSJeremy Morse   SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack;
29689fd9d56dSJeremy Morse   auto *TopScope = LS.getCurrentFunctionScope();
29699fd9d56dSJeremy Morse 
29709fd9d56dSJeremy Morse   // Unlike lexical scope explorers, we explore in reverse order, to find the
29719fd9d56dSJeremy Morse   // "last" lexical scope used for each block early.
29729fd9d56dSJeremy Morse   WorkStack.push_back({TopScope, TopScope->getChildren().size() - 1});
29739fd9d56dSJeremy Morse 
29749fd9d56dSJeremy Morse   while (!WorkStack.empty()) {
29759fd9d56dSJeremy Morse     auto &ScopePosition = WorkStack.back();
29769fd9d56dSJeremy Morse     LexicalScope *WS = ScopePosition.first;
29779fd9d56dSJeremy Morse     ssize_t ChildNum = ScopePosition.second--;
29789fd9d56dSJeremy Morse 
29799fd9d56dSJeremy Morse     const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();
29809fd9d56dSJeremy Morse     if (ChildNum >= 0) {
29819fd9d56dSJeremy Morse       // If ChildNum is positive, there are remaining children to explore.
29829fd9d56dSJeremy Morse       // Push the child and its children-count onto the stack.
29839fd9d56dSJeremy Morse       auto &ChildScope = Children[ChildNum];
29849fd9d56dSJeremy Morse       WorkStack.push_back(
29859fd9d56dSJeremy Morse           std::make_pair(ChildScope, ChildScope->getChildren().size() - 1));
29869fd9d56dSJeremy Morse     } else {
29879fd9d56dSJeremy Morse       WorkStack.pop_back();
29889fd9d56dSJeremy Morse 
29899fd9d56dSJeremy Morse       // We've explored all children and any later blocks: examine all blocks
29909fd9d56dSJeremy Morse       // in our scope. If they haven't yet had an ejection number set, then
29919fd9d56dSJeremy Morse       // this scope will be the last to use that block.
29929fd9d56dSJeremy Morse       auto DILocationIt = ScopeToDILocation.find(WS);
29939fd9d56dSJeremy Morse       if (DILocationIt != ScopeToDILocation.end()) {
29949fd9d56dSJeremy Morse         getBlocksForScope(DILocationIt->second, BlocksToExplore,
29959fd9d56dSJeremy Morse                           ScopeToAssignBlocks.find(WS)->second);
29969e6d1f4bSKazu Hirata         for (const auto *MBB : BlocksToExplore) {
29979fd9d56dSJeremy Morse           unsigned BBNum = MBB->getNumber();
29989fd9d56dSJeremy Morse           if (EjectionMap[BBNum] == 0)
29999fd9d56dSJeremy Morse             EjectionMap[BBNum] = WS->getDFSOut();
30009fd9d56dSJeremy Morse         }
30019fd9d56dSJeremy Morse 
30029fd9d56dSJeremy Morse         BlocksToExplore.clear();
30039fd9d56dSJeremy Morse       }
30049fd9d56dSJeremy Morse     }
30059fd9d56dSJeremy Morse   }
30069fd9d56dSJeremy Morse }
30079fd9d56dSJeremy Morse 
depthFirstVLocAndEmit(unsigned MaxNumBlocks,const ScopeToDILocT & ScopeToDILocation,const ScopeToVarsT & ScopeToVars,ScopeToAssignBlocksT & ScopeToAssignBlocks,LiveInsT & Output,FuncValueTable & MOutLocs,FuncValueTable & MInLocs,SmallVectorImpl<VLocTracker> & AllTheVLocs,MachineFunction & MF,DenseMap<DebugVariable,unsigned> & AllVarsNumbering,const TargetPassConfig & TPC)30089fd9d56dSJeremy Morse bool InstrRefBasedLDV::depthFirstVLocAndEmit(
30099fd9d56dSJeremy Morse     unsigned MaxNumBlocks, const ScopeToDILocT &ScopeToDILocation,
30109fd9d56dSJeremy Morse     const ScopeToVarsT &ScopeToVars, ScopeToAssignBlocksT &ScopeToAssignBlocks,
3011ab49dce0SJeremy Morse     LiveInsT &Output, FuncValueTable &MOutLocs, FuncValueTable &MInLocs,
30129fd9d56dSJeremy Morse     SmallVectorImpl<VLocTracker> &AllTheVLocs, MachineFunction &MF,
30139fd9d56dSJeremy Morse     DenseMap<DebugVariable, unsigned> &AllVarsNumbering,
30149fd9d56dSJeremy Morse     const TargetPassConfig &TPC) {
30159fd9d56dSJeremy Morse   TTracker = new TransferTracker(TII, MTracker, MF, *TRI, CalleeSavedRegs, TPC);
30169fd9d56dSJeremy Morse   unsigned NumLocs = MTracker->getNumLocs();
30179fd9d56dSJeremy Morse   VTracker = nullptr;
30189fd9d56dSJeremy Morse 
30199fd9d56dSJeremy Morse   // No scopes? No variable locations.
3020ab49dce0SJeremy Morse   if (!LS.getCurrentFunctionScope())
30219fd9d56dSJeremy Morse     return false;
30229fd9d56dSJeremy Morse 
30239fd9d56dSJeremy Morse   // Build map from block number to the last scope that uses the block.
30249fd9d56dSJeremy Morse   SmallVector<unsigned, 16> EjectionMap;
30259fd9d56dSJeremy Morse   EjectionMap.resize(MaxNumBlocks, 0);
30269fd9d56dSJeremy Morse   makeDepthFirstEjectionMap(EjectionMap, ScopeToDILocation,
30279fd9d56dSJeremy Morse                             ScopeToAssignBlocks);
30289fd9d56dSJeremy Morse 
30299fd9d56dSJeremy Morse   // Helper lambda for ejecting a block -- if nothing is going to use the block,
30309fd9d56dSJeremy Morse   // we can translate the variable location information into DBG_VALUEs and then
30319fd9d56dSJeremy Morse   // free all of InstrRefBasedLDV's data structures.
30329fd9d56dSJeremy Morse   auto EjectBlock = [&](MachineBasicBlock &MBB) -> void {
30339fd9d56dSJeremy Morse     unsigned BBNum = MBB.getNumber();
30349fd9d56dSJeremy Morse     AllTheVLocs[BBNum].clear();
30359fd9d56dSJeremy Morse 
30369fd9d56dSJeremy Morse     // Prime the transfer-tracker, and then step through all the block
30379fd9d56dSJeremy Morse     // instructions, installing transfers.
30389fd9d56dSJeremy Morse     MTracker->reset();
30399fd9d56dSJeremy Morse     MTracker->loadFromArray(MInLocs[BBNum], BBNum);
30409fd9d56dSJeremy Morse     TTracker->loadInlocs(MBB, MInLocs[BBNum], Output[BBNum], NumLocs);
30419fd9d56dSJeremy Morse 
30429fd9d56dSJeremy Morse     CurBB = BBNum;
30439fd9d56dSJeremy Morse     CurInst = 1;
30449fd9d56dSJeremy Morse     for (auto &MI : MBB) {
3045ab49dce0SJeremy Morse       process(MI, MOutLocs.get(), MInLocs.get());
30469fd9d56dSJeremy Morse       TTracker->checkInstForNewValues(CurInst, MI.getIterator());
30479fd9d56dSJeremy Morse       ++CurInst;
30489fd9d56dSJeremy Morse     }
30499fd9d56dSJeremy Morse 
30509fd9d56dSJeremy Morse     // Free machine-location tables for this block.
3051ab49dce0SJeremy Morse     MInLocs[BBNum].reset();
3052ab49dce0SJeremy Morse     MOutLocs[BBNum].reset();
30539fd9d56dSJeremy Morse     // We don't need live-in variable values for this block either.
30549fd9d56dSJeremy Morse     Output[BBNum].clear();
30559fd9d56dSJeremy Morse     AllTheVLocs[BBNum].clear();
30569fd9d56dSJeremy Morse   };
30579fd9d56dSJeremy Morse 
30589fd9d56dSJeremy Morse   SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
30599fd9d56dSJeremy Morse   SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack;
30609fd9d56dSJeremy Morse   WorkStack.push_back({LS.getCurrentFunctionScope(), 0});
30619fd9d56dSJeremy Morse   unsigned HighestDFSIn = 0;
30629fd9d56dSJeremy Morse 
30639fd9d56dSJeremy Morse   // Proceed to explore in depth first order.
30649fd9d56dSJeremy Morse   while (!WorkStack.empty()) {
30659fd9d56dSJeremy Morse     auto &ScopePosition = WorkStack.back();
30669fd9d56dSJeremy Morse     LexicalScope *WS = ScopePosition.first;
30679fd9d56dSJeremy Morse     ssize_t ChildNum = ScopePosition.second++;
30689fd9d56dSJeremy Morse 
30699fd9d56dSJeremy Morse     // We obesrve scopes with children twice here, once descending in, once
30709fd9d56dSJeremy Morse     // ascending out of the scope nest. Use HighestDFSIn as a ratchet to ensure
30719fd9d56dSJeremy Morse     // we don't process a scope twice. Additionally, ignore scopes that don't
30729fd9d56dSJeremy Morse     // have a DILocation -- by proxy, this means we never tracked any variable
30739fd9d56dSJeremy Morse     // assignments in that scope.
30749fd9d56dSJeremy Morse     auto DILocIt = ScopeToDILocation.find(WS);
30759fd9d56dSJeremy Morse     if (HighestDFSIn <= WS->getDFSIn() && DILocIt != ScopeToDILocation.end()) {
30769fd9d56dSJeremy Morse       const DILocation *DILoc = DILocIt->second;
30779fd9d56dSJeremy Morse       auto &VarsWeCareAbout = ScopeToVars.find(WS)->second;
30789fd9d56dSJeremy Morse       auto &BlocksInScope = ScopeToAssignBlocks.find(WS)->second;
30799fd9d56dSJeremy Morse 
30809fd9d56dSJeremy Morse       buildVLocValueMap(DILoc, VarsWeCareAbout, BlocksInScope, Output, MOutLocs,
30819fd9d56dSJeremy Morse                         MInLocs, AllTheVLocs);
30829fd9d56dSJeremy Morse     }
30839fd9d56dSJeremy Morse 
30849fd9d56dSJeremy Morse     HighestDFSIn = std::max(HighestDFSIn, WS->getDFSIn());
30859fd9d56dSJeremy Morse 
30869fd9d56dSJeremy Morse     // Descend into any scope nests.
30879fd9d56dSJeremy Morse     const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();
30889fd9d56dSJeremy Morse     if (ChildNum < (ssize_t)Children.size()) {
30899fd9d56dSJeremy Morse       // There are children to explore -- push onto stack and continue.
30909fd9d56dSJeremy Morse       auto &ChildScope = Children[ChildNum];
30919fd9d56dSJeremy Morse       WorkStack.push_back(std::make_pair(ChildScope, 0));
30929fd9d56dSJeremy Morse     } else {
30939fd9d56dSJeremy Morse       WorkStack.pop_back();
30949fd9d56dSJeremy Morse 
30959fd9d56dSJeremy Morse       // We've explored a leaf, or have explored all the children of a scope.
30969fd9d56dSJeremy Morse       // Try to eject any blocks where this is the last scope it's relevant to.
30979fd9d56dSJeremy Morse       auto DILocationIt = ScopeToDILocation.find(WS);
30989fd9d56dSJeremy Morse       if (DILocationIt == ScopeToDILocation.end())
30999fd9d56dSJeremy Morse         continue;
31009fd9d56dSJeremy Morse 
31019fd9d56dSJeremy Morse       getBlocksForScope(DILocationIt->second, BlocksToExplore,
31029fd9d56dSJeremy Morse                         ScopeToAssignBlocks.find(WS)->second);
31039e6d1f4bSKazu Hirata       for (const auto *MBB : BlocksToExplore)
31049fd9d56dSJeremy Morse         if (WS->getDFSOut() == EjectionMap[MBB->getNumber()])
31059fd9d56dSJeremy Morse           EjectBlock(const_cast<MachineBasicBlock &>(*MBB));
31069fd9d56dSJeremy Morse 
31079fd9d56dSJeremy Morse       BlocksToExplore.clear();
31089fd9d56dSJeremy Morse     }
31099fd9d56dSJeremy Morse   }
31109fd9d56dSJeremy Morse 
31119fd9d56dSJeremy Morse   // Some artificial blocks may not have been ejected, meaning they're not
31129fd9d56dSJeremy Morse   // connected to an actual legitimate scope. This can technically happen
31139fd9d56dSJeremy Morse   // with things like the entry block. In theory, we shouldn't need to do
31149fd9d56dSJeremy Morse   // anything for such out-of-scope blocks, but for the sake of being similar
31159fd9d56dSJeremy Morse   // to VarLocBasedLDV, eject these too.
31169fd9d56dSJeremy Morse   for (auto *MBB : ArtificialBlocks)
31179fd9d56dSJeremy Morse     if (MOutLocs[MBB->getNumber()])
31189fd9d56dSJeremy Morse       EjectBlock(*MBB);
31199fd9d56dSJeremy Morse 
31209fd9d56dSJeremy Morse   return emitTransfers(AllVarsNumbering);
31219fd9d56dSJeremy Morse }
31229fd9d56dSJeremy Morse 
emitTransfers(DenseMap<DebugVariable,unsigned> & AllVarsNumbering)31234a2cb013SJeremy Morse bool InstrRefBasedLDV::emitTransfers(
31244a2cb013SJeremy Morse     DenseMap<DebugVariable, unsigned> &AllVarsNumbering) {
31254a2cb013SJeremy Morse   // Go through all the transfers recorded in the TransferTracker -- this is
31264a2cb013SJeremy Morse   // both the live-ins to a block, and any movements of values that happen
31274a2cb013SJeremy Morse   // in the middle.
31284a2cb013SJeremy Morse   for (const auto &P : TTracker->Transfers) {
31294a2cb013SJeremy Morse     // We have to insert DBG_VALUEs in a consistent order, otherwise they
31304a2cb013SJeremy Morse     // appear in DWARF in different orders. Use the order that they appear
31314a2cb013SJeremy Morse     // when walking through each block / each instruction, stored in
31324a2cb013SJeremy Morse     // AllVarsNumbering.
31334a2cb013SJeremy Morse     SmallVector<std::pair<unsigned, MachineInstr *>> Insts;
31344a2cb013SJeremy Morse     for (MachineInstr *MI : P.Insts) {
31354a2cb013SJeremy Morse       DebugVariable Var(MI->getDebugVariable(), MI->getDebugExpression(),
31364a2cb013SJeremy Morse                         MI->getDebugLoc()->getInlinedAt());
31374a2cb013SJeremy Morse       Insts.emplace_back(AllVarsNumbering.find(Var)->second, MI);
31384a2cb013SJeremy Morse     }
3139*acf648b5SKazu Hirata     llvm::sort(Insts, llvm::less_first());
31404a2cb013SJeremy Morse 
31414a2cb013SJeremy Morse     // Insert either before or after the designated point...
31424a2cb013SJeremy Morse     if (P.MBB) {
31434a2cb013SJeremy Morse       MachineBasicBlock &MBB = *P.MBB;
31444a2cb013SJeremy Morse       for (const auto &Pair : Insts)
31454a2cb013SJeremy Morse         MBB.insert(P.Pos, Pair.second);
31464a2cb013SJeremy Morse     } else {
31474a2cb013SJeremy Morse       // Terminators, like tail calls, can clobber things. Don't try and place
31484a2cb013SJeremy Morse       // transfers after them.
31494a2cb013SJeremy Morse       if (P.Pos->isTerminator())
31504a2cb013SJeremy Morse         continue;
31514a2cb013SJeremy Morse 
31524a2cb013SJeremy Morse       MachineBasicBlock &MBB = *P.Pos->getParent();
31534a2cb013SJeremy Morse       for (const auto &Pair : Insts)
31544a2cb013SJeremy Morse         MBB.insertAfterBundle(P.Pos, Pair.second);
31554a2cb013SJeremy Morse     }
31564a2cb013SJeremy Morse   }
31574a2cb013SJeremy Morse 
31584a2cb013SJeremy Morse   return TTracker->Transfers.size() != 0;
31594a2cb013SJeremy Morse }
31604a2cb013SJeremy Morse 
3161ae6f7882SJeremy Morse /// Calculate the liveness information for the given machine function and
3162ae6f7882SJeremy Morse /// extend ranges across basic blocks.
ExtendRanges(MachineFunction & MF,MachineDominatorTree * DomTree,TargetPassConfig * TPC,unsigned InputBBLimit,unsigned InputDbgValLimit)3163a3936a6cSJeremy Morse bool InstrRefBasedLDV::ExtendRanges(MachineFunction &MF,
3164a3936a6cSJeremy Morse                                     MachineDominatorTree *DomTree,
3165a3936a6cSJeremy Morse                                     TargetPassConfig *TPC,
3166708cbda5SJeremy Morse                                     unsigned InputBBLimit,
3167708cbda5SJeremy Morse                                     unsigned InputDbgValLimit) {
3168ae6f7882SJeremy Morse   // No subprogram means this function contains no debuginfo.
3169ae6f7882SJeremy Morse   if (!MF.getFunction().getSubprogram())
3170ae6f7882SJeremy Morse     return false;
3171ae6f7882SJeremy Morse 
3172ae6f7882SJeremy Morse   LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
3173ae6f7882SJeremy Morse   this->TPC = TPC;
3174ae6f7882SJeremy Morse 
3175a3936a6cSJeremy Morse   this->DomTree = DomTree;
3176ae6f7882SJeremy Morse   TRI = MF.getSubtarget().getRegisterInfo();
3177e7084ceaSJeremy Morse   MRI = &MF.getRegInfo();
3178ae6f7882SJeremy Morse   TII = MF.getSubtarget().getInstrInfo();
3179ae6f7882SJeremy Morse   TFI = MF.getSubtarget().getFrameLowering();
3180ae6f7882SJeremy Morse   TFI->getCalleeSaves(MF, CalleeSavedRegs);
3181010108bbSJeremy Morse   MFI = &MF.getFrameInfo();
3182ae6f7882SJeremy Morse   LS.initialize(MF);
3183ae6f7882SJeremy Morse 
3184bfadc5dcSJeremy Morse   const auto &STI = MF.getSubtarget();
3185bfadc5dcSJeremy Morse   AdjustsStackInCalls = MFI->adjustsStack() &&
3186bfadc5dcSJeremy Morse                         STI.getFrameLowering()->stackProbeFunctionModifiesSP();
3187bfadc5dcSJeremy Morse   if (AdjustsStackInCalls)
3188bfadc5dcSJeremy Morse     StackProbeSymbolName = STI.getTargetLowering()->getStackProbeSymbolName(MF);
3189bfadc5dcSJeremy Morse 
3190ae6f7882SJeremy Morse   MTracker =
3191ae6f7882SJeremy Morse       new MLocTracker(MF, *TII, *TRI, *MF.getSubtarget().getTargetLowering());
3192ae6f7882SJeremy Morse   VTracker = nullptr;
3193ae6f7882SJeremy Morse   TTracker = nullptr;
3194ae6f7882SJeremy Morse 
3195ae6f7882SJeremy Morse   SmallVector<MLocTransferMap, 32> MLocTransfer;
3196ae6f7882SJeremy Morse   SmallVector<VLocTracker, 8> vlocs;
3197ae6f7882SJeremy Morse   LiveInsT SavedLiveIns;
3198ae6f7882SJeremy Morse 
3199ae6f7882SJeremy Morse   int MaxNumBlocks = -1;
3200ae6f7882SJeremy Morse   for (auto &MBB : MF)
3201ae6f7882SJeremy Morse     MaxNumBlocks = std::max(MBB.getNumber(), MaxNumBlocks);
3202ae6f7882SJeremy Morse   assert(MaxNumBlocks >= 0);
3203ae6f7882SJeremy Morse   ++MaxNumBlocks;
3204ae6f7882SJeremy Morse 
3205f0ca0a32SVitaly Buka   initialSetup(MF);
3206f0ca0a32SVitaly Buka 
3207ae6f7882SJeremy Morse   MLocTransfer.resize(MaxNumBlocks);
32080eee8445SJeremy Morse   vlocs.resize(MaxNumBlocks, VLocTracker(OverlapFragments, EmptyExpr));
3209ae6f7882SJeremy Morse   SavedLiveIns.resize(MaxNumBlocks);
3210ae6f7882SJeremy Morse 
3211ab93e710SJeremy Morse   produceMLocTransferFunction(MF, MLocTransfer, MaxNumBlocks);
3212ae6f7882SJeremy Morse 
3213ae6f7882SJeremy Morse   // Allocate and initialize two array-of-arrays for the live-in and live-out
3214ae6f7882SJeremy Morse   // machine values. The outer dimension is the block number; while the inner
3215ae6f7882SJeremy Morse   // dimension is a LocIdx from MLocTracker.
3216ab49dce0SJeremy Morse   FuncValueTable MOutLocs = std::make_unique<ValueTable[]>(MaxNumBlocks);
3217ab49dce0SJeremy Morse   FuncValueTable MInLocs = std::make_unique<ValueTable[]>(MaxNumBlocks);
3218ae6f7882SJeremy Morse   unsigned NumLocs = MTracker->getNumLocs();
3219ae6f7882SJeremy Morse   for (int i = 0; i < MaxNumBlocks; ++i) {
3220a3936a6cSJeremy Morse     // These all auto-initialize to ValueIDNum::EmptyValue
3221ab49dce0SJeremy Morse     MOutLocs[i] = std::make_unique<ValueIDNum[]>(NumLocs);
3222ab49dce0SJeremy Morse     MInLocs[i] = std::make_unique<ValueIDNum[]>(NumLocs);
3223ae6f7882SJeremy Morse   }
3224ae6f7882SJeremy Morse 
3225ae6f7882SJeremy Morse   // Solve the machine value dataflow problem using the MLocTransfer function,
3226ae6f7882SJeremy Morse   // storing the computed live-ins / live-outs into the array-of-arrays. We use
3227ae6f7882SJeremy Morse   // both live-ins and live-outs for decision making in the variable value
3228ae6f7882SJeremy Morse   // dataflow problem.
3229a3936a6cSJeremy Morse   buildMLocValueMap(MF, MInLocs, MOutLocs, MLocTransfer);
3230ae6f7882SJeremy Morse 
3231010108bbSJeremy Morse   // Patch up debug phi numbers, turning unknown block-live-in values into
3232010108bbSJeremy Morse   // either live-through machine values, or PHIs.
3233010108bbSJeremy Morse   for (auto &DBG_PHI : DebugPHINumToValue) {
3234010108bbSJeremy Morse     // Identify unresolved block-live-ins.
3235be5734ddSJeremy Morse     if (!DBG_PHI.ValueRead)
3236be5734ddSJeremy Morse       continue;
3237be5734ddSJeremy Morse 
3238be5734ddSJeremy Morse     ValueIDNum &Num = *DBG_PHI.ValueRead;
3239010108bbSJeremy Morse     if (!Num.isPHI())
3240010108bbSJeremy Morse       continue;
3241010108bbSJeremy Morse 
3242010108bbSJeremy Morse     unsigned BlockNo = Num.getBlock();
3243010108bbSJeremy Morse     LocIdx LocNo = Num.getLoc();
3244010108bbSJeremy Morse     Num = MInLocs[BlockNo][LocNo.asU64()];
3245010108bbSJeremy Morse   }
3246010108bbSJeremy Morse   // Later, we'll be looking up ranges of instruction numbers.
3247010108bbSJeremy Morse   llvm::sort(DebugPHINumToValue);
3248010108bbSJeremy Morse 
3249ab93e710SJeremy Morse   // Walk back through each block / instruction, collecting DBG_VALUE
3250ab93e710SJeremy Morse   // instructions and recording what machine value their operands refer to.
3251ab93e710SJeremy Morse   for (auto &OrderPair : OrderToBB) {
3252ab93e710SJeremy Morse     MachineBasicBlock &MBB = *OrderPair.second;
3253ab93e710SJeremy Morse     CurBB = MBB.getNumber();
3254ab93e710SJeremy Morse     VTracker = &vlocs[CurBB];
3255ab93e710SJeremy Morse     VTracker->MBB = &MBB;
3256ab93e710SJeremy Morse     MTracker->loadFromArray(MInLocs[CurBB], CurBB);
3257ab93e710SJeremy Morse     CurInst = 1;
3258ab93e710SJeremy Morse     for (auto &MI : MBB) {
3259ab49dce0SJeremy Morse       process(MI, MOutLocs.get(), MInLocs.get());
3260ab93e710SJeremy Morse       ++CurInst;
3261ab93e710SJeremy Morse     }
3262ab93e710SJeremy Morse     MTracker->reset();
3263ab93e710SJeremy Morse   }
3264ab93e710SJeremy Morse 
3265ae6f7882SJeremy Morse   // Number all variables in the order that they appear, to be used as a stable
3266ae6f7882SJeremy Morse   // insertion order later.
3267ae6f7882SJeremy Morse   DenseMap<DebugVariable, unsigned> AllVarsNumbering;
3268ae6f7882SJeremy Morse 
3269ae6f7882SJeremy Morse   // Map from one LexicalScope to all the variables in that scope.
32704a2cb013SJeremy Morse   ScopeToVarsT ScopeToVars;
3271ae6f7882SJeremy Morse 
32724a2cb013SJeremy Morse   // Map from One lexical scope to all blocks where assignments happen for
32734a2cb013SJeremy Morse   // that scope.
32744a2cb013SJeremy Morse   ScopeToAssignBlocksT ScopeToAssignBlocks;
3275ae6f7882SJeremy Morse 
32764a2cb013SJeremy Morse   // Store map of DILocations that describes scopes.
32774a2cb013SJeremy Morse   ScopeToDILocT ScopeToDILocation;
3278ae6f7882SJeremy Morse 
3279ae6f7882SJeremy Morse   // To mirror old LiveDebugValues, enumerate variables in RPOT order. Otherwise
3280ae6f7882SJeremy Morse   // the order is unimportant, it just has to be stable.
3281708cbda5SJeremy Morse   unsigned VarAssignCount = 0;
3282ae6f7882SJeremy Morse   for (unsigned int I = 0; I < OrderToBB.size(); ++I) {
3283ae6f7882SJeremy Morse     auto *MBB = OrderToBB[I];
3284ae6f7882SJeremy Morse     auto *VTracker = &vlocs[MBB->getNumber()];
3285ae6f7882SJeremy Morse     // Collect each variable with a DBG_VALUE in this block.
3286ae6f7882SJeremy Morse     for (auto &idx : VTracker->Vars) {
3287ae6f7882SJeremy Morse       const auto &Var = idx.first;
3288ae6f7882SJeremy Morse       const DILocation *ScopeLoc = VTracker->Scopes[Var];
3289ae6f7882SJeremy Morse       assert(ScopeLoc != nullptr);
3290ae6f7882SJeremy Morse       auto *Scope = LS.findLexicalScope(ScopeLoc);
3291ae6f7882SJeremy Morse 
3292ae6f7882SJeremy Morse       // No insts in scope -> shouldn't have been recorded.
3293ae6f7882SJeremy Morse       assert(Scope != nullptr);
3294ae6f7882SJeremy Morse 
3295ae6f7882SJeremy Morse       AllVarsNumbering.insert(std::make_pair(Var, AllVarsNumbering.size()));
3296ae6f7882SJeremy Morse       ScopeToVars[Scope].insert(Var);
32974a2cb013SJeremy Morse       ScopeToAssignBlocks[Scope].insert(VTracker->MBB);
3298ae6f7882SJeremy Morse       ScopeToDILocation[Scope] = ScopeLoc;
3299708cbda5SJeremy Morse       ++VarAssignCount;
3300ae6f7882SJeremy Morse     }
3301ae6f7882SJeremy Morse   }
3302ae6f7882SJeremy Morse 
3303708cbda5SJeremy Morse   bool Changed = false;
3304708cbda5SJeremy Morse 
3305708cbda5SJeremy Morse   // If we have an extremely large number of variable assignments and blocks,
3306708cbda5SJeremy Morse   // bail out at this point. We've burnt some time doing analysis already,
3307708cbda5SJeremy Morse   // however we should cut our losses.
3308708cbda5SJeremy Morse   if ((unsigned)MaxNumBlocks > InputBBLimit &&
3309708cbda5SJeremy Morse       VarAssignCount > InputDbgValLimit) {
3310708cbda5SJeremy Morse     LLVM_DEBUG(dbgs() << "Disabling InstrRefBasedLDV: " << MF.getName()
3311708cbda5SJeremy Morse                       << " has " << MaxNumBlocks << " basic blocks and "
3312708cbda5SJeremy Morse                       << VarAssignCount
3313708cbda5SJeremy Morse                       << " variable assignments, exceeding limits.\n");
3314708cbda5SJeremy Morse   } else {
33159fd9d56dSJeremy Morse     // Optionally, solve the variable value problem and emit to blocks by using
33169fd9d56dSJeremy Morse     // a lexical-scope-depth search. It should be functionally identical to
33179fd9d56dSJeremy Morse     // the "else" block of this condition.
33189fd9d56dSJeremy Morse     Changed = depthFirstVLocAndEmit(
33199fd9d56dSJeremy Morse         MaxNumBlocks, ScopeToDILocation, ScopeToVars, ScopeToAssignBlocks,
33209fd9d56dSJeremy Morse         SavedLiveIns, MOutLocs, MInLocs, vlocs, MF, AllVarsNumbering, *TPC);
3321708cbda5SJeremy Morse   }
3322708cbda5SJeremy Morse 
3323ae6f7882SJeremy Morse   delete MTracker;
33240caeaff1SJeremy Morse   delete TTracker;
33250caeaff1SJeremy Morse   MTracker = nullptr;
3326ae6f7882SJeremy Morse   VTracker = nullptr;
3327ae6f7882SJeremy Morse   TTracker = nullptr;
3328ae6f7882SJeremy Morse 
3329ae6f7882SJeremy Morse   ArtificialBlocks.clear();
3330ae6f7882SJeremy Morse   OrderToBB.clear();
3331ae6f7882SJeremy Morse   BBToOrder.clear();
3332ae6f7882SJeremy Morse   BBNumToRPO.clear();
333368f47157SJeremy Morse   DebugInstrNumToInstr.clear();
3334010108bbSJeremy Morse   DebugPHINumToValue.clear();
33350eee8445SJeremy Morse   OverlapFragments.clear();
33360eee8445SJeremy Morse   SeenFragments.clear();
3337d556eb7eSJeremy Morse   SeenDbgPHIs.clear();
3338ae6f7882SJeremy Morse 
3339ae6f7882SJeremy Morse   return Changed;
3340ae6f7882SJeremy Morse }
3341ae6f7882SJeremy Morse 
makeInstrRefBasedLiveDebugValues()3342ae6f7882SJeremy Morse LDVImpl *llvm::makeInstrRefBasedLiveDebugValues() {
3343ae6f7882SJeremy Morse   return new InstrRefBasedLDV();
3344ae6f7882SJeremy Morse }
3345010108bbSJeremy Morse 
3346010108bbSJeremy Morse namespace {
3347010108bbSJeremy Morse class LDVSSABlock;
3348010108bbSJeremy Morse class LDVSSAUpdater;
3349010108bbSJeremy Morse 
3350010108bbSJeremy Morse // Pick a type to identify incoming block values as we construct SSA. We
3351010108bbSJeremy Morse // can't use anything more robust than an integer unfortunately, as SSAUpdater
3352010108bbSJeremy Morse // expects to zero-initialize the type.
3353010108bbSJeremy Morse typedef uint64_t BlockValueNum;
3354010108bbSJeremy Morse 
3355010108bbSJeremy Morse /// Represents an SSA PHI node for the SSA updater class. Contains the block
3356010108bbSJeremy Morse /// this PHI is in, the value number it would have, and the expected incoming
3357010108bbSJeremy Morse /// values from parent blocks.
3358010108bbSJeremy Morse class LDVSSAPhi {
3359010108bbSJeremy Morse public:
3360010108bbSJeremy Morse   SmallVector<std::pair<LDVSSABlock *, BlockValueNum>, 4> IncomingValues;
3361010108bbSJeremy Morse   LDVSSABlock *ParentBlock;
3362010108bbSJeremy Morse   BlockValueNum PHIValNum;
LDVSSAPhi(BlockValueNum PHIValNum,LDVSSABlock * ParentBlock)3363010108bbSJeremy Morse   LDVSSAPhi(BlockValueNum PHIValNum, LDVSSABlock *ParentBlock)
3364010108bbSJeremy Morse       : ParentBlock(ParentBlock), PHIValNum(PHIValNum) {}
3365010108bbSJeremy Morse 
getParent()3366010108bbSJeremy Morse   LDVSSABlock *getParent() { return ParentBlock; }
3367010108bbSJeremy Morse };
3368010108bbSJeremy Morse 
3369010108bbSJeremy Morse /// Thin wrapper around a block predecessor iterator. Only difference from a
3370010108bbSJeremy Morse /// normal block iterator is that it dereferences to an LDVSSABlock.
3371010108bbSJeremy Morse class LDVSSABlockIterator {
3372010108bbSJeremy Morse public:
3373010108bbSJeremy Morse   MachineBasicBlock::pred_iterator PredIt;
3374010108bbSJeremy Morse   LDVSSAUpdater &Updater;
3375010108bbSJeremy Morse 
LDVSSABlockIterator(MachineBasicBlock::pred_iterator PredIt,LDVSSAUpdater & Updater)3376010108bbSJeremy Morse   LDVSSABlockIterator(MachineBasicBlock::pred_iterator PredIt,
3377010108bbSJeremy Morse                       LDVSSAUpdater &Updater)
3378010108bbSJeremy Morse       : PredIt(PredIt), Updater(Updater) {}
3379010108bbSJeremy Morse 
operator !=(const LDVSSABlockIterator & OtherIt) const3380010108bbSJeremy Morse   bool operator!=(const LDVSSABlockIterator &OtherIt) const {
3381010108bbSJeremy Morse     return OtherIt.PredIt != PredIt;
3382010108bbSJeremy Morse   }
3383010108bbSJeremy Morse 
operator ++()3384010108bbSJeremy Morse   LDVSSABlockIterator &operator++() {
3385010108bbSJeremy Morse     ++PredIt;
3386010108bbSJeremy Morse     return *this;
3387010108bbSJeremy Morse   }
3388010108bbSJeremy Morse 
3389010108bbSJeremy Morse   LDVSSABlock *operator*();
3390010108bbSJeremy Morse };
3391010108bbSJeremy Morse 
3392010108bbSJeremy Morse /// Thin wrapper around a block for SSA Updater interface. Necessary because
3393010108bbSJeremy Morse /// we need to track the PHI value(s) that we may have observed as necessary
3394010108bbSJeremy Morse /// in this block.
3395010108bbSJeremy Morse class LDVSSABlock {
3396010108bbSJeremy Morse public:
3397010108bbSJeremy Morse   MachineBasicBlock &BB;
3398010108bbSJeremy Morse   LDVSSAUpdater &Updater;
3399010108bbSJeremy Morse   using PHIListT = SmallVector<LDVSSAPhi, 1>;
3400010108bbSJeremy Morse   /// List of PHIs in this block. There should only ever be one.
3401010108bbSJeremy Morse   PHIListT PHIList;
3402010108bbSJeremy Morse 
LDVSSABlock(MachineBasicBlock & BB,LDVSSAUpdater & Updater)3403010108bbSJeremy Morse   LDVSSABlock(MachineBasicBlock &BB, LDVSSAUpdater &Updater)
3404010108bbSJeremy Morse       : BB(BB), Updater(Updater) {}
3405010108bbSJeremy Morse 
succ_begin()3406010108bbSJeremy Morse   LDVSSABlockIterator succ_begin() {
3407010108bbSJeremy Morse     return LDVSSABlockIterator(BB.succ_begin(), Updater);
3408010108bbSJeremy Morse   }
3409010108bbSJeremy Morse 
succ_end()3410010108bbSJeremy Morse   LDVSSABlockIterator succ_end() {
3411010108bbSJeremy Morse     return LDVSSABlockIterator(BB.succ_end(), Updater);
3412010108bbSJeremy Morse   }
3413010108bbSJeremy Morse 
3414010108bbSJeremy Morse   /// SSAUpdater has requested a PHI: create that within this block record.
newPHI(BlockValueNum Value)3415010108bbSJeremy Morse   LDVSSAPhi *newPHI(BlockValueNum Value) {
3416010108bbSJeremy Morse     PHIList.emplace_back(Value, this);
3417010108bbSJeremy Morse     return &PHIList.back();
3418010108bbSJeremy Morse   }
3419010108bbSJeremy Morse 
3420010108bbSJeremy Morse   /// SSAUpdater wishes to know what PHIs already exist in this block.
phis()3421010108bbSJeremy Morse   PHIListT &phis() { return PHIList; }
3422010108bbSJeremy Morse };
3423010108bbSJeremy Morse 
3424010108bbSJeremy Morse /// Utility class for the SSAUpdater interface: tracks blocks, PHIs and values
3425010108bbSJeremy Morse /// while SSAUpdater is exploring the CFG. It's passed as a handle / baton to
3426010108bbSJeremy Morse // SSAUpdaterTraits<LDVSSAUpdater>.
3427010108bbSJeremy Morse class LDVSSAUpdater {
3428010108bbSJeremy Morse public:
3429010108bbSJeremy Morse   /// Map of value numbers to PHI records.
3430010108bbSJeremy Morse   DenseMap<BlockValueNum, LDVSSAPhi *> PHIs;
3431010108bbSJeremy Morse   /// Map of which blocks generate Undef values -- blocks that are not
3432010108bbSJeremy Morse   /// dominated by any Def.
3433010108bbSJeremy Morse   DenseMap<MachineBasicBlock *, BlockValueNum> UndefMap;
3434010108bbSJeremy Morse   /// Map of machine blocks to our own records of them.
3435010108bbSJeremy Morse   DenseMap<MachineBasicBlock *, LDVSSABlock *> BlockMap;
3436010108bbSJeremy Morse   /// Machine location where any PHI must occur.
3437010108bbSJeremy Morse   LocIdx Loc;
3438010108bbSJeremy Morse   /// Table of live-in machine value numbers for blocks / locations.
3439ab49dce0SJeremy Morse   const ValueTable *MLiveIns;
3440010108bbSJeremy Morse 
LDVSSAUpdater(LocIdx L,const ValueTable * MLiveIns)3441ab49dce0SJeremy Morse   LDVSSAUpdater(LocIdx L, const ValueTable *MLiveIns)
3442ab49dce0SJeremy Morse       : Loc(L), MLiveIns(MLiveIns) {}
3443010108bbSJeremy Morse 
reset()3444010108bbSJeremy Morse   void reset() {
3445e63b18bcSJeremy Morse     for (auto &Block : BlockMap)
3446e63b18bcSJeremy Morse       delete Block.second;
3447e63b18bcSJeremy Morse 
3448010108bbSJeremy Morse     PHIs.clear();
3449010108bbSJeremy Morse     UndefMap.clear();
3450010108bbSJeremy Morse     BlockMap.clear();
3451010108bbSJeremy Morse   }
3452010108bbSJeremy Morse 
~LDVSSAUpdater()3453010108bbSJeremy Morse   ~LDVSSAUpdater() { reset(); }
3454010108bbSJeremy Morse 
3455010108bbSJeremy Morse   /// For a given MBB, create a wrapper block for it. Stores it in the
3456010108bbSJeremy Morse   /// LDVSSAUpdater block map.
getSSALDVBlock(MachineBasicBlock * BB)3457010108bbSJeremy Morse   LDVSSABlock *getSSALDVBlock(MachineBasicBlock *BB) {
3458010108bbSJeremy Morse     auto it = BlockMap.find(BB);
3459010108bbSJeremy Morse     if (it == BlockMap.end()) {
3460010108bbSJeremy Morse       BlockMap[BB] = new LDVSSABlock(*BB, *this);
3461010108bbSJeremy Morse       it = BlockMap.find(BB);
3462010108bbSJeremy Morse     }
3463010108bbSJeremy Morse     return it->second;
3464010108bbSJeremy Morse   }
3465010108bbSJeremy Morse 
3466010108bbSJeremy Morse   /// Find the live-in value number for the given block. Looks up the value at
3467010108bbSJeremy Morse   /// the PHI location on entry.
getValue(LDVSSABlock * LDVBB)3468010108bbSJeremy Morse   BlockValueNum getValue(LDVSSABlock *LDVBB) {
3469010108bbSJeremy Morse     return MLiveIns[LDVBB->BB.getNumber()][Loc.asU64()].asU64();
3470010108bbSJeremy Morse   }
3471010108bbSJeremy Morse };
3472010108bbSJeremy Morse 
operator *()3473010108bbSJeremy Morse LDVSSABlock *LDVSSABlockIterator::operator*() {
3474010108bbSJeremy Morse   return Updater.getSSALDVBlock(*PredIt);
3475010108bbSJeremy Morse }
3476010108bbSJeremy Morse 
3477632e15e7SDavid Blaikie #ifndef NDEBUG
3478010108bbSJeremy Morse 
operator <<(raw_ostream & out,const LDVSSAPhi & PHI)3479010108bbSJeremy Morse raw_ostream &operator<<(raw_ostream &out, const LDVSSAPhi &PHI) {
3480010108bbSJeremy Morse   out << "SSALDVPHI " << PHI.PHIValNum;
3481010108bbSJeremy Morse   return out;
3482010108bbSJeremy Morse }
3483010108bbSJeremy Morse 
3484632e15e7SDavid Blaikie #endif
3485632e15e7SDavid Blaikie 
3486632e15e7SDavid Blaikie } // namespace
3487632e15e7SDavid Blaikie 
3488632e15e7SDavid Blaikie namespace llvm {
3489632e15e7SDavid Blaikie 
3490010108bbSJeremy Morse /// Template specialization to give SSAUpdater access to CFG and value
3491010108bbSJeremy Morse /// information. SSAUpdater calls methods in these traits, passing in the
3492010108bbSJeremy Morse /// LDVSSAUpdater object, to learn about blocks and the values they define.
3493010108bbSJeremy Morse /// It also provides methods to create PHI nodes and track them.
3494010108bbSJeremy Morse template <> class SSAUpdaterTraits<LDVSSAUpdater> {
3495010108bbSJeremy Morse public:
3496010108bbSJeremy Morse   using BlkT = LDVSSABlock;
3497010108bbSJeremy Morse   using ValT = BlockValueNum;
3498010108bbSJeremy Morse   using PhiT = LDVSSAPhi;
3499010108bbSJeremy Morse   using BlkSucc_iterator = LDVSSABlockIterator;
3500010108bbSJeremy Morse 
3501010108bbSJeremy Morse   // Methods to access block successors -- dereferencing to our wrapper class.
BlkSucc_begin(BlkT * BB)3502010108bbSJeremy Morse   static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); }
BlkSucc_end(BlkT * BB)3503010108bbSJeremy Morse   static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); }
3504010108bbSJeremy Morse 
3505010108bbSJeremy Morse   /// Iterator for PHI operands.
3506010108bbSJeremy Morse   class PHI_iterator {
3507010108bbSJeremy Morse   private:
3508010108bbSJeremy Morse     LDVSSAPhi *PHI;
3509010108bbSJeremy Morse     unsigned Idx;
3510010108bbSJeremy Morse 
3511010108bbSJeremy Morse   public:
PHI_iterator(LDVSSAPhi * P)3512010108bbSJeremy Morse     explicit PHI_iterator(LDVSSAPhi *P) // begin iterator
3513010108bbSJeremy Morse         : PHI(P), Idx(0) {}
PHI_iterator(LDVSSAPhi * P,bool)3514010108bbSJeremy Morse     PHI_iterator(LDVSSAPhi *P, bool) // end iterator
3515010108bbSJeremy Morse         : PHI(P), Idx(PHI->IncomingValues.size()) {}
3516010108bbSJeremy Morse 
operator ++()3517010108bbSJeremy Morse     PHI_iterator &operator++() {
3518010108bbSJeremy Morse       Idx++;
3519010108bbSJeremy Morse       return *this;
3520010108bbSJeremy Morse     }
operator ==(const PHI_iterator & X) const3521010108bbSJeremy Morse     bool operator==(const PHI_iterator &X) const { return Idx == X.Idx; }
operator !=(const PHI_iterator & X) const3522010108bbSJeremy Morse     bool operator!=(const PHI_iterator &X) const { return !operator==(X); }
3523010108bbSJeremy Morse 
getIncomingValue()3524010108bbSJeremy Morse     BlockValueNum getIncomingValue() { return PHI->IncomingValues[Idx].second; }
3525010108bbSJeremy Morse 
getIncomingBlock()3526010108bbSJeremy Morse     LDVSSABlock *getIncomingBlock() { return PHI->IncomingValues[Idx].first; }
3527010108bbSJeremy Morse   };
3528010108bbSJeremy Morse 
PHI_begin(PhiT * PHI)3529010108bbSJeremy Morse   static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
3530010108bbSJeremy Morse 
PHI_end(PhiT * PHI)3531010108bbSJeremy Morse   static inline PHI_iterator PHI_end(PhiT *PHI) {
3532010108bbSJeremy Morse     return PHI_iterator(PHI, true);
3533010108bbSJeremy Morse   }
3534010108bbSJeremy Morse 
3535010108bbSJeremy Morse   /// FindPredecessorBlocks - Put the predecessors of BB into the Preds
3536010108bbSJeremy Morse   /// vector.
FindPredecessorBlocks(LDVSSABlock * BB,SmallVectorImpl<LDVSSABlock * > * Preds)3537010108bbSJeremy Morse   static void FindPredecessorBlocks(LDVSSABlock *BB,
3538010108bbSJeremy Morse                                     SmallVectorImpl<LDVSSABlock *> *Preds) {
3539ef2d0e0fSKazu Hirata     for (MachineBasicBlock *Pred : BB->BB.predecessors())
3540ef2d0e0fSKazu Hirata       Preds->push_back(BB->Updater.getSSALDVBlock(Pred));
3541010108bbSJeremy Morse   }
3542010108bbSJeremy Morse 
3543010108bbSJeremy Morse   /// GetUndefVal - Normally creates an IMPLICIT_DEF instruction with a new
3544010108bbSJeremy Morse   /// register. For LiveDebugValues, represents a block identified as not having
3545010108bbSJeremy Morse   /// any DBG_PHI predecessors.
GetUndefVal(LDVSSABlock * BB,LDVSSAUpdater * Updater)3546010108bbSJeremy Morse   static BlockValueNum GetUndefVal(LDVSSABlock *BB, LDVSSAUpdater *Updater) {
3547010108bbSJeremy Morse     // Create a value number for this block -- it needs to be unique and in the
3548010108bbSJeremy Morse     // "undef" collection, so that we know it's not real. Use a number
3549010108bbSJeremy Morse     // representing a PHI into this block.
3550010108bbSJeremy Morse     BlockValueNum Num = ValueIDNum(BB->BB.getNumber(), 0, Updater->Loc).asU64();
3551010108bbSJeremy Morse     Updater->UndefMap[&BB->BB] = Num;
3552010108bbSJeremy Morse     return Num;
3553010108bbSJeremy Morse   }
3554010108bbSJeremy Morse 
3555010108bbSJeremy Morse   /// CreateEmptyPHI - Create a (representation of a) PHI in the given block.
3556010108bbSJeremy Morse   /// SSAUpdater will populate it with information about incoming values. The
3557010108bbSJeremy Morse   /// value number of this PHI is whatever the  machine value number problem
3558010108bbSJeremy Morse   /// solution determined it to be. This includes non-phi values if SSAUpdater
3559010108bbSJeremy Morse   /// tries to create a PHI where the incoming values are identical.
CreateEmptyPHI(LDVSSABlock * BB,unsigned NumPreds,LDVSSAUpdater * Updater)3560010108bbSJeremy Morse   static BlockValueNum CreateEmptyPHI(LDVSSABlock *BB, unsigned NumPreds,
3561010108bbSJeremy Morse                                    LDVSSAUpdater *Updater) {
3562010108bbSJeremy Morse     BlockValueNum PHIValNum = Updater->getValue(BB);
3563010108bbSJeremy Morse     LDVSSAPhi *PHI = BB->newPHI(PHIValNum);
3564010108bbSJeremy Morse     Updater->PHIs[PHIValNum] = PHI;
3565010108bbSJeremy Morse     return PHIValNum;
3566010108bbSJeremy Morse   }
3567010108bbSJeremy Morse 
3568010108bbSJeremy Morse   /// AddPHIOperand - Add the specified value as an operand of the PHI for
3569010108bbSJeremy Morse   /// the specified predecessor block.
AddPHIOperand(LDVSSAPhi * PHI,BlockValueNum Val,LDVSSABlock * Pred)3570010108bbSJeremy Morse   static void AddPHIOperand(LDVSSAPhi *PHI, BlockValueNum Val, LDVSSABlock *Pred) {
3571010108bbSJeremy Morse     PHI->IncomingValues.push_back(std::make_pair(Pred, Val));
3572010108bbSJeremy Morse   }
3573010108bbSJeremy Morse 
3574010108bbSJeremy Morse   /// ValueIsPHI - Check if the instruction that defines the specified value
3575010108bbSJeremy Morse   /// is a PHI instruction.
ValueIsPHI(BlockValueNum Val,LDVSSAUpdater * Updater)3576010108bbSJeremy Morse   static LDVSSAPhi *ValueIsPHI(BlockValueNum Val, LDVSSAUpdater *Updater) {
3577010108bbSJeremy Morse     auto PHIIt = Updater->PHIs.find(Val);
3578010108bbSJeremy Morse     if (PHIIt == Updater->PHIs.end())
3579010108bbSJeremy Morse       return nullptr;
3580010108bbSJeremy Morse     return PHIIt->second;
3581010108bbSJeremy Morse   }
3582010108bbSJeremy Morse 
3583010108bbSJeremy Morse   /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
3584010108bbSJeremy Morse   /// operands, i.e., it was just added.
ValueIsNewPHI(BlockValueNum Val,LDVSSAUpdater * Updater)3585010108bbSJeremy Morse   static LDVSSAPhi *ValueIsNewPHI(BlockValueNum Val, LDVSSAUpdater *Updater) {
3586010108bbSJeremy Morse     LDVSSAPhi *PHI = ValueIsPHI(Val, Updater);
3587010108bbSJeremy Morse     if (PHI && PHI->IncomingValues.size() == 0)
3588010108bbSJeremy Morse       return PHI;
3589010108bbSJeremy Morse     return nullptr;
3590010108bbSJeremy Morse   }
3591010108bbSJeremy Morse 
3592010108bbSJeremy Morse   /// GetPHIValue - For the specified PHI instruction, return the value
3593010108bbSJeremy Morse   /// that it defines.
GetPHIValue(LDVSSAPhi * PHI)3594010108bbSJeremy Morse   static BlockValueNum GetPHIValue(LDVSSAPhi *PHI) { return PHI->PHIValNum; }
3595010108bbSJeremy Morse };
3596010108bbSJeremy Morse 
3597010108bbSJeremy Morse } // end namespace llvm
3598010108bbSJeremy Morse 
resolveDbgPHIs(MachineFunction & MF,const ValueTable * MLiveOuts,const ValueTable * MLiveIns,MachineInstr & Here,uint64_t InstrNum)3599ab49dce0SJeremy Morse Optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIs(
3600ab49dce0SJeremy Morse     MachineFunction &MF, const ValueTable *MLiveOuts,
3601ab49dce0SJeremy Morse     const ValueTable *MLiveIns, MachineInstr &Here, uint64_t InstrNum) {
3602ab49dce0SJeremy Morse   assert(MLiveOuts && MLiveIns &&
3603ab49dce0SJeremy Morse          "Tried to resolve DBG_PHI before location "
3604ab49dce0SJeremy Morse          "tables allocated?");
3605ab49dce0SJeremy Morse 
3606d556eb7eSJeremy Morse   // This function will be called twice per DBG_INSTR_REF, and might end up
3607d556eb7eSJeremy Morse   // computing lots of SSA information: memoize it.
3608d556eb7eSJeremy Morse   auto SeenDbgPHIIt = SeenDbgPHIs.find(&Here);
3609d556eb7eSJeremy Morse   if (SeenDbgPHIIt != SeenDbgPHIs.end())
3610d556eb7eSJeremy Morse     return SeenDbgPHIIt->second;
3611d556eb7eSJeremy Morse 
3612d556eb7eSJeremy Morse   Optional<ValueIDNum> Result =
3613d556eb7eSJeremy Morse       resolveDbgPHIsImpl(MF, MLiveOuts, MLiveIns, Here, InstrNum);
3614d556eb7eSJeremy Morse   SeenDbgPHIs.insert({&Here, Result});
3615d556eb7eSJeremy Morse   return Result;
3616d556eb7eSJeremy Morse }
3617d556eb7eSJeremy Morse 
resolveDbgPHIsImpl(MachineFunction & MF,const ValueTable * MLiveOuts,const ValueTable * MLiveIns,MachineInstr & Here,uint64_t InstrNum)3618d556eb7eSJeremy Morse Optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIsImpl(
3619ab49dce0SJeremy Morse     MachineFunction &MF, const ValueTable *MLiveOuts,
3620ab49dce0SJeremy Morse     const ValueTable *MLiveIns, MachineInstr &Here, uint64_t InstrNum) {
3621010108bbSJeremy Morse   // Pick out records of DBG_PHI instructions that have been observed. If there
3622010108bbSJeremy Morse   // are none, then we cannot compute a value number.
3623010108bbSJeremy Morse   auto RangePair = std::equal_range(DebugPHINumToValue.begin(),
3624010108bbSJeremy Morse                                     DebugPHINumToValue.end(), InstrNum);
3625010108bbSJeremy Morse   auto LowerIt = RangePair.first;
3626010108bbSJeremy Morse   auto UpperIt = RangePair.second;
3627010108bbSJeremy Morse 
3628010108bbSJeremy Morse   // No DBG_PHI means there can be no location.
3629010108bbSJeremy Morse   if (LowerIt == UpperIt)
3630010108bbSJeremy Morse     return None;
3631010108bbSJeremy Morse 
3632be5734ddSJeremy Morse   // If any DBG_PHIs referred to a location we didn't understand, don't try to
3633be5734ddSJeremy Morse   // compute a value. There might be scenarios where we could recover a value
3634be5734ddSJeremy Morse   // for some range of DBG_INSTR_REFs, but at this point we can have high
3635be5734ddSJeremy Morse   // confidence that we've seen a bug.
3636be5734ddSJeremy Morse   auto DBGPHIRange = make_range(LowerIt, UpperIt);
3637be5734ddSJeremy Morse   for (const DebugPHIRecord &DBG_PHI : DBGPHIRange)
3638be5734ddSJeremy Morse     if (!DBG_PHI.ValueRead)
3639be5734ddSJeremy Morse       return None;
3640be5734ddSJeremy Morse 
3641010108bbSJeremy Morse   // If there's only one DBG_PHI, then that is our value number.
3642010108bbSJeremy Morse   if (std::distance(LowerIt, UpperIt) == 1)
3643be5734ddSJeremy Morse     return *LowerIt->ValueRead;
3644010108bbSJeremy Morse 
3645010108bbSJeremy Morse   // Pick out the location (physreg, slot) where any PHIs must occur. It's
3646010108bbSJeremy Morse   // technically possible for us to merge values in different registers in each
3647010108bbSJeremy Morse   // block, but highly unlikely that LLVM will generate such code after register
3648010108bbSJeremy Morse   // allocation.
3649be5734ddSJeremy Morse   LocIdx Loc = *LowerIt->ReadLoc;
3650010108bbSJeremy Morse 
3651010108bbSJeremy Morse   // We have several DBG_PHIs, and a use position (the Here inst). All each
3652010108bbSJeremy Morse   // DBG_PHI does is identify a value at a program position. We can treat each
3653010108bbSJeremy Morse   // DBG_PHI like it's a Def of a value, and the use position is a Use of a
3654010108bbSJeremy Morse   // value, just like SSA. We use the bulk-standard LLVM SSA updater class to
3655010108bbSJeremy Morse   // determine which Def is used at the Use, and any PHIs that happen along
3656010108bbSJeremy Morse   // the way.
3657010108bbSJeremy Morse   // Adapted LLVM SSA Updater:
3658010108bbSJeremy Morse   LDVSSAUpdater Updater(Loc, MLiveIns);
3659010108bbSJeremy Morse   // Map of which Def or PHI is the current value in each block.
3660010108bbSJeremy Morse   DenseMap<LDVSSABlock *, BlockValueNum> AvailableValues;
3661010108bbSJeremy Morse   // Set of PHIs that we have created along the way.
3662010108bbSJeremy Morse   SmallVector<LDVSSAPhi *, 8> CreatedPHIs;
3663010108bbSJeremy Morse 
3664010108bbSJeremy Morse   // Each existing DBG_PHI is a Def'd value under this model. Record these Defs
3665010108bbSJeremy Morse   // for the SSAUpdater.
3666010108bbSJeremy Morse   for (const auto &DBG_PHI : DBGPHIRange) {
3667010108bbSJeremy Morse     LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB);
3668be5734ddSJeremy Morse     const ValueIDNum &Num = *DBG_PHI.ValueRead;
3669010108bbSJeremy Morse     AvailableValues.insert(std::make_pair(Block, Num.asU64()));
3670010108bbSJeremy Morse   }
3671010108bbSJeremy Morse 
3672010108bbSJeremy Morse   LDVSSABlock *HereBlock = Updater.getSSALDVBlock(Here.getParent());
3673010108bbSJeremy Morse   const auto &AvailIt = AvailableValues.find(HereBlock);
3674010108bbSJeremy Morse   if (AvailIt != AvailableValues.end()) {
3675010108bbSJeremy Morse     // Actually, we already know what the value is -- the Use is in the same
3676010108bbSJeremy Morse     // block as the Def.
3677010108bbSJeremy Morse     return ValueIDNum::fromU64(AvailIt->second);
3678010108bbSJeremy Morse   }
3679010108bbSJeremy Morse 
3680010108bbSJeremy Morse   // Otherwise, we must use the SSA Updater. It will identify the value number
3681010108bbSJeremy Morse   // that we are to use, and the PHIs that must happen along the way.
3682010108bbSJeremy Morse   SSAUpdaterImpl<LDVSSAUpdater> Impl(&Updater, &AvailableValues, &CreatedPHIs);
3683010108bbSJeremy Morse   BlockValueNum ResultInt = Impl.GetValue(Updater.getSSALDVBlock(Here.getParent()));
3684010108bbSJeremy Morse   ValueIDNum Result = ValueIDNum::fromU64(ResultInt);
3685010108bbSJeremy Morse 
3686010108bbSJeremy Morse   // We have the number for a PHI, or possibly live-through value, to be used
3687010108bbSJeremy Morse   // at this Use. There are a number of things we have to check about it though:
3688010108bbSJeremy Morse   //  * Does any PHI use an 'Undef' (like an IMPLICIT_DEF) value? If so, this
3689010108bbSJeremy Morse   //    Use was not completely dominated by DBG_PHIs and we should abort.
3690010108bbSJeremy Morse   //  * Are the Defs or PHIs clobbered in a block? SSAUpdater isn't aware that
3691010108bbSJeremy Morse   //    we've left SSA form. Validate that the inputs to each PHI are the
3692010108bbSJeremy Morse   //    expected values.
3693010108bbSJeremy Morse   //  * Is a PHI we've created actually a merging of values, or are all the
3694010108bbSJeremy Morse   //    predecessor values the same, leading to a non-PHI machine value number?
3695010108bbSJeremy Morse   //    (SSAUpdater doesn't know that either). Remap validated PHIs into the
3696010108bbSJeremy Morse   //    the ValidatedValues collection below to sort this out.
3697010108bbSJeremy Morse   DenseMap<LDVSSABlock *, ValueIDNum> ValidatedValues;
3698010108bbSJeremy Morse 
3699010108bbSJeremy Morse   // Define all the input DBG_PHI values in ValidatedValues.
3700010108bbSJeremy Morse   for (const auto &DBG_PHI : DBGPHIRange) {
3701010108bbSJeremy Morse     LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB);
3702be5734ddSJeremy Morse     const ValueIDNum &Num = *DBG_PHI.ValueRead;
3703010108bbSJeremy Morse     ValidatedValues.insert(std::make_pair(Block, Num));
3704010108bbSJeremy Morse   }
3705010108bbSJeremy Morse 
3706010108bbSJeremy Morse   // Sort PHIs to validate into RPO-order.
3707010108bbSJeremy Morse   SmallVector<LDVSSAPhi *, 8> SortedPHIs;
3708010108bbSJeremy Morse   for (auto &PHI : CreatedPHIs)
3709010108bbSJeremy Morse     SortedPHIs.push_back(PHI);
3710010108bbSJeremy Morse 
3711aba43035SDmitri Gribenko   llvm::sort(SortedPHIs, [&](LDVSSAPhi *A, LDVSSAPhi *B) {
3712010108bbSJeremy Morse     return BBToOrder[&A->getParent()->BB] < BBToOrder[&B->getParent()->BB];
3713010108bbSJeremy Morse   });
3714010108bbSJeremy Morse 
3715010108bbSJeremy Morse   for (auto &PHI : SortedPHIs) {
3716010108bbSJeremy Morse     ValueIDNum ThisBlockValueNum =
3717010108bbSJeremy Morse         MLiveIns[PHI->ParentBlock->BB.getNumber()][Loc.asU64()];
3718010108bbSJeremy Morse 
3719010108bbSJeremy Morse     // Are all these things actually defined?
3720010108bbSJeremy Morse     for (auto &PHIIt : PHI->IncomingValues) {
3721010108bbSJeremy Morse       // Any undef input means DBG_PHIs didn't dominate the use point.
3722010108bbSJeremy Morse       if (Updater.UndefMap.find(&PHIIt.first->BB) != Updater.UndefMap.end())
3723010108bbSJeremy Morse         return None;
3724010108bbSJeremy Morse 
3725010108bbSJeremy Morse       ValueIDNum ValueToCheck;
3726ab49dce0SJeremy Morse       const ValueTable &BlockLiveOuts = MLiveOuts[PHIIt.first->BB.getNumber()];
3727010108bbSJeremy Morse 
3728010108bbSJeremy Morse       auto VVal = ValidatedValues.find(PHIIt.first);
3729010108bbSJeremy Morse       if (VVal == ValidatedValues.end()) {
3730010108bbSJeremy Morse         // We cross a loop, and this is a backedge. LLVMs tail duplication
3731010108bbSJeremy Morse         // happens so late that DBG_PHI instructions should not be able to
3732010108bbSJeremy Morse         // migrate into loops -- meaning we can only be live-through this
3733010108bbSJeremy Morse         // loop.
3734010108bbSJeremy Morse         ValueToCheck = ThisBlockValueNum;
3735010108bbSJeremy Morse       } else {
3736010108bbSJeremy Morse         // Does the block have as a live-out, in the location we're examining,
3737010108bbSJeremy Morse         // the value that we expect? If not, it's been moved or clobbered.
3738010108bbSJeremy Morse         ValueToCheck = VVal->second;
3739010108bbSJeremy Morse       }
3740010108bbSJeremy Morse 
3741010108bbSJeremy Morse       if (BlockLiveOuts[Loc.asU64()] != ValueToCheck)
3742010108bbSJeremy Morse         return None;
3743010108bbSJeremy Morse     }
3744010108bbSJeremy Morse 
3745010108bbSJeremy Morse     // Record this value as validated.
3746010108bbSJeremy Morse     ValidatedValues.insert({PHI->ParentBlock, ThisBlockValueNum});
3747010108bbSJeremy Morse   }
3748010108bbSJeremy Morse 
3749010108bbSJeremy Morse   // All the PHIs are valid: we can return what the SSAUpdater said our value
3750010108bbSJeremy Morse   // number was.
3751010108bbSJeremy Morse   return Result;
3752010108bbSJeremy Morse }
3753