xref: /src/contrib/llvm-project/llvm/lib/CodeGen/LiveDebugVariables.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1cf099d11SDimitry Andric //===- LiveDebugVariables.cpp - Tracking debug info variables -------------===//
2cf099d11SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6cf099d11SDimitry Andric //
7cf099d11SDimitry Andric //===----------------------------------------------------------------------===//
8cf099d11SDimitry Andric //
9cf099d11SDimitry Andric // This file implements the LiveDebugVariables analysis.
10cf099d11SDimitry Andric //
11cf099d11SDimitry Andric // Remove all DBG_VALUE instructions referencing virtual registers and replace
12cf099d11SDimitry Andric // them with a data structure tracking where live user variables are kept - in a
13cf099d11SDimitry Andric // virtual register or in a stack slot.
14cf099d11SDimitry Andric //
15cf099d11SDimitry Andric // Allow the data structure to be updated during register allocation when values
16cf099d11SDimitry Andric // are moved between registers and stack slots. Finally emit new DBG_VALUE
17cf099d11SDimitry Andric // instructions after register allocation is complete.
18cf099d11SDimitry Andric //
19cf099d11SDimitry Andric //===----------------------------------------------------------------------===//
20cf099d11SDimitry Andric 
21ac9a064cSDimitry Andric #include "llvm/CodeGen/LiveDebugVariables.h"
22044eb2f6SDimitry Andric #include "llvm/ADT/ArrayRef.h"
23044eb2f6SDimitry Andric #include "llvm/ADT/DenseMap.h"
24cf099d11SDimitry Andric #include "llvm/ADT/IntervalMap.h"
25e6d15924SDimitry Andric #include "llvm/ADT/MapVector.h"
26044eb2f6SDimitry Andric #include "llvm/ADT/STLExtras.h"
27044eb2f6SDimitry Andric #include "llvm/ADT/SmallSet.h"
28044eb2f6SDimitry Andric #include "llvm/ADT/SmallVector.h"
2930815c53SDimitry Andric #include "llvm/ADT/Statistic.h"
30044eb2f6SDimitry Andric #include "llvm/ADT/StringRef.h"
31145449b1SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
32044eb2f6SDimitry Andric #include "llvm/CodeGen/LexicalScopes.h"
33044eb2f6SDimitry Andric #include "llvm/CodeGen/LiveInterval.h"
34044eb2f6SDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
35044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
36cf099d11SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
37cf099d11SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
38044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
39cf099d11SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
40044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
416b943ff3SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
42044eb2f6SDimitry Andric #include "llvm/CodeGen/SlotIndexes.h"
43044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
44044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
45044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
46044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
474a16efa3SDimitry Andric #include "llvm/CodeGen/VirtRegMap.h"
48eb11fae6SDimitry Andric #include "llvm/Config/llvm-config.h"
49044eb2f6SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
50044eb2f6SDimitry Andric #include "llvm/IR/DebugLoc.h"
51044eb2f6SDimitry Andric #include "llvm/IR/Function.h"
52706b4fc4SDimitry Andric #include "llvm/InitializePasses.h"
53044eb2f6SDimitry Andric #include "llvm/Pass.h"
54044eb2f6SDimitry Andric #include "llvm/Support/Casting.h"
55cf099d11SDimitry Andric #include "llvm/Support/CommandLine.h"
56cf099d11SDimitry Andric #include "llvm/Support/Debug.h"
575a5ac124SDimitry Andric #include "llvm/Support/raw_ostream.h"
58044eb2f6SDimitry Andric #include <algorithm>
59044eb2f6SDimitry Andric #include <cassert>
60044eb2f6SDimitry Andric #include <iterator>
61b1c73532SDimitry Andric #include <map>
625ca98fd9SDimitry Andric #include <memory>
63e3b55780SDimitry Andric #include <optional>
6401095a5dSDimitry Andric #include <utility>
655ca98fd9SDimitry Andric 
66cf099d11SDimitry Andric using namespace llvm;
67cf099d11SDimitry Andric 
68ab44ce3dSDimitry Andric #define DEBUG_TYPE "livedebugvars"
695ca98fd9SDimitry Andric 
70cf099d11SDimitry Andric static cl::opt<bool>
71cf099d11SDimitry Andric EnableLDV("live-debug-variables", cl::init(true),
72cf099d11SDimitry Andric           cl::desc("Enable the live debug variables pass"), cl::Hidden);
73cf099d11SDimitry Andric 
7430815c53SDimitry Andric STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
75e6d15924SDimitry Andric STATISTIC(NumInsertedDebugLabels, "Number of DBG_LABELs inserted");
76044eb2f6SDimitry Andric 
77cf099d11SDimitry Andric char LiveDebugVariables::ID = 0;
78cf099d11SDimitry Andric 
79ab44ce3dSDimitry Andric INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE,
80cf099d11SDimitry Andric                 "Debug Variable Analysis", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)81ac9a064cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass)
82ac9a064cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(LiveIntervalsWrapperPass)
83ab44ce3dSDimitry Andric INITIALIZE_PASS_END(LiveDebugVariables, DEBUG_TYPE,
84cf099d11SDimitry Andric                 "Debug Variable Analysis", false, false)
85cf099d11SDimitry Andric 
86cf099d11SDimitry Andric void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
87ac9a064cSDimitry Andric   AU.addRequired<MachineDominatorTreeWrapperPass>();
88ac9a064cSDimitry Andric   AU.addRequiredTransitive<LiveIntervalsWrapperPass>();
89cf099d11SDimitry Andric   AU.setPreservesAll();
90cf099d11SDimitry Andric   MachineFunctionPass::getAnalysisUsage(AU);
91cf099d11SDimitry Andric }
92cf099d11SDimitry Andric 
LiveDebugVariables()93044eb2f6SDimitry Andric LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID) {
94cf099d11SDimitry Andric   initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
95cf099d11SDimitry Andric }
96cf099d11SDimitry Andric 
97044eb2f6SDimitry Andric enum : unsigned { UndefLocNo = ~0U };
98044eb2f6SDimitry Andric 
99b60736ecSDimitry Andric namespace {
100cfca06d7SDimitry Andric /// Describes a debug variable value by location number and expression along
101cfca06d7SDimitry Andric /// with some flags about the original usage of the location.
102cfca06d7SDimitry Andric class DbgVariableValue {
103044eb2f6SDimitry Andric public:
DbgVariableValue(ArrayRef<unsigned> NewLocs,bool WasIndirect,bool WasList,const DIExpression & Expr)104344a3780SDimitry Andric   DbgVariableValue(ArrayRef<unsigned> NewLocs, bool WasIndirect, bool WasList,
105344a3780SDimitry Andric                    const DIExpression &Expr)
106344a3780SDimitry Andric       : WasIndirect(WasIndirect), WasList(WasList), Expression(&Expr) {
107344a3780SDimitry Andric     assert(!(WasIndirect && WasList) &&
108344a3780SDimitry Andric            "DBG_VALUE_LISTs should not be indirect.");
109344a3780SDimitry Andric     SmallVector<unsigned> LocNoVec;
110344a3780SDimitry Andric     for (unsigned LocNo : NewLocs) {
111344a3780SDimitry Andric       auto It = find(LocNoVec, LocNo);
112344a3780SDimitry Andric       if (It == LocNoVec.end())
113344a3780SDimitry Andric         LocNoVec.push_back(LocNo);
114344a3780SDimitry Andric       else {
115344a3780SDimitry Andric         // Loc duplicates an element in LocNos; replace references to Op
116344a3780SDimitry Andric         // with references to the duplicating element.
117344a3780SDimitry Andric         unsigned OpIdx = LocNoVec.size();
118344a3780SDimitry Andric         unsigned DuplicatingIdx = std::distance(LocNoVec.begin(), It);
119344a3780SDimitry Andric         Expression =
120344a3780SDimitry Andric             DIExpression::replaceArg(Expression, OpIdx, DuplicatingIdx);
121344a3780SDimitry Andric       }
122344a3780SDimitry Andric     }
123344a3780SDimitry Andric     // FIXME: Debug values referencing 64+ unique machine locations are rare and
124344a3780SDimitry Andric     // currently unsupported for performance reasons. If we can verify that
125344a3780SDimitry Andric     // performance is acceptable for such debug values, we can increase the
126344a3780SDimitry Andric     // bit-width of LocNoCount to 14 to enable up to 16384 unique machine
127344a3780SDimitry Andric     // locations. We will also need to verify that this does not cause issues
128344a3780SDimitry Andric     // with LiveDebugVariables' use of IntervalMap.
129344a3780SDimitry Andric     if (LocNoVec.size() < 64) {
130344a3780SDimitry Andric       LocNoCount = LocNoVec.size();
131344a3780SDimitry Andric       if (LocNoCount > 0) {
132344a3780SDimitry Andric         LocNos = std::make_unique<unsigned[]>(LocNoCount);
133344a3780SDimitry Andric         std::copy(LocNoVec.begin(), LocNoVec.end(), loc_nos_begin());
134344a3780SDimitry Andric       }
135344a3780SDimitry Andric     } else {
136344a3780SDimitry Andric       LLVM_DEBUG(dbgs() << "Found debug value with 64+ unique machine "
137344a3780SDimitry Andric                            "locations, dropping...\n");
138344a3780SDimitry Andric       LocNoCount = 1;
139344a3780SDimitry Andric       // Turn this into an undef debug value list; right now, the simplest form
140344a3780SDimitry Andric       // of this is an expression with one arg, and an undef debug operand.
141344a3780SDimitry Andric       Expression =
142e3b55780SDimitry Andric           DIExpression::get(Expr.getContext(), {dwarf::DW_OP_LLVM_arg, 0});
143344a3780SDimitry Andric       if (auto FragmentInfoOpt = Expr.getFragmentInfo())
144344a3780SDimitry Andric         Expression = *DIExpression::createFragmentExpression(
145344a3780SDimitry Andric             Expression, FragmentInfoOpt->OffsetInBits,
146344a3780SDimitry Andric             FragmentInfoOpt->SizeInBits);
147344a3780SDimitry Andric       LocNos = std::make_unique<unsigned[]>(LocNoCount);
148344a3780SDimitry Andric       LocNos[0] = UndefLocNo;
149344a3780SDimitry Andric     }
150044eb2f6SDimitry Andric   }
151044eb2f6SDimitry Andric 
DbgVariableValue()1526f8fc217SDimitry Andric   DbgVariableValue() : LocNoCount(0), WasIndirect(false), WasList(false) {}
DbgVariableValue(const DbgVariableValue & Other)153344a3780SDimitry Andric   DbgVariableValue(const DbgVariableValue &Other)
154344a3780SDimitry Andric       : LocNoCount(Other.LocNoCount), WasIndirect(Other.getWasIndirect()),
155344a3780SDimitry Andric         WasList(Other.getWasList()), Expression(Other.getExpression()) {
156344a3780SDimitry Andric     if (Other.getLocNoCount()) {
157344a3780SDimitry Andric       LocNos.reset(new unsigned[Other.getLocNoCount()]);
158344a3780SDimitry Andric       std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin());
159344a3780SDimitry Andric     }
160344a3780SDimitry Andric   }
161344a3780SDimitry Andric 
operator =(const DbgVariableValue & Other)162344a3780SDimitry Andric   DbgVariableValue &operator=(const DbgVariableValue &Other) {
163344a3780SDimitry Andric     if (this == &Other)
164344a3780SDimitry Andric       return *this;
165344a3780SDimitry Andric     if (Other.getLocNoCount()) {
166344a3780SDimitry Andric       LocNos.reset(new unsigned[Other.getLocNoCount()]);
167344a3780SDimitry Andric       std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin());
168344a3780SDimitry Andric     } else {
169344a3780SDimitry Andric       LocNos.release();
170344a3780SDimitry Andric     }
171344a3780SDimitry Andric     LocNoCount = Other.getLocNoCount();
172344a3780SDimitry Andric     WasIndirect = Other.getWasIndirect();
173344a3780SDimitry Andric     WasList = Other.getWasList();
174344a3780SDimitry Andric     Expression = Other.getExpression();
175344a3780SDimitry Andric     return *this;
176344a3780SDimitry Andric   }
177044eb2f6SDimitry Andric 
getExpression() const178cfca06d7SDimitry Andric   const DIExpression *getExpression() const { return Expression; }
getLocNoCount() const179344a3780SDimitry Andric   uint8_t getLocNoCount() const { return LocNoCount; }
containsLocNo(unsigned LocNo) const180344a3780SDimitry Andric   bool containsLocNo(unsigned LocNo) const {
181344a3780SDimitry Andric     return is_contained(loc_nos(), LocNo);
182044eb2f6SDimitry Andric   }
getWasIndirect() const183cfca06d7SDimitry Andric   bool getWasIndirect() const { return WasIndirect; }
getWasList() const184344a3780SDimitry Andric   bool getWasList() const { return WasList; }
isUndef() const185344a3780SDimitry Andric   bool isUndef() const { return LocNoCount == 0 || containsLocNo(UndefLocNo); }
186044eb2f6SDimitry Andric 
decrementLocNosAfterPivot(unsigned Pivot) const187344a3780SDimitry Andric   DbgVariableValue decrementLocNosAfterPivot(unsigned Pivot) const {
188344a3780SDimitry Andric     SmallVector<unsigned, 4> NewLocNos;
189344a3780SDimitry Andric     for (unsigned LocNo : loc_nos())
190344a3780SDimitry Andric       NewLocNos.push_back(LocNo != UndefLocNo && LocNo > Pivot ? LocNo - 1
191344a3780SDimitry Andric                                                                : LocNo);
192344a3780SDimitry Andric     return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
193344a3780SDimitry Andric   }
194344a3780SDimitry Andric 
remapLocNos(ArrayRef<unsigned> LocNoMap) const195344a3780SDimitry Andric   DbgVariableValue remapLocNos(ArrayRef<unsigned> LocNoMap) const {
196344a3780SDimitry Andric     SmallVector<unsigned> NewLocNos;
197344a3780SDimitry Andric     for (unsigned LocNo : loc_nos())
198344a3780SDimitry Andric       // Undef values don't exist in locations (and thus not in LocNoMap
199344a3780SDimitry Andric       // either) so skip over them. See getLocationNo().
200344a3780SDimitry Andric       NewLocNos.push_back(LocNo == UndefLocNo ? UndefLocNo : LocNoMap[LocNo]);
201344a3780SDimitry Andric     return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
202344a3780SDimitry Andric   }
203344a3780SDimitry Andric 
changeLocNo(unsigned OldLocNo,unsigned NewLocNo) const204344a3780SDimitry Andric   DbgVariableValue changeLocNo(unsigned OldLocNo, unsigned NewLocNo) const {
205344a3780SDimitry Andric     SmallVector<unsigned> NewLocNos;
206344a3780SDimitry Andric     NewLocNos.assign(loc_nos_begin(), loc_nos_end());
207344a3780SDimitry Andric     auto OldLocIt = find(NewLocNos, OldLocNo);
208344a3780SDimitry Andric     assert(OldLocIt != NewLocNos.end() && "Old location must be present.");
209344a3780SDimitry Andric     *OldLocIt = NewLocNo;
210344a3780SDimitry Andric     return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
211344a3780SDimitry Andric   }
212344a3780SDimitry Andric 
hasLocNoGreaterThan(unsigned LocNo) const213344a3780SDimitry Andric   bool hasLocNoGreaterThan(unsigned LocNo) const {
214344a3780SDimitry Andric     return any_of(loc_nos(),
215344a3780SDimitry Andric                   [LocNo](unsigned ThisLocNo) { return ThisLocNo > LocNo; });
216344a3780SDimitry Andric   }
217344a3780SDimitry Andric 
printLocNos(llvm::raw_ostream & OS) const218344a3780SDimitry Andric   void printLocNos(llvm::raw_ostream &OS) const {
219344a3780SDimitry Andric     for (const unsigned &Loc : loc_nos())
220344a3780SDimitry Andric       OS << (&Loc == loc_nos_begin() ? " " : ", ") << Loc;
221044eb2f6SDimitry Andric   }
222044eb2f6SDimitry Andric 
operator ==(const DbgVariableValue & LHS,const DbgVariableValue & RHS)223cfca06d7SDimitry Andric   friend inline bool operator==(const DbgVariableValue &LHS,
224cfca06d7SDimitry Andric                                 const DbgVariableValue &RHS) {
225344a3780SDimitry Andric     if (std::tie(LHS.LocNoCount, LHS.WasIndirect, LHS.WasList,
226344a3780SDimitry Andric                  LHS.Expression) !=
227344a3780SDimitry Andric         std::tie(RHS.LocNoCount, RHS.WasIndirect, RHS.WasList, RHS.Expression))
228344a3780SDimitry Andric       return false;
229344a3780SDimitry Andric     return std::equal(LHS.loc_nos_begin(), LHS.loc_nos_end(),
230344a3780SDimitry Andric                       RHS.loc_nos_begin());
231044eb2f6SDimitry Andric   }
232044eb2f6SDimitry Andric 
operator !=(const DbgVariableValue & LHS,const DbgVariableValue & RHS)233cfca06d7SDimitry Andric   friend inline bool operator!=(const DbgVariableValue &LHS,
234cfca06d7SDimitry Andric                                 const DbgVariableValue &RHS) {
235044eb2f6SDimitry Andric     return !(LHS == RHS);
236044eb2f6SDimitry Andric   }
237044eb2f6SDimitry Andric 
loc_nos_begin()238344a3780SDimitry Andric   unsigned *loc_nos_begin() { return LocNos.get(); }
loc_nos_begin() const239344a3780SDimitry Andric   const unsigned *loc_nos_begin() const { return LocNos.get(); }
loc_nos_end()240344a3780SDimitry Andric   unsigned *loc_nos_end() { return LocNos.get() + LocNoCount; }
loc_nos_end() const241344a3780SDimitry Andric   const unsigned *loc_nos_end() const { return LocNos.get() + LocNoCount; }
loc_nos() const242344a3780SDimitry Andric   ArrayRef<unsigned> loc_nos() const {
243344a3780SDimitry Andric     return ArrayRef<unsigned>(LocNos.get(), LocNoCount);
244344a3780SDimitry Andric   }
245344a3780SDimitry Andric 
246044eb2f6SDimitry Andric private:
247344a3780SDimitry Andric   // IntervalMap requires the value object to be very small, to the extent
248344a3780SDimitry Andric   // that we do not have enough room for an std::vector. Using a C-style array
249344a3780SDimitry Andric   // (with a unique_ptr wrapper for convenience) allows us to optimize for this
250344a3780SDimitry Andric   // specific case by packing the array size into only 6 bits (it is highly
251344a3780SDimitry Andric   // unlikely that any debug value will need 64+ locations).
252344a3780SDimitry Andric   std::unique_ptr<unsigned[]> LocNos;
253344a3780SDimitry Andric   uint8_t LocNoCount : 6;
254344a3780SDimitry Andric   bool WasIndirect : 1;
255344a3780SDimitry Andric   bool WasList : 1;
256cfca06d7SDimitry Andric   const DIExpression *Expression = nullptr;
257044eb2f6SDimitry Andric };
258b60736ecSDimitry Andric } // namespace
259044eb2f6SDimitry Andric 
260cfca06d7SDimitry Andric /// Map of where a user value is live to that value.
261cfca06d7SDimitry Andric using LocMap = IntervalMap<SlotIndex, DbgVariableValue, 4>;
262044eb2f6SDimitry Andric 
263d8e91e46SDimitry Andric /// Map of stack slot offsets for spilled locations.
264d8e91e46SDimitry Andric /// Non-spilled locations are not added to the map.
265d8e91e46SDimitry Andric using SpillOffsetMap = DenseMap<unsigned, unsigned>;
266d8e91e46SDimitry Andric 
267344a3780SDimitry Andric /// Cache to save the location where it can be used as the starting
268344a3780SDimitry Andric /// position as input for calling MachineBasicBlock::SkipPHIsLabelsAndDebug.
269344a3780SDimitry Andric /// This is to prevent MachineBasicBlock::SkipPHIsLabelsAndDebug from
270344a3780SDimitry Andric /// repeatedly searching the same set of PHIs/Labels/Debug instructions
271344a3780SDimitry Andric /// if it is called many times for the same block.
272344a3780SDimitry Andric using BlockSkipInstsMap =
273344a3780SDimitry Andric     DenseMap<MachineBasicBlock *, MachineBasicBlock::iterator>;
274344a3780SDimitry Andric 
275044eb2f6SDimitry Andric namespace {
276044eb2f6SDimitry Andric 
277044eb2f6SDimitry Andric class LDVImpl;
278cf099d11SDimitry Andric 
279d8e91e46SDimitry Andric /// A user value is a part of a debug info user variable.
280cf099d11SDimitry Andric ///
281cf099d11SDimitry Andric /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
282cf099d11SDimitry Andric /// holds part of a user variable. The part is identified by a byte offset.
283706b4fc4SDimitry Andric ///
284706b4fc4SDimitry Andric /// UserValues are grouped into equivalence classes for easier searching. Two
285cfca06d7SDimitry Andric /// user values are related if they are held by the same virtual register. The
286cfca06d7SDimitry Andric /// equivalence class is the transitive closure of that relation.
287cf099d11SDimitry Andric class UserValue {
288044eb2f6SDimitry Andric   const DILocalVariable *Variable; ///< The debug info variable we are part of.
289cfca06d7SDimitry Andric   /// The part of the variable we describe.
290e3b55780SDimitry Andric   const std::optional<DIExpression::FragmentInfo> Fragment;
291cf099d11SDimitry Andric   DebugLoc dl;            ///< The debug location for the variable. This is
292cf099d11SDimitry Andric                           ///< used by dwarf writer to find lexical scope.
293706b4fc4SDimitry Andric   UserValue *leader;      ///< Equivalence class leader.
294706b4fc4SDimitry Andric   UserValue *next = nullptr; ///< Next value in equivalence class, or null.
295cf099d11SDimitry Andric 
296cf099d11SDimitry Andric   /// Numbered locations referenced by locmap.
297cf099d11SDimitry Andric   SmallVector<MachineOperand, 4> locations;
298cf099d11SDimitry Andric 
299cf099d11SDimitry Andric   /// Map of slot indices where this value is live.
300cf099d11SDimitry Andric   LocMap locInts;
301cf099d11SDimitry Andric 
302cfca06d7SDimitry Andric   /// Set of interval start indexes that have been trimmed to the
303cfca06d7SDimitry Andric   /// lexical scope.
304cfca06d7SDimitry Andric   SmallSet<SlotIndex, 2> trimmedDefs;
305cfca06d7SDimitry Andric 
306cfca06d7SDimitry Andric   /// Insert a DBG_VALUE into MBB at Idx for DbgValue.
307044eb2f6SDimitry Andric   void insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
308cfca06d7SDimitry Andric                         SlotIndex StopIdx, DbgVariableValue DbgValue,
309344a3780SDimitry Andric                         ArrayRef<bool> LocSpills,
310344a3780SDimitry Andric                         ArrayRef<unsigned> SpillOffsets, LiveIntervals &LIS,
311044eb2f6SDimitry Andric                         const TargetInstrInfo &TII,
312344a3780SDimitry Andric                         const TargetRegisterInfo &TRI,
313344a3780SDimitry Andric                         BlockSkipInstsMap &BBSkipInstsMap);
314cf099d11SDimitry Andric 
315d8e91e46SDimitry Andric   /// Replace OldLocNo ranges with NewRegs ranges where NewRegs
31656fe8f14SDimitry Andric   /// is live. Returns true if any changes were made.
317cfca06d7SDimitry Andric   bool splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs,
318f8af5cf6SDimitry Andric                      LiveIntervals &LIS);
31956fe8f14SDimitry Andric 
320cf099d11SDimitry Andric public:
321d8e91e46SDimitry Andric   /// Create a new UserValue.
UserValue(const DILocalVariable * var,std::optional<DIExpression::FragmentInfo> Fragment,DebugLoc L,LocMap::Allocator & alloc)322cfca06d7SDimitry Andric   UserValue(const DILocalVariable *var,
323e3b55780SDimitry Andric             std::optional<DIExpression::FragmentInfo> Fragment, DebugLoc L,
324044eb2f6SDimitry Andric             LocMap::Allocator &alloc)
325cfca06d7SDimitry Andric       : Variable(var), Fragment(Fragment), dl(std::move(L)), leader(this),
326706b4fc4SDimitry Andric         locInts(alloc) {}
327cf099d11SDimitry Andric 
328706b4fc4SDimitry Andric   /// Get the leader of this value's equivalence class.
getLeader()329706b4fc4SDimitry Andric   UserValue *getLeader() {
330706b4fc4SDimitry Andric     UserValue *l = leader;
331706b4fc4SDimitry Andric     while (l != l->leader)
332706b4fc4SDimitry Andric       l = l->leader;
333706b4fc4SDimitry Andric     return leader = l;
334706b4fc4SDimitry Andric   }
335706b4fc4SDimitry Andric 
336706b4fc4SDimitry Andric   /// Return the next UserValue in the equivalence class.
getNext() const337706b4fc4SDimitry Andric   UserValue *getNext() const { return next; }
338706b4fc4SDimitry Andric 
339706b4fc4SDimitry Andric   /// Merge equivalence classes.
merge(UserValue * L1,UserValue * L2)340706b4fc4SDimitry Andric   static UserValue *merge(UserValue *L1, UserValue *L2) {
341706b4fc4SDimitry Andric     L2 = L2->getLeader();
342706b4fc4SDimitry Andric     if (!L1)
343706b4fc4SDimitry Andric       return L2;
344706b4fc4SDimitry Andric     L1 = L1->getLeader();
345706b4fc4SDimitry Andric     if (L1 == L2)
346706b4fc4SDimitry Andric       return L1;
347706b4fc4SDimitry Andric     // Splice L2 before L1's members.
348706b4fc4SDimitry Andric     UserValue *End = L2;
349706b4fc4SDimitry Andric     while (End->next) {
350706b4fc4SDimitry Andric       End->leader = L1;
351706b4fc4SDimitry Andric       End = End->next;
352706b4fc4SDimitry Andric     }
353706b4fc4SDimitry Andric     End->leader = L1;
354706b4fc4SDimitry Andric     End->next = L1->next;
355706b4fc4SDimitry Andric     L1->next = L2;
356706b4fc4SDimitry Andric     return L1;
357cf099d11SDimitry Andric   }
358cf099d11SDimitry Andric 
359eb11fae6SDimitry Andric   /// Return the location number that matches Loc.
360eb11fae6SDimitry Andric   ///
361eb11fae6SDimitry Andric   /// For undef values we always return location number UndefLocNo without
362eb11fae6SDimitry Andric   /// inserting anything in locations. Since locations is a vector and the
363eb11fae6SDimitry Andric   /// location number is the position in the vector and UndefLocNo is ~0,
364eb11fae6SDimitry Andric   /// we would need a very big vector to put the value at the right position.
getLocationNo(const MachineOperand & LocMO)365cf099d11SDimitry Andric   unsigned getLocationNo(const MachineOperand &LocMO) {
3666b943ff3SDimitry Andric     if (LocMO.isReg()) {
3676b943ff3SDimitry Andric       if (LocMO.getReg() == 0)
368044eb2f6SDimitry Andric         return UndefLocNo;
3696b943ff3SDimitry Andric       // For register locations we dont care about use/def and other flags.
3706b943ff3SDimitry Andric       for (unsigned i = 0, e = locations.size(); i != e; ++i)
3716b943ff3SDimitry Andric         if (locations[i].isReg() &&
3726b943ff3SDimitry Andric             locations[i].getReg() == LocMO.getReg() &&
3736b943ff3SDimitry Andric             locations[i].getSubReg() == LocMO.getSubReg())
3746b943ff3SDimitry Andric           return i;
3756b943ff3SDimitry Andric     } else
376cf099d11SDimitry Andric       for (unsigned i = 0, e = locations.size(); i != e; ++i)
377cf099d11SDimitry Andric         if (LocMO.isIdenticalTo(locations[i]))
378cf099d11SDimitry Andric           return i;
379cf099d11SDimitry Andric     locations.push_back(LocMO);
380cf099d11SDimitry Andric     // We are storing a MachineOperand outside a MachineInstr.
381cf099d11SDimitry Andric     locations.back().clearParent();
3826b943ff3SDimitry Andric     // Don't store def operands.
383eb11fae6SDimitry Andric     if (locations.back().isReg()) {
384eb11fae6SDimitry Andric       if (locations.back().isDef())
385eb11fae6SDimitry Andric         locations.back().setIsDead(false);
3866b943ff3SDimitry Andric       locations.back().setIsUse();
387eb11fae6SDimitry Andric     }
388cf099d11SDimitry Andric     return locations.size() - 1;
389cf099d11SDimitry Andric   }
390cf099d11SDimitry Andric 
391706b4fc4SDimitry Andric   /// Remove (recycle) a location number. If \p LocNo still is used by the
392706b4fc4SDimitry Andric   /// locInts nothing is done.
removeLocationIfUnused(unsigned LocNo)393706b4fc4SDimitry Andric   void removeLocationIfUnused(unsigned LocNo) {
394706b4fc4SDimitry Andric     // Bail out if LocNo still is used.
395706b4fc4SDimitry Andric     for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
396344a3780SDimitry Andric       const DbgVariableValue &DbgValue = I.value();
397344a3780SDimitry Andric       if (DbgValue.containsLocNo(LocNo))
398706b4fc4SDimitry Andric         return;
399706b4fc4SDimitry Andric     }
400706b4fc4SDimitry Andric     // Remove the entry in the locations vector, and adjust all references to
401706b4fc4SDimitry Andric     // location numbers above the removed entry.
402706b4fc4SDimitry Andric     locations.erase(locations.begin() + LocNo);
403706b4fc4SDimitry Andric     for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
404344a3780SDimitry Andric       const DbgVariableValue &DbgValue = I.value();
405344a3780SDimitry Andric       if (DbgValue.hasLocNoGreaterThan(LocNo))
406344a3780SDimitry Andric         I.setValueUnchecked(DbgValue.decrementLocNosAfterPivot(LocNo));
407706b4fc4SDimitry Andric     }
408706b4fc4SDimitry Andric   }
409706b4fc4SDimitry Andric 
410d8e91e46SDimitry Andric   /// Ensure that all virtual register locations are mapped.
4116b943ff3SDimitry Andric   void mapVirtRegs(LDVImpl *LDV);
4126b943ff3SDimitry Andric 
413cfca06d7SDimitry Andric   /// Add a definition point to this user value.
addDef(SlotIndex Idx,ArrayRef<MachineOperand> LocMOs,bool IsIndirect,bool IsList,const DIExpression & Expr)414344a3780SDimitry Andric   void addDef(SlotIndex Idx, ArrayRef<MachineOperand> LocMOs, bool IsIndirect,
415344a3780SDimitry Andric               bool IsList, const DIExpression &Expr) {
416344a3780SDimitry Andric     SmallVector<unsigned> Locs;
417c0981da4SDimitry Andric     for (const MachineOperand &Op : LocMOs)
418344a3780SDimitry Andric       Locs.push_back(getLocationNo(Op));
419344a3780SDimitry Andric     DbgVariableValue DbgValue(Locs, IsIndirect, IsList, Expr);
420cfca06d7SDimitry Andric     // Add a singular (Idx,Idx) -> value mapping.
421cf099d11SDimitry Andric     LocMap::iterator I = locInts.find(Idx);
422cf099d11SDimitry Andric     if (!I.valid() || I.start() != Idx)
423344a3780SDimitry Andric       I.insert(Idx, Idx.getNextSlot(), std::move(DbgValue));
42430815c53SDimitry Andric     else
42530815c53SDimitry Andric       // A later DBG_VALUE at the same SlotIndex overrides the old location.
426344a3780SDimitry Andric       I.setValue(std::move(DbgValue));
427cf099d11SDimitry Andric   }
428cf099d11SDimitry Andric 
429d8e91e46SDimitry Andric   /// Extend the current definition as far as possible down.
430d8e91e46SDimitry Andric   ///
431b915e9e0SDimitry Andric   /// Stop when meeting an existing def or when leaving the live
432d8e91e46SDimitry Andric   /// range of VNI. End points where VNI is no longer live are added to Kills.
433d8e91e46SDimitry Andric   ///
434d8e91e46SDimitry Andric   /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
435d8e91e46SDimitry Andric   /// data-flow analysis to propagate them beyond basic block boundaries.
436d8e91e46SDimitry Andric   ///
437d8e91e46SDimitry Andric   /// \param Idx Starting point for the definition.
438cfca06d7SDimitry Andric   /// \param DbgValue value to propagate.
439344a3780SDimitry Andric   /// \param LiveIntervalInfo For each location number key in this map,
440344a3780SDimitry Andric   /// restricts liveness to where the LiveRange has the value equal to the\
441344a3780SDimitry Andric   /// VNInfo.
442d8e91e46SDimitry Andric   /// \param [out] Kills Append end points of VNI's live range to Kills.
443d8e91e46SDimitry Andric   /// \param LIS Live intervals analysis.
444e3b55780SDimitry Andric   void
445e3b55780SDimitry Andric   extendDef(SlotIndex Idx, DbgVariableValue DbgValue,
446344a3780SDimitry Andric             SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>>
447344a3780SDimitry Andric                 &LiveIntervalInfo,
448e3b55780SDimitry Andric             std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills,
449b915e9e0SDimitry Andric             LiveIntervals &LIS);
450cf099d11SDimitry Andric 
451cfca06d7SDimitry Andric   /// The value in LI may be copies to other registers. Determine if
452d8e91e46SDimitry Andric   /// any of the copies are available at the kill points, and add defs if
453d8e91e46SDimitry Andric   /// possible.
454d8e91e46SDimitry Andric   ///
455cfca06d7SDimitry Andric   /// \param DbgValue Location number of LI->reg, and DIExpression.
456344a3780SDimitry Andric   /// \param LocIntervals Scan for copies of the value for each location in the
457344a3780SDimitry Andric   /// corresponding LiveInterval->reg.
458344a3780SDimitry Andric   /// \param KilledAt The point where the range of DbgValue could be extended.
459cfca06d7SDimitry Andric   /// \param [in,out] NewDefs Append (Idx, DbgValue) of inserted defs here.
460044eb2f6SDimitry Andric   void addDefsFromCopies(
461344a3780SDimitry Andric       DbgVariableValue DbgValue,
462344a3780SDimitry Andric       SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals,
463344a3780SDimitry Andric       SlotIndex KilledAt,
464cfca06d7SDimitry Andric       SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
465044eb2f6SDimitry Andric       MachineRegisterInfo &MRI, LiveIntervals &LIS);
4666b943ff3SDimitry Andric 
467d8e91e46SDimitry Andric   /// Compute the live intervals of all locations after collecting all their
468d8e91e46SDimitry Andric   /// def points.
46958b69754SDimitry Andric   void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
470044eb2f6SDimitry Andric                         LiveIntervals &LIS, LexicalScopes &LS);
471cf099d11SDimitry Andric 
472d8e91e46SDimitry Andric   /// Replace OldReg ranges with NewRegs ranges where NewRegs is
47356fe8f14SDimitry Andric   /// live. Returns true if any changes were made.
474cfca06d7SDimitry Andric   bool splitRegister(Register OldReg, ArrayRef<Register> NewRegs,
475f8af5cf6SDimitry Andric                      LiveIntervals &LIS);
47656fe8f14SDimitry Andric 
477d8e91e46SDimitry Andric   /// Rewrite virtual register locations according to the provided virtual
478d8e91e46SDimitry Andric   /// register map. Record the stack slot offsets for the locations that
479d8e91e46SDimitry Andric   /// were spilled.
480d8e91e46SDimitry Andric   void rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
481d8e91e46SDimitry Andric                         const TargetInstrInfo &TII,
482d8e91e46SDimitry Andric                         const TargetRegisterInfo &TRI,
483d8e91e46SDimitry Andric                         SpillOffsetMap &SpillOffsets);
484cf099d11SDimitry Andric 
485d8e91e46SDimitry Andric   /// Recreate DBG_VALUE instruction from data structures.
486044eb2f6SDimitry Andric   void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
487044eb2f6SDimitry Andric                        const TargetInstrInfo &TII,
488044eb2f6SDimitry Andric                        const TargetRegisterInfo &TRI,
489344a3780SDimitry Andric                        const SpillOffsetMap &SpillOffsets,
490344a3780SDimitry Andric                        BlockSkipInstsMap &BBSkipInstsMap);
491cf099d11SDimitry Andric 
492d8e91e46SDimitry Andric   /// Return DebugLoc of this UserValue.
getDebugLoc()493344a3780SDimitry Andric   const DebugLoc &getDebugLoc() { return dl; }
494044eb2f6SDimitry Andric 
4955a5ac124SDimitry Andric   void print(raw_ostream &, const TargetRegisterInfo *);
496cf099d11SDimitry Andric };
497cf099d11SDimitry Andric 
498e6d15924SDimitry Andric /// A user label is a part of a debug info user label.
499e6d15924SDimitry Andric class UserLabel {
500e6d15924SDimitry Andric   const DILabel *Label; ///< The debug info label we are part of.
501e6d15924SDimitry Andric   DebugLoc dl;          ///< The debug location for the label. This is
502e6d15924SDimitry Andric                         ///< used by dwarf writer to find lexical scope.
503e6d15924SDimitry Andric   SlotIndex loc;        ///< Slot used by the debug label.
504e6d15924SDimitry Andric 
505e6d15924SDimitry Andric   /// Insert a DBG_LABEL into MBB at Idx.
506e6d15924SDimitry Andric   void insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
507344a3780SDimitry Andric                         LiveIntervals &LIS, const TargetInstrInfo &TII,
508344a3780SDimitry Andric                         BlockSkipInstsMap &BBSkipInstsMap);
509e6d15924SDimitry Andric 
510e6d15924SDimitry Andric public:
511e6d15924SDimitry Andric   /// Create a new UserLabel.
UserLabel(const DILabel * label,DebugLoc L,SlotIndex Idx)512e6d15924SDimitry Andric   UserLabel(const DILabel *label, DebugLoc L, SlotIndex Idx)
513e6d15924SDimitry Andric       : Label(label), dl(std::move(L)), loc(Idx) {}
514e6d15924SDimitry Andric 
515e6d15924SDimitry Andric   /// Does this UserLabel match the parameters?
matches(const DILabel * L,const DILocation * IA,const SlotIndex Index) const516cfca06d7SDimitry Andric   bool matches(const DILabel *L, const DILocation *IA,
517e6d15924SDimitry Andric              const SlotIndex Index) const {
518e6d15924SDimitry Andric     return Label == L && dl->getInlinedAt() == IA && loc == Index;
519e6d15924SDimitry Andric   }
520e6d15924SDimitry Andric 
521e6d15924SDimitry Andric   /// Recreate DBG_LABEL instruction from data structures.
522344a3780SDimitry Andric   void emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
523344a3780SDimitry Andric                       BlockSkipInstsMap &BBSkipInstsMap);
524e6d15924SDimitry Andric 
525e6d15924SDimitry Andric   /// Return DebugLoc of this UserLabel.
getDebugLoc()526344a3780SDimitry Andric   const DebugLoc &getDebugLoc() { return dl; }
527e6d15924SDimitry Andric 
528e6d15924SDimitry Andric   void print(raw_ostream &, const TargetRegisterInfo *);
529e6d15924SDimitry Andric };
530e6d15924SDimitry Andric 
531d8e91e46SDimitry Andric /// Implementation of the LiveDebugVariables pass.
532cf099d11SDimitry Andric class LDVImpl {
533cf099d11SDimitry Andric   LiveDebugVariables &pass;
534cf099d11SDimitry Andric   LocMap::Allocator allocator;
535044eb2f6SDimitry Andric   MachineFunction *MF = nullptr;
536cf099d11SDimitry Andric   LiveIntervals *LIS;
537cf099d11SDimitry Andric   const TargetRegisterInfo *TRI;
538cf099d11SDimitry Andric 
539344a3780SDimitry Andric   /// Position and VReg of a PHI instruction during register allocation.
540344a3780SDimitry Andric   struct PHIValPos {
541344a3780SDimitry Andric     SlotIndex SI;    /// Slot where this PHI occurs.
542344a3780SDimitry Andric     Register Reg;    /// VReg this PHI occurs in.
543344a3780SDimitry Andric     unsigned SubReg; /// Qualifiying subregister for Reg.
544344a3780SDimitry Andric   };
545344a3780SDimitry Andric 
546344a3780SDimitry Andric   /// Map from debug instruction number to PHI position during allocation.
547344a3780SDimitry Andric   std::map<unsigned, PHIValPos> PHIValToPos;
548344a3780SDimitry Andric   /// Index of, for each VReg, which debug instruction numbers and corresponding
549344a3780SDimitry Andric   /// PHIs are sensitive to splitting. Each VReg may have multiple PHI defs,
550344a3780SDimitry Andric   /// at different positions.
551344a3780SDimitry Andric   DenseMap<Register, std::vector<unsigned>> RegToPHIIdx;
552344a3780SDimitry Andric 
553344a3780SDimitry Andric   /// Record for any debug instructions unlinked from their blocks during
554344a3780SDimitry Andric   /// regalloc. Stores the instr and it's location, so that they can be
555344a3780SDimitry Andric   /// re-inserted after regalloc is over.
556344a3780SDimitry Andric   struct InstrPos {
557344a3780SDimitry Andric     MachineInstr *MI;       ///< Debug instruction, unlinked from it's block.
558344a3780SDimitry Andric     SlotIndex Idx;          ///< Slot position where MI should be re-inserted.
559344a3780SDimitry Andric     MachineBasicBlock *MBB; ///< Block that MI was in.
560344a3780SDimitry Andric   };
561344a3780SDimitry Andric 
562344a3780SDimitry Andric   /// Collection of stored debug instructions, preserved until after regalloc.
563344a3780SDimitry Andric   SmallVector<InstrPos, 32> StashedDebugInstrs;
564b60736ecSDimitry Andric 
5654a16efa3SDimitry Andric   /// Whether emitDebugValues is called.
566044eb2f6SDimitry Andric   bool EmitDone = false;
567044eb2f6SDimitry Andric 
5684a16efa3SDimitry Andric   /// Whether the machine function is modified during the pass.
569044eb2f6SDimitry Andric   bool ModifiedMF = false;
5704a16efa3SDimitry Andric 
571d8e91e46SDimitry Andric   /// All allocated UserValue instances.
5725ca98fd9SDimitry Andric   SmallVector<std::unique_ptr<UserValue>, 8> userValues;
573cf099d11SDimitry Andric 
574e6d15924SDimitry Andric   /// All allocated UserLabel instances.
575e6d15924SDimitry Andric   SmallVector<std::unique_ptr<UserLabel>, 2> userLabels;
576e6d15924SDimitry Andric 
577706b4fc4SDimitry Andric   /// Map virtual register to eq class leader.
578706b4fc4SDimitry Andric   using VRMap = DenseMap<unsigned, UserValue *>;
579706b4fc4SDimitry Andric   VRMap virtRegToEqClass;
580cf099d11SDimitry Andric 
581cfca06d7SDimitry Andric   /// Map to find existing UserValue instances.
582cfca06d7SDimitry Andric   using UVMap = DenseMap<DebugVariable, UserValue *>;
583706b4fc4SDimitry Andric   UVMap userVarMap;
584cf099d11SDimitry Andric 
585d8e91e46SDimitry Andric   /// Find or create a UserValue.
586cfca06d7SDimitry Andric   UserValue *getUserValue(const DILocalVariable *Var,
587e3b55780SDimitry Andric                           std::optional<DIExpression::FragmentInfo> Fragment,
588044eb2f6SDimitry Andric                           const DebugLoc &DL);
589cf099d11SDimitry Andric 
590706b4fc4SDimitry Andric   /// Find the EC leader for VirtReg or null.
591cfca06d7SDimitry Andric   UserValue *lookupVirtReg(Register VirtReg);
592cf099d11SDimitry Andric 
593d8e91e46SDimitry Andric   /// Add DBG_VALUE instruction to our maps.
594d8e91e46SDimitry Andric   ///
595d8e91e46SDimitry Andric   /// \param MI DBG_VALUE instruction
596d8e91e46SDimitry Andric   /// \param Idx Last valid SLotIndex before instruction.
597d8e91e46SDimitry Andric   ///
598d8e91e46SDimitry Andric   /// \returns True if the DBG_VALUE instruction should be deleted.
59901095a5dSDimitry Andric   bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
600cf099d11SDimitry Andric 
601344a3780SDimitry Andric   /// Track variable location debug instructions while using the instruction
602344a3780SDimitry Andric   /// referencing implementation. Such debug instructions do not need to be
603344a3780SDimitry Andric   /// updated during regalloc because they identify instructions rather than
604344a3780SDimitry Andric   /// register locations. However, they needs to be removed from the
605344a3780SDimitry Andric   /// MachineFunction during regalloc, then re-inserted later, to avoid
606344a3780SDimitry Andric   /// disrupting the allocator.
607b60736ecSDimitry Andric   ///
608344a3780SDimitry Andric   /// \param MI Any DBG_VALUE / DBG_INSTR_REF / DBG_PHI instruction
609b60736ecSDimitry Andric   /// \param Idx Last valid SlotIndex before instruction
610b60736ecSDimitry Andric   ///
611344a3780SDimitry Andric   /// \returns Iterator to continue processing from after unlinking.
612344a3780SDimitry Andric   MachineBasicBlock::iterator handleDebugInstr(MachineInstr &MI, SlotIndex Idx);
613b60736ecSDimitry Andric 
614e6d15924SDimitry Andric   /// Add DBG_LABEL instruction to UserLabel.
615e6d15924SDimitry Andric   ///
616e6d15924SDimitry Andric   /// \param MI DBG_LABEL instruction
617e6d15924SDimitry Andric   /// \param Idx Last valid SlotIndex before instruction.
618e6d15924SDimitry Andric   ///
619e6d15924SDimitry Andric   /// \returns True if the DBG_LABEL instruction should be deleted.
620e6d15924SDimitry Andric   bool handleDebugLabel(MachineInstr &MI, SlotIndex Idx);
621e6d15924SDimitry Andric 
622d8e91e46SDimitry Andric   /// Collect and erase all DBG_VALUE instructions, adding a UserValue def
623d8e91e46SDimitry Andric   /// for each instruction.
624d8e91e46SDimitry Andric   ///
625d8e91e46SDimitry Andric   /// \param mf MachineFunction to be scanned.
626344a3780SDimitry Andric   /// \param InstrRef Whether to operate in instruction referencing mode. If
627344a3780SDimitry Andric   ///        true, most of LiveDebugVariables doesn't run.
628d8e91e46SDimitry Andric   ///
629d8e91e46SDimitry Andric   /// \returns True if any debug values were found.
630344a3780SDimitry Andric   bool collectDebugValues(MachineFunction &mf, bool InstrRef);
631cf099d11SDimitry Andric 
632d8e91e46SDimitry Andric   /// Compute the live intervals of all user values after collecting all
633d8e91e46SDimitry Andric   /// their def points.
634cf099d11SDimitry Andric   void computeIntervals();
635cf099d11SDimitry Andric 
636cf099d11SDimitry Andric public:
LDVImpl(LiveDebugVariables * ps)637044eb2f6SDimitry Andric   LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
638044eb2f6SDimitry Andric 
639344a3780SDimitry Andric   bool runOnMachineFunction(MachineFunction &mf, bool InstrRef);
640cf099d11SDimitry Andric 
641d8e91e46SDimitry Andric   /// Release all memory.
clear()642cf099d11SDimitry Andric   void clear() {
64367c32a98SDimitry Andric     MF = nullptr;
644344a3780SDimitry Andric     PHIValToPos.clear();
645344a3780SDimitry Andric     RegToPHIIdx.clear();
646344a3780SDimitry Andric     StashedDebugInstrs.clear();
647cf099d11SDimitry Andric     userValues.clear();
648e6d15924SDimitry Andric     userLabels.clear();
649706b4fc4SDimitry Andric     virtRegToEqClass.clear();
650706b4fc4SDimitry Andric     userVarMap.clear();
6514a16efa3SDimitry Andric     // Make sure we call emitDebugValues if the machine function was modified.
6524a16efa3SDimitry Andric     assert((!ModifiedMF || EmitDone) &&
6534a16efa3SDimitry Andric            "Dbg values are not emitted in LDV");
6544a16efa3SDimitry Andric     EmitDone = false;
6554a16efa3SDimitry Andric     ModifiedMF = false;
656cf099d11SDimitry Andric   }
657cf099d11SDimitry Andric 
658706b4fc4SDimitry Andric   /// Map virtual register to an equivalence class.
659cfca06d7SDimitry Andric   void mapVirtReg(Register VirtReg, UserValue *EC);
6606b943ff3SDimitry Andric 
661344a3780SDimitry Andric   /// Replace any PHI referring to OldReg with its corresponding NewReg, if
662344a3780SDimitry Andric   /// present.
663344a3780SDimitry Andric   void splitPHIRegister(Register OldReg, ArrayRef<Register> NewRegs);
664344a3780SDimitry Andric 
665d8e91e46SDimitry Andric   /// Replace all references to OldReg with NewRegs.
666cfca06d7SDimitry Andric   void splitRegister(Register OldReg, ArrayRef<Register> NewRegs);
66756fe8f14SDimitry Andric 
668d8e91e46SDimitry Andric   /// Recreate DBG_VALUE instruction from data structures.
669cf099d11SDimitry Andric   void emitDebugValues(VirtRegMap *VRM);
670cf099d11SDimitry Andric 
671cf099d11SDimitry Andric   void print(raw_ostream&);
672cf099d11SDimitry Andric };
673cf099d11SDimitry Andric 
674044eb2f6SDimitry Andric } // end anonymous namespace
675044eb2f6SDimitry Andric 
676044eb2f6SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
printDebugLoc(const DebugLoc & DL,raw_ostream & CommentOS,const LLVMContext & Ctx)67701095a5dSDimitry Andric static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
6785a5ac124SDimitry Andric                           const LLVMContext &Ctx) {
6795a5ac124SDimitry Andric   if (!DL)
6805a5ac124SDimitry Andric     return;
6815a5ac124SDimitry Andric 
6825a5ac124SDimitry Andric   auto *Scope = cast<DIScope>(DL.getScope());
6835a5ac124SDimitry Andric   // Omit the directory, because it's likely to be long and uninteresting.
6845a5ac124SDimitry Andric   CommentOS << Scope->getFilename();
6855a5ac124SDimitry Andric   CommentOS << ':' << DL.getLine();
6865a5ac124SDimitry Andric   if (DL.getCol() != 0)
6875a5ac124SDimitry Andric     CommentOS << ':' << DL.getCol();
6885a5ac124SDimitry Andric 
6895a5ac124SDimitry Andric   DebugLoc InlinedAtDL = DL.getInlinedAt();
6905a5ac124SDimitry Andric   if (!InlinedAtDL)
6915a5ac124SDimitry Andric     return;
6925a5ac124SDimitry Andric 
6935a5ac124SDimitry Andric   CommentOS << " @[ ";
6945a5ac124SDimitry Andric   printDebugLoc(InlinedAtDL, CommentOS, Ctx);
6955a5ac124SDimitry Andric   CommentOS << " ]";
6965a5ac124SDimitry Andric }
6975a5ac124SDimitry Andric 
printExtendedName(raw_ostream & OS,const DINode * Node,const DILocation * DL)698e6d15924SDimitry Andric static void printExtendedName(raw_ostream &OS, const DINode *Node,
6995a5ac124SDimitry Andric                               const DILocation *DL) {
700e6d15924SDimitry Andric   const LLVMContext &Ctx = Node->getContext();
701e6d15924SDimitry Andric   StringRef Res;
702706b4fc4SDimitry Andric   unsigned Line = 0;
703e6d15924SDimitry Andric   if (const auto *V = dyn_cast<const DILocalVariable>(Node)) {
704e6d15924SDimitry Andric     Res = V->getName();
705e6d15924SDimitry Andric     Line = V->getLine();
706e6d15924SDimitry Andric   } else if (const auto *L = dyn_cast<const DILabel>(Node)) {
707e6d15924SDimitry Andric     Res = L->getName();
708e6d15924SDimitry Andric     Line = L->getLine();
709e6d15924SDimitry Andric   }
710e6d15924SDimitry Andric 
7115a5ac124SDimitry Andric   if (!Res.empty())
712e6d15924SDimitry Andric     OS << Res << "," << Line;
713e6d15924SDimitry Andric   auto *InlinedAt = DL ? DL->getInlinedAt() : nullptr;
714e6d15924SDimitry Andric   if (InlinedAt) {
7155a5ac124SDimitry Andric     if (DebugLoc InlinedAtDL = InlinedAt) {
7165a5ac124SDimitry Andric       OS << " @[";
7175a5ac124SDimitry Andric       printDebugLoc(InlinedAtDL, OS, Ctx);
7185a5ac124SDimitry Andric       OS << "]";
7195a5ac124SDimitry Andric     }
7205a5ac124SDimitry Andric   }
7215a5ac124SDimitry Andric }
7225a5ac124SDimitry Andric 
print(raw_ostream & OS,const TargetRegisterInfo * TRI)7235a5ac124SDimitry Andric void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
72430815c53SDimitry Andric   OS << "!\"";
725e6d15924SDimitry Andric   printExtendedName(OS, Variable, dl);
7265a5ac124SDimitry Andric 
72730815c53SDimitry Andric   OS << "\"\t";
728cf099d11SDimitry Andric   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
729cf099d11SDimitry Andric     OS << " [" << I.start() << ';' << I.stop() << "):";
730044eb2f6SDimitry Andric     if (I.value().isUndef())
731cf099d11SDimitry Andric       OS << " undef";
732044eb2f6SDimitry Andric     else {
733344a3780SDimitry Andric       I.value().printLocNos(OS);
734cfca06d7SDimitry Andric       if (I.value().getWasIndirect())
735cfca06d7SDimitry Andric         OS << " ind";
736344a3780SDimitry Andric       else if (I.value().getWasList())
737344a3780SDimitry Andric         OS << " list";
738044eb2f6SDimitry Andric     }
739cf099d11SDimitry Andric   }
74056fe8f14SDimitry Andric   for (unsigned i = 0, e = locations.size(); i != e; ++i) {
74156fe8f14SDimitry Andric     OS << " Loc" << i << '=';
7425a5ac124SDimitry Andric     locations[i].print(OS, TRI);
74356fe8f14SDimitry Andric   }
744cf099d11SDimitry Andric   OS << '\n';
745cf099d11SDimitry Andric }
746cf099d11SDimitry Andric 
print(raw_ostream & OS,const TargetRegisterInfo * TRI)747e6d15924SDimitry Andric void UserLabel::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
748e6d15924SDimitry Andric   OS << "!\"";
749e6d15924SDimitry Andric   printExtendedName(OS, Label, dl);
750e6d15924SDimitry Andric 
751e6d15924SDimitry Andric   OS << "\"\t";
752e6d15924SDimitry Andric   OS << loc;
753e6d15924SDimitry Andric   OS << '\n';
754e6d15924SDimitry Andric }
755e6d15924SDimitry Andric 
print(raw_ostream & OS)756cf099d11SDimitry Andric void LDVImpl::print(raw_ostream &OS) {
757cf099d11SDimitry Andric   OS << "********** DEBUG VARIABLES **********\n";
758e6d15924SDimitry Andric   for (auto &userValue : userValues)
759e6d15924SDimitry Andric     userValue->print(OS, TRI);
760e6d15924SDimitry Andric   OS << "********** DEBUG LABELS **********\n";
761e6d15924SDimitry Andric   for (auto &userLabel : userLabels)
762e6d15924SDimitry Andric     userLabel->print(OS, TRI);
763cf099d11SDimitry Andric }
764044eb2f6SDimitry Andric #endif
765cf099d11SDimitry Andric 
mapVirtRegs(LDVImpl * LDV)7666b943ff3SDimitry Andric void UserValue::mapVirtRegs(LDVImpl *LDV) {
767ac9a064cSDimitry Andric   for (const MachineOperand &MO : locations)
768ac9a064cSDimitry Andric     if (MO.isReg() && MO.getReg().isVirtual())
769ac9a064cSDimitry Andric       LDV->mapVirtReg(MO.getReg(), this);
7706b943ff3SDimitry Andric }
7716b943ff3SDimitry Andric 
772e3b55780SDimitry Andric UserValue *
getUserValue(const DILocalVariable * Var,std::optional<DIExpression::FragmentInfo> Fragment,const DebugLoc & DL)773e3b55780SDimitry Andric LDVImpl::getUserValue(const DILocalVariable *Var,
774e3b55780SDimitry Andric                       std::optional<DIExpression::FragmentInfo> Fragment,
775cfca06d7SDimitry Andric                       const DebugLoc &DL) {
776cfca06d7SDimitry Andric   // FIXME: Handle partially overlapping fragments. See
777cfca06d7SDimitry Andric   // https://reviews.llvm.org/D70121#1849741.
778cfca06d7SDimitry Andric   DebugVariable ID(Var, Fragment, DL->getInlinedAt());
779cfca06d7SDimitry Andric   UserValue *&UV = userVarMap[ID];
780cfca06d7SDimitry Andric   if (!UV) {
781706b4fc4SDimitry Andric     userValues.push_back(
782cfca06d7SDimitry Andric         std::make_unique<UserValue>(Var, Fragment, DL, allocator));
783cfca06d7SDimitry Andric     UV = userValues.back().get();
784cfca06d7SDimitry Andric   }
785706b4fc4SDimitry Andric   return UV;
786706b4fc4SDimitry Andric }
787706b4fc4SDimitry Andric 
mapVirtReg(Register VirtReg,UserValue * EC)788cfca06d7SDimitry Andric void LDVImpl::mapVirtReg(Register VirtReg, UserValue *EC) {
789e3b55780SDimitry Andric   assert(VirtReg.isVirtual() && "Only map VirtRegs");
790706b4fc4SDimitry Andric   UserValue *&Leader = virtRegToEqClass[VirtReg];
791706b4fc4SDimitry Andric   Leader = UserValue::merge(Leader, EC);
792cf099d11SDimitry Andric }
793cf099d11SDimitry Andric 
lookupVirtReg(Register VirtReg)794cfca06d7SDimitry Andric UserValue *LDVImpl::lookupVirtReg(Register VirtReg) {
795706b4fc4SDimitry Andric   if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
796706b4fc4SDimitry Andric     return UV->getLeader();
7975ca98fd9SDimitry Andric   return nullptr;
798cf099d11SDimitry Andric }
799cf099d11SDimitry Andric 
handleDebugValue(MachineInstr & MI,SlotIndex Idx)80001095a5dSDimitry Andric bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
801344a3780SDimitry Andric   // DBG_VALUE loc, offset, variable, expr
802344a3780SDimitry Andric   // DBG_VALUE_LIST variable, expr, locs...
803344a3780SDimitry Andric   if (!MI.isDebugValue()) {
804344a3780SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't handle non-DBG_VALUE*: " << MI);
805344a3780SDimitry Andric     return false;
806344a3780SDimitry Andric   }
807344a3780SDimitry Andric   if (!MI.getDebugVariableOp().isMetadata()) {
808344a3780SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't handle DBG_VALUE* with invalid variable: "
809344a3780SDimitry Andric                       << MI);
810344a3780SDimitry Andric     return false;
811344a3780SDimitry Andric   }
812344a3780SDimitry Andric   if (MI.isNonListDebugValue() &&
813344a3780SDimitry Andric       (MI.getNumOperands() != 4 ||
814344a3780SDimitry Andric        !(MI.getDebugOffset().isImm() || MI.getDebugOffset().isReg()))) {
815344a3780SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't handle malformed DBG_VALUE: " << MI);
816cf099d11SDimitry Andric     return false;
817cf099d11SDimitry Andric   }
818cf099d11SDimitry Andric 
819eb11fae6SDimitry Andric   // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual
820eb11fae6SDimitry Andric   // register that hasn't been defined yet. If we do not remove those here, then
821eb11fae6SDimitry Andric   // the re-insertion of the DBG_VALUE instruction after register allocation
822eb11fae6SDimitry Andric   // will be incorrect.
823eb11fae6SDimitry Andric   bool Discard = false;
824344a3780SDimitry Andric   for (const MachineOperand &Op : MI.debug_operands()) {
825e3b55780SDimitry Andric     if (Op.isReg() && Op.getReg().isVirtual()) {
826344a3780SDimitry Andric       const Register Reg = Op.getReg();
827eb11fae6SDimitry Andric       if (!LIS->hasInterval(Reg)) {
828eb11fae6SDimitry Andric         // The DBG_VALUE is described by a virtual register that does not have a
829eb11fae6SDimitry Andric         // live interval. Discard the DBG_VALUE.
830eb11fae6SDimitry Andric         Discard = true;
831eb11fae6SDimitry Andric         LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx
832eb11fae6SDimitry Andric                           << " " << MI);
833eb11fae6SDimitry Andric       } else {
834344a3780SDimitry Andric         // The DBG_VALUE is only valid if either Reg is live out from Idx, or
835344a3780SDimitry Andric         // Reg is defined dead at Idx (where Idx is the slot index for the
836344a3780SDimitry Andric         // instruction preceding the DBG_VALUE).
837eb11fae6SDimitry Andric         const LiveInterval &LI = LIS->getInterval(Reg);
838eb11fae6SDimitry Andric         LiveQueryResult LRQ = LI.Query(Idx);
839eb11fae6SDimitry Andric         if (!LRQ.valueOutOrDead()) {
840eb11fae6SDimitry Andric           // We have found a DBG_VALUE with the value in a virtual register that
841eb11fae6SDimitry Andric           // is not live. Discard the DBG_VALUE.
842eb11fae6SDimitry Andric           Discard = true;
843eb11fae6SDimitry Andric           LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx
844eb11fae6SDimitry Andric                             << " " << MI);
845eb11fae6SDimitry Andric         }
846eb11fae6SDimitry Andric       }
847eb11fae6SDimitry Andric     }
848344a3780SDimitry Andric   }
849eb11fae6SDimitry Andric 
850044eb2f6SDimitry Andric   // Get or create the UserValue for (variable,offset) here.
851cfca06d7SDimitry Andric   bool IsIndirect = MI.isDebugOffsetImm();
852cfca06d7SDimitry Andric   if (IsIndirect)
853cfca06d7SDimitry Andric     assert(MI.getDebugOffset().getImm() == 0 &&
854cfca06d7SDimitry Andric            "DBG_VALUE with nonzero offset");
855344a3780SDimitry Andric   bool IsList = MI.isDebugValueList();
856044eb2f6SDimitry Andric   const DILocalVariable *Var = MI.getDebugVariable();
857044eb2f6SDimitry Andric   const DIExpression *Expr = MI.getDebugExpression();
858cfca06d7SDimitry Andric   UserValue *UV = getUserValue(Var, Expr->getFragmentInfo(), MI.getDebugLoc());
859eb11fae6SDimitry Andric   if (!Discard)
860344a3780SDimitry Andric     UV->addDef(Idx,
861344a3780SDimitry Andric                ArrayRef<MachineOperand>(MI.debug_operands().begin(),
862344a3780SDimitry Andric                                         MI.debug_operands().end()),
863344a3780SDimitry Andric                IsIndirect, IsList, *Expr);
864eb11fae6SDimitry Andric   else {
865eb11fae6SDimitry Andric     MachineOperand MO = MachineOperand::CreateReg(0U, false);
866eb11fae6SDimitry Andric     MO.setIsDebug();
867344a3780SDimitry Andric     // We should still pass a list the same size as MI.debug_operands() even if
868344a3780SDimitry Andric     // all MOs are undef, so that DbgVariableValue can correctly adjust the
869344a3780SDimitry Andric     // expression while removing the duplicated undefs.
870344a3780SDimitry Andric     SmallVector<MachineOperand, 4> UndefMOs(MI.getNumDebugOperands(), MO);
871344a3780SDimitry Andric     UV->addDef(Idx, UndefMOs, false, IsList, *Expr);
872eb11fae6SDimitry Andric   }
873cf099d11SDimitry Andric   return true;
874cf099d11SDimitry Andric }
875cf099d11SDimitry Andric 
handleDebugInstr(MachineInstr & MI,SlotIndex Idx)876344a3780SDimitry Andric MachineBasicBlock::iterator LDVImpl::handleDebugInstr(MachineInstr &MI,
877344a3780SDimitry Andric                                                       SlotIndex Idx) {
878e3b55780SDimitry Andric   assert(MI.isDebugValueLike() || MI.isDebugPHI());
879344a3780SDimitry Andric 
880344a3780SDimitry Andric   // In instruction referencing mode, there should be no DBG_VALUE instructions
881344a3780SDimitry Andric   // that refer to virtual registers. They might still refer to constants.
882e3b55780SDimitry Andric   if (MI.isDebugValueLike())
883e3b55780SDimitry Andric     assert(none_of(MI.debug_operands(),
884e3b55780SDimitry Andric                    [](const MachineOperand &MO) {
885e3b55780SDimitry Andric                      return MO.isReg() && MO.getReg().isVirtual();
886e3b55780SDimitry Andric                    }) &&
887e3b55780SDimitry Andric            "MIs should not refer to Virtual Registers in InstrRef mode.");
888344a3780SDimitry Andric 
889344a3780SDimitry Andric   // Unlink the instruction, store it in the debug instructions collection.
890344a3780SDimitry Andric   auto NextInst = std::next(MI.getIterator());
891344a3780SDimitry Andric   auto *MBB = MI.getParent();
892344a3780SDimitry Andric   MI.removeFromParent();
893344a3780SDimitry Andric   StashedDebugInstrs.push_back({&MI, Idx, MBB});
894344a3780SDimitry Andric   return NextInst;
895b60736ecSDimitry Andric }
896b60736ecSDimitry Andric 
handleDebugLabel(MachineInstr & MI,SlotIndex Idx)897e6d15924SDimitry Andric bool LDVImpl::handleDebugLabel(MachineInstr &MI, SlotIndex Idx) {
898e6d15924SDimitry Andric   // DBG_LABEL label
899e6d15924SDimitry Andric   if (MI.getNumOperands() != 1 || !MI.getOperand(0).isMetadata()) {
900e6d15924SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't handle " << MI);
901e6d15924SDimitry Andric     return false;
902e6d15924SDimitry Andric   }
903e6d15924SDimitry Andric 
904e6d15924SDimitry Andric   // Get or create the UserLabel for label here.
905e6d15924SDimitry Andric   const DILabel *Label = MI.getDebugLabel();
906e6d15924SDimitry Andric   const DebugLoc &DL = MI.getDebugLoc();
907e6d15924SDimitry Andric   bool Found = false;
908e6d15924SDimitry Andric   for (auto const &L : userLabels) {
909cfca06d7SDimitry Andric     if (L->matches(Label, DL->getInlinedAt(), Idx)) {
910e6d15924SDimitry Andric       Found = true;
911e6d15924SDimitry Andric       break;
912e6d15924SDimitry Andric     }
913e6d15924SDimitry Andric   }
914e6d15924SDimitry Andric   if (!Found)
9151d5ae102SDimitry Andric     userLabels.push_back(std::make_unique<UserLabel>(Label, DL, Idx));
916e6d15924SDimitry Andric 
917e6d15924SDimitry Andric   return true;
918e6d15924SDimitry Andric }
919e6d15924SDimitry Andric 
collectDebugValues(MachineFunction & mf,bool InstrRef)920344a3780SDimitry Andric bool LDVImpl::collectDebugValues(MachineFunction &mf, bool InstrRef) {
921cf099d11SDimitry Andric   bool Changed = false;
922344a3780SDimitry Andric   for (MachineBasicBlock &MBB : mf) {
923344a3780SDimitry Andric     for (MachineBasicBlock::iterator MBBI = MBB.begin(), MBBE = MBB.end();
924cf099d11SDimitry Andric          MBBI != MBBE;) {
925d8e91e46SDimitry Andric       // Use the first debug instruction in the sequence to get a SlotIndex
926d8e91e46SDimitry Andric       // for following consecutive debug instructions.
927344a3780SDimitry Andric       if (!MBBI->isDebugOrPseudoInstr()) {
928cf099d11SDimitry Andric         ++MBBI;
929cf099d11SDimitry Andric         continue;
930cf099d11SDimitry Andric       }
931d8e91e46SDimitry Andric       // Debug instructions has no slot index. Use the previous
932d8e91e46SDimitry Andric       // non-debug instruction's SlotIndex as its SlotIndex.
93301095a5dSDimitry Andric       SlotIndex Idx =
934344a3780SDimitry Andric           MBBI == MBB.begin()
935344a3780SDimitry Andric               ? LIS->getMBBStartIdx(&MBB)
93601095a5dSDimitry Andric               : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
937d8e91e46SDimitry Andric       // Handle consecutive debug instructions with the same slot index.
938cf099d11SDimitry Andric       do {
939344a3780SDimitry Andric         // In instruction referencing mode, pass each instr to handleDebugInstr
940344a3780SDimitry Andric         // to be unlinked. Ignore DBG_VALUE_LISTs -- they refer to vregs, and
941344a3780SDimitry Andric         // need to go through the normal live interval splitting process.
942344a3780SDimitry Andric         if (InstrRef && (MBBI->isNonListDebugValue() || MBBI->isDebugPHI() ||
943344a3780SDimitry Andric                          MBBI->isDebugRef())) {
944344a3780SDimitry Andric           MBBI = handleDebugInstr(*MBBI, Idx);
945344a3780SDimitry Andric           Changed = true;
946344a3780SDimitry Andric         // In normal debug mode, use the dedicated DBG_VALUE / DBG_LABEL handler
947344a3780SDimitry Andric         // to track things through register allocation, and erase the instr.
948344a3780SDimitry Andric         } else if ((MBBI->isDebugValue() && handleDebugValue(*MBBI, Idx)) ||
949e6d15924SDimitry Andric                    (MBBI->isDebugLabel() && handleDebugLabel(*MBBI, Idx))) {
950344a3780SDimitry Andric           MBBI = MBB.erase(MBBI);
951cf099d11SDimitry Andric           Changed = true;
952cf099d11SDimitry Andric         } else
953cf099d11SDimitry Andric           ++MBBI;
954344a3780SDimitry Andric       } while (MBBI != MBBE && MBBI->isDebugOrPseudoInstr());
955cf099d11SDimitry Andric     }
956cf099d11SDimitry Andric   }
957cf099d11SDimitry Andric   return Changed;
958cf099d11SDimitry Andric }
959cf099d11SDimitry Andric 
extendDef(SlotIndex Idx,DbgVariableValue DbgValue,SmallDenseMap<unsigned,std::pair<LiveRange *,const VNInfo * >> & LiveIntervalInfo,std::optional<std::pair<SlotIndex,SmallVector<unsigned>>> & Kills,LiveIntervals & LIS)960344a3780SDimitry Andric void UserValue::extendDef(
961344a3780SDimitry Andric     SlotIndex Idx, DbgVariableValue DbgValue,
962344a3780SDimitry Andric     SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>>
963344a3780SDimitry Andric         &LiveIntervalInfo,
964e3b55780SDimitry Andric     std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills,
965b915e9e0SDimitry Andric     LiveIntervals &LIS) {
966dd58ef01SDimitry Andric   SlotIndex Start = Idx;
967cf099d11SDimitry Andric   MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
968cf099d11SDimitry Andric   SlotIndex Stop = LIS.getMBBEndIdx(MBB);
969cf099d11SDimitry Andric   LocMap::iterator I = locInts.find(Start);
970cf099d11SDimitry Andric 
971344a3780SDimitry Andric   // Limit to the intersection of the VNIs' live ranges.
972344a3780SDimitry Andric   for (auto &LII : LiveIntervalInfo) {
973344a3780SDimitry Andric     LiveRange *LR = LII.second.first;
974344a3780SDimitry Andric     assert(LR && LII.second.second && "Missing range info for Idx.");
975f8af5cf6SDimitry Andric     LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
976344a3780SDimitry Andric     assert(Segment && Segment->valno == LII.second.second &&
977344a3780SDimitry Andric            "Invalid VNInfo for Idx given?");
97801095a5dSDimitry Andric     if (Segment->end < Stop) {
97901095a5dSDimitry Andric       Stop = Segment->end;
980344a3780SDimitry Andric       Kills = {Stop, {LII.first}};
981145449b1SDimitry Andric     } else if (Segment->end == Stop && Kills) {
982344a3780SDimitry Andric       // If multiple locations end at the same place, track all of them in
983344a3780SDimitry Andric       // Kills.
984344a3780SDimitry Andric       Kills->second.push_back(LII.first);
98501095a5dSDimitry Andric     }
986cf099d11SDimitry Andric   }
987cf099d11SDimitry Andric 
988cf099d11SDimitry Andric   // There could already be a short def at Start.
989cf099d11SDimitry Andric   if (I.valid() && I.start() <= Start) {
990cf099d11SDimitry Andric     // Stop when meeting a different location or an already extended interval.
991cf099d11SDimitry Andric     Start = Start.getNextSlot();
992344a3780SDimitry Andric     if (I.value() != DbgValue || I.stop() != Start) {
993344a3780SDimitry Andric       // Clear `Kills`, as we have a new def available.
994e3b55780SDimitry Andric       Kills = std::nullopt;
995dd58ef01SDimitry Andric       return;
996344a3780SDimitry Andric     }
997cf099d11SDimitry Andric     // This is a one-slot placeholder. Just skip it.
998cf099d11SDimitry Andric     ++I;
999cf099d11SDimitry Andric   }
1000cf099d11SDimitry Andric 
1001cf099d11SDimitry Andric   // Limited by the next def.
1002344a3780SDimitry Andric   if (I.valid() && I.start() < Stop) {
100301095a5dSDimitry Andric     Stop = I.start();
1004344a3780SDimitry Andric     // Clear `Kills`, as we have a new def available.
1005e3b55780SDimitry Andric     Kills = std::nullopt;
1006344a3780SDimitry Andric   }
1007cf099d11SDimitry Andric 
1008344a3780SDimitry Andric   if (Start < Stop) {
1009344a3780SDimitry Andric     DbgVariableValue ExtDbgValue(DbgValue);
1010344a3780SDimitry Andric     I.insert(Start, Stop, std::move(ExtDbgValue));
1011344a3780SDimitry Andric   }
1012cf099d11SDimitry Andric }
1013cf099d11SDimitry Andric 
addDefsFromCopies(DbgVariableValue DbgValue,SmallVectorImpl<std::pair<unsigned,LiveInterval * >> & LocIntervals,SlotIndex KilledAt,SmallVectorImpl<std::pair<SlotIndex,DbgVariableValue>> & NewDefs,MachineRegisterInfo & MRI,LiveIntervals & LIS)1014044eb2f6SDimitry Andric void UserValue::addDefsFromCopies(
1015344a3780SDimitry Andric     DbgVariableValue DbgValue,
1016344a3780SDimitry Andric     SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals,
1017344a3780SDimitry Andric     SlotIndex KilledAt,
1018cfca06d7SDimitry Andric     SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
10196b943ff3SDimitry Andric     MachineRegisterInfo &MRI, LiveIntervals &LIS) {
10206b943ff3SDimitry Andric   // Don't track copies from physregs, there are too many uses.
1021e3b55780SDimitry Andric   if (any_of(LocIntervals,
1022e3b55780SDimitry Andric              [](auto LocI) { return !LocI.second->reg().isVirtual(); }))
10236b943ff3SDimitry Andric     return;
10246b943ff3SDimitry Andric 
10256b943ff3SDimitry Andric   // Collect all the (vreg, valno) pairs that are copies of LI.
1026344a3780SDimitry Andric   SmallDenseMap<unsigned,
1027344a3780SDimitry Andric                 SmallVector<std::pair<LiveInterval *, const VNInfo *>, 4>>
1028344a3780SDimitry Andric       CopyValues;
1029344a3780SDimitry Andric   for (auto &LocInterval : LocIntervals) {
1030344a3780SDimitry Andric     unsigned LocNo = LocInterval.first;
1031344a3780SDimitry Andric     LiveInterval *LI = LocInterval.second;
1032b60736ecSDimitry Andric     for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg())) {
10335ca98fd9SDimitry Andric       MachineInstr *MI = MO.getParent();
10346b943ff3SDimitry Andric       // Copies of the full value.
10355ca98fd9SDimitry Andric       if (MO.getSubReg() || !MI->isCopy())
10366b943ff3SDimitry Andric         continue;
10371d5ae102SDimitry Andric       Register DstReg = MI->getOperand(0).getReg();
10386b943ff3SDimitry Andric 
10396b943ff3SDimitry Andric       // Don't follow copies to physregs. These are usually setting up call
10406b943ff3SDimitry Andric       // arguments, and the argument registers are always call clobbered. We are
1041344a3780SDimitry Andric       // better off in the source register which could be a callee-saved
1042344a3780SDimitry Andric       // register, or it could be spilled.
1043e3b55780SDimitry Andric       if (!DstReg.isVirtual())
10446b943ff3SDimitry Andric         continue;
10456b943ff3SDimitry Andric 
1046cfca06d7SDimitry Andric       // Is the value extended to reach this copy? If not, another def may be
1047cfca06d7SDimitry Andric       // blocking it, or we are looking at a wrong value of LI.
104801095a5dSDimitry Andric       SlotIndex Idx = LIS.getInstructionIndex(*MI);
104963faed5bSDimitry Andric       LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
1050cfca06d7SDimitry Andric       if (!I.valid() || I.value() != DbgValue)
10516b943ff3SDimitry Andric         continue;
10526b943ff3SDimitry Andric 
10536b943ff3SDimitry Andric       if (!LIS.hasInterval(DstReg))
10546b943ff3SDimitry Andric         continue;
10556b943ff3SDimitry Andric       LiveInterval *DstLI = &LIS.getInterval(DstReg);
105663faed5bSDimitry Andric       const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
105763faed5bSDimitry Andric       assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
1058344a3780SDimitry Andric       CopyValues[LocNo].push_back(std::make_pair(DstLI, DstVNI));
1059344a3780SDimitry Andric     }
10606b943ff3SDimitry Andric   }
10616b943ff3SDimitry Andric 
10626b943ff3SDimitry Andric   if (CopyValues.empty())
10636b943ff3SDimitry Andric     return;
10646b943ff3SDimitry Andric 
1065344a3780SDimitry Andric #if !defined(NDEBUG)
1066344a3780SDimitry Andric   for (auto &LocInterval : LocIntervals)
1067344a3780SDimitry Andric     LLVM_DEBUG(dbgs() << "Got " << CopyValues[LocInterval.first].size()
1068344a3780SDimitry Andric                       << " copies of " << *LocInterval.second << '\n');
1069344a3780SDimitry Andric #endif
10706b943ff3SDimitry Andric 
1071344a3780SDimitry Andric   // Try to add defs of the copied values for the kill point. Check that there
1072344a3780SDimitry Andric   // isn't already a def at Idx.
1073344a3780SDimitry Andric   LocMap::iterator I = locInts.find(KilledAt);
1074344a3780SDimitry Andric   if (I.valid() && I.start() <= KilledAt)
1075344a3780SDimitry Andric     return;
1076344a3780SDimitry Andric   DbgVariableValue NewValue(DbgValue);
1077344a3780SDimitry Andric   for (auto &LocInterval : LocIntervals) {
1078344a3780SDimitry Andric     unsigned LocNo = LocInterval.first;
1079344a3780SDimitry Andric     bool FoundCopy = false;
1080344a3780SDimitry Andric     for (auto &LIAndVNI : CopyValues[LocNo]) {
1081344a3780SDimitry Andric       LiveInterval *DstLI = LIAndVNI.first;
1082344a3780SDimitry Andric       const VNInfo *DstVNI = LIAndVNI.second;
1083344a3780SDimitry Andric       if (DstLI->getVNInfoAt(KilledAt) != DstVNI)
10846b943ff3SDimitry Andric         continue;
1085344a3780SDimitry Andric       LLVM_DEBUG(dbgs() << "Kill at " << KilledAt << " covered by valno #"
10866b943ff3SDimitry Andric                         << DstVNI->id << " in " << *DstLI << '\n');
10876b943ff3SDimitry Andric       MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
10886b943ff3SDimitry Andric       assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
1089344a3780SDimitry Andric       unsigned NewLocNo = getLocationNo(CopyMI->getOperand(0));
1090344a3780SDimitry Andric       NewValue = NewValue.changeLocNo(LocNo, NewLocNo);
1091344a3780SDimitry Andric       FoundCopy = true;
10926b943ff3SDimitry Andric       break;
10936b943ff3SDimitry Andric     }
1094344a3780SDimitry Andric     // If there are any killed locations we can't find a copy for, we can't
1095344a3780SDimitry Andric     // extend the variable value.
1096344a3780SDimitry Andric     if (!FoundCopy)
1097344a3780SDimitry Andric       return;
10986b943ff3SDimitry Andric   }
1099344a3780SDimitry Andric   I.insert(KilledAt, KilledAt.getNextSlot(), NewValue);
1100344a3780SDimitry Andric   NewDefs.push_back(std::make_pair(KilledAt, NewValue));
11016b943ff3SDimitry Andric }
11026b943ff3SDimitry Andric 
computeIntervals(MachineRegisterInfo & MRI,const TargetRegisterInfo & TRI,LiveIntervals & LIS,LexicalScopes & LS)1103044eb2f6SDimitry Andric void UserValue::computeIntervals(MachineRegisterInfo &MRI,
110458b69754SDimitry Andric                                  const TargetRegisterInfo &TRI,
1105044eb2f6SDimitry Andric                                  LiveIntervals &LIS, LexicalScopes &LS) {
1106cfca06d7SDimitry Andric   SmallVector<std::pair<SlotIndex, DbgVariableValue>, 16> Defs;
1107cf099d11SDimitry Andric 
1108cf099d11SDimitry Andric   // Collect all defs to be extended (Skipping undefs).
1109cf099d11SDimitry Andric   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
1110044eb2f6SDimitry Andric     if (!I.value().isUndef())
1111cf099d11SDimitry Andric       Defs.push_back(std::make_pair(I.start(), I.value()));
1112cf099d11SDimitry Andric 
11136b943ff3SDimitry Andric   // Extend all defs, and possibly add new ones along the way.
11146b943ff3SDimitry Andric   for (unsigned i = 0; i != Defs.size(); ++i) {
1115cf099d11SDimitry Andric     SlotIndex Idx = Defs[i].first;
1116cfca06d7SDimitry Andric     DbgVariableValue DbgValue = Defs[i].second;
1117344a3780SDimitry Andric     SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>> LIs;
1118344a3780SDimitry Andric     SmallVector<const VNInfo *, 4> VNIs;
1119344a3780SDimitry Andric     bool ShouldExtendDef = false;
1120344a3780SDimitry Andric     for (unsigned LocNo : DbgValue.loc_nos()) {
1121344a3780SDimitry Andric       const MachineOperand &LocMO = locations[LocNo];
1122e3b55780SDimitry Andric       if (!LocMO.isReg() || !LocMO.getReg().isVirtual()) {
1123344a3780SDimitry Andric         ShouldExtendDef |= !LocMO.isReg();
112458b69754SDimitry Andric         continue;
112558b69754SDimitry Andric       }
1126344a3780SDimitry Andric       ShouldExtendDef = true;
11275ca98fd9SDimitry Andric       LiveInterval *LI = nullptr;
11285ca98fd9SDimitry Andric       const VNInfo *VNI = nullptr;
1129044eb2f6SDimitry Andric       if (LIS.hasInterval(LocMO.getReg())) {
1130044eb2f6SDimitry Andric         LI = &LIS.getInterval(LocMO.getReg());
113158b69754SDimitry Andric         VNI = LI->getVNInfoAt(Idx);
113258b69754SDimitry Andric       }
1133344a3780SDimitry Andric       if (LI && VNI)
1134344a3780SDimitry Andric         LIs[LocNo] = {LI, VNI};
1135344a3780SDimitry Andric     }
1136344a3780SDimitry Andric     if (ShouldExtendDef) {
1137e3b55780SDimitry Andric       std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> Kills;
1138344a3780SDimitry Andric       extendDef(Idx, DbgValue, LIs, Kills, LIS);
1139344a3780SDimitry Andric 
1140344a3780SDimitry Andric       if (Kills) {
1141344a3780SDimitry Andric         SmallVector<std::pair<unsigned, LiveInterval *>, 2> KilledLocIntervals;
1142344a3780SDimitry Andric         bool AnySubreg = false;
1143344a3780SDimitry Andric         for (unsigned LocNo : Kills->second) {
1144344a3780SDimitry Andric           const MachineOperand &LocMO = this->locations[LocNo];
1145344a3780SDimitry Andric           if (LocMO.getSubReg()) {
1146344a3780SDimitry Andric             AnySubreg = true;
1147344a3780SDimitry Andric             break;
1148344a3780SDimitry Andric           }
1149344a3780SDimitry Andric           LiveInterval *LI = &LIS.getInterval(LocMO.getReg());
1150344a3780SDimitry Andric           KilledLocIntervals.push_back({LocNo, LI});
1151344a3780SDimitry Andric         }
1152344a3780SDimitry Andric 
1153d8e91e46SDimitry Andric         // FIXME: Handle sub-registers in addDefsFromCopies. The problem is that
1154d8e91e46SDimitry Andric         // if the original location for example is %vreg0:sub_hi, and we find a
1155344a3780SDimitry Andric         // full register copy in addDefsFromCopies (at the moment it only
1156344a3780SDimitry Andric         // handles full register copies), then we must add the sub1 sub-register
1157344a3780SDimitry Andric         // index to the new location. However, that is only possible if the new
1158344a3780SDimitry Andric         // virtual register is of the same regclass (or if there is an
1159344a3780SDimitry Andric         // equivalent sub-register in that regclass). For now, simply skip
1160344a3780SDimitry Andric         // handling copies if a sub-register is involved.
1161344a3780SDimitry Andric         if (!AnySubreg)
1162344a3780SDimitry Andric           addDefsFromCopies(DbgValue, KilledLocIntervals, Kills->first, Defs,
1163344a3780SDimitry Andric                             MRI, LIS);
1164344a3780SDimitry Andric       }
116558b69754SDimitry Andric     }
116658b69754SDimitry Andric 
1167044eb2f6SDimitry Andric     // For physregs, we only mark the start slot idx. DwarfDebug will see it
1168044eb2f6SDimitry Andric     // as if the DBG_VALUE is valid up until the end of the basic block, or
1169044eb2f6SDimitry Andric     // the next def of the physical register. So we do not need to extend the
1170044eb2f6SDimitry Andric     // range. It might actually happen that the DBG_VALUE is the last use of
1171044eb2f6SDimitry Andric     // the physical register (e.g. if this is an unused input argument to a
1172044eb2f6SDimitry Andric     // function).
1173cf099d11SDimitry Andric   }
1174cf099d11SDimitry Andric 
1175044eb2f6SDimitry Andric   // The computed intervals may extend beyond the range of the debug
1176044eb2f6SDimitry Andric   // location's lexical scope. In this case, splitting of an interval
1177044eb2f6SDimitry Andric   // can result in an interval outside of the scope being created,
1178044eb2f6SDimitry Andric   // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
1179344a3780SDimitry Andric   // this, trim the intervals to the lexical scope in the case of inlined
1180344a3780SDimitry Andric   // variables, since heavy inlining may cause production of dramatically big
1181344a3780SDimitry Andric   // number of DBG_VALUEs to be generated.
1182344a3780SDimitry Andric   if (!dl.getInlinedAt())
1183344a3780SDimitry Andric     return;
1184044eb2f6SDimitry Andric 
1185044eb2f6SDimitry Andric   LexicalScope *Scope = LS.findLexicalScope(dl);
1186044eb2f6SDimitry Andric   if (!Scope)
1187044eb2f6SDimitry Andric     return;
1188044eb2f6SDimitry Andric 
1189044eb2f6SDimitry Andric   SlotIndex PrevEnd;
1190044eb2f6SDimitry Andric   LocMap::iterator I = locInts.begin();
1191044eb2f6SDimitry Andric 
1192044eb2f6SDimitry Andric   // Iterate over the lexical scope ranges. Each time round the loop
1193044eb2f6SDimitry Andric   // we check the intervals for overlap with the end of the previous
1194044eb2f6SDimitry Andric   // range and the start of the next. The first range is handled as
1195044eb2f6SDimitry Andric   // a special case where there is no PrevEnd.
1196044eb2f6SDimitry Andric   for (const InsnRange &Range : Scope->getRanges()) {
1197044eb2f6SDimitry Andric     SlotIndex RStart = LIS.getInstructionIndex(*Range.first);
1198044eb2f6SDimitry Andric     SlotIndex REnd = LIS.getInstructionIndex(*Range.second);
1199044eb2f6SDimitry Andric 
1200cfca06d7SDimitry Andric     // Variable locations at the first instruction of a block should be
1201cfca06d7SDimitry Andric     // based on the block's SlotIndex, not the first instruction's index.
1202cfca06d7SDimitry Andric     if (Range.first == Range.first->getParent()->begin())
1203cfca06d7SDimitry Andric       RStart = LIS.getSlotIndexes()->getIndexBefore(*Range.first);
1204cfca06d7SDimitry Andric 
1205044eb2f6SDimitry Andric     // At the start of each iteration I has been advanced so that
1206044eb2f6SDimitry Andric     // I.stop() >= PrevEnd. Check for overlap.
1207044eb2f6SDimitry Andric     if (PrevEnd && I.start() < PrevEnd) {
1208044eb2f6SDimitry Andric       SlotIndex IStop = I.stop();
1209cfca06d7SDimitry Andric       DbgVariableValue DbgValue = I.value();
1210044eb2f6SDimitry Andric 
1211044eb2f6SDimitry Andric       // Stop overlaps previous end - trim the end of the interval to
1212044eb2f6SDimitry Andric       // the scope range.
1213044eb2f6SDimitry Andric       I.setStopUnchecked(PrevEnd);
1214044eb2f6SDimitry Andric       ++I;
1215044eb2f6SDimitry Andric 
1216044eb2f6SDimitry Andric       // If the interval also overlaps the start of the "next" (i.e.
1217cfca06d7SDimitry Andric       // current) range create a new interval for the remainder (which
1218cfca06d7SDimitry Andric       // may be further trimmed).
1219044eb2f6SDimitry Andric       if (RStart < IStop)
1220cfca06d7SDimitry Andric         I.insert(RStart, IStop, DbgValue);
1221044eb2f6SDimitry Andric     }
1222044eb2f6SDimitry Andric 
1223044eb2f6SDimitry Andric     // Advance I so that I.stop() >= RStart, and check for overlap.
1224044eb2f6SDimitry Andric     I.advanceTo(RStart);
1225044eb2f6SDimitry Andric     if (!I.valid())
1226044eb2f6SDimitry Andric       return;
1227044eb2f6SDimitry Andric 
1228cfca06d7SDimitry Andric     if (I.start() < RStart) {
1229cfca06d7SDimitry Andric       // Interval start overlaps range - trim to the scope range.
1230cfca06d7SDimitry Andric       I.setStartUnchecked(RStart);
1231cfca06d7SDimitry Andric       // Remember that this interval was trimmed.
1232cfca06d7SDimitry Andric       trimmedDefs.insert(RStart);
1233cfca06d7SDimitry Andric     }
1234cfca06d7SDimitry Andric 
1235044eb2f6SDimitry Andric     // The end of a lexical scope range is the last instruction in the
1236044eb2f6SDimitry Andric     // range. To convert to an interval we need the index of the
1237044eb2f6SDimitry Andric     // instruction after it.
1238044eb2f6SDimitry Andric     REnd = REnd.getNextIndex();
1239044eb2f6SDimitry Andric 
1240044eb2f6SDimitry Andric     // Advance I to first interval outside current range.
1241044eb2f6SDimitry Andric     I.advanceTo(REnd);
1242044eb2f6SDimitry Andric     if (!I.valid())
1243044eb2f6SDimitry Andric       return;
1244044eb2f6SDimitry Andric 
1245044eb2f6SDimitry Andric     PrevEnd = REnd;
1246044eb2f6SDimitry Andric   }
1247044eb2f6SDimitry Andric 
1248044eb2f6SDimitry Andric   // Check for overlap with end of final range.
1249044eb2f6SDimitry Andric   if (PrevEnd && I.start() < PrevEnd)
1250044eb2f6SDimitry Andric     I.setStopUnchecked(PrevEnd);
1251cf099d11SDimitry Andric }
1252cf099d11SDimitry Andric 
computeIntervals()1253cf099d11SDimitry Andric void LDVImpl::computeIntervals() {
1254044eb2f6SDimitry Andric   LexicalScopes LS;
1255044eb2f6SDimitry Andric   LS.initialize(*MF);
1256044eb2f6SDimitry Andric 
1257ac9a064cSDimitry Andric   for (const auto &UV : userValues) {
1258ac9a064cSDimitry Andric     UV->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS);
1259ac9a064cSDimitry Andric     UV->mapVirtRegs(this);
12606b943ff3SDimitry Andric   }
1261cf099d11SDimitry Andric }
1262cf099d11SDimitry Andric 
runOnMachineFunction(MachineFunction & mf,bool InstrRef)1263344a3780SDimitry Andric bool LDVImpl::runOnMachineFunction(MachineFunction &mf, bool InstrRef) {
126467c32a98SDimitry Andric   clear();
1265cf099d11SDimitry Andric   MF = &mf;
1266ac9a064cSDimitry Andric   LIS = &pass.getAnalysis<LiveIntervalsWrapperPass>().getLIS();
126767c32a98SDimitry Andric   TRI = mf.getSubtarget().getRegisterInfo();
1268eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
1269522600a2SDimitry Andric                     << mf.getName() << " **********\n");
1270cf099d11SDimitry Andric 
1271344a3780SDimitry Andric   bool Changed = collectDebugValues(mf, InstrRef);
1272cf099d11SDimitry Andric   computeIntervals();
1273eb11fae6SDimitry Andric   LLVM_DEBUG(print(dbgs()));
1274344a3780SDimitry Andric 
1275344a3780SDimitry Andric   // Collect the set of VReg / SlotIndexs where PHIs occur; index the sensitive
1276344a3780SDimitry Andric   // VRegs too, for when we're notified of a range split.
1277344a3780SDimitry Andric   SlotIndexes *Slots = LIS->getSlotIndexes();
1278344a3780SDimitry Andric   for (const auto &PHIIt : MF->DebugPHIPositions) {
1279344a3780SDimitry Andric     const MachineFunction::DebugPHIRegallocPos &Position = PHIIt.second;
1280344a3780SDimitry Andric     MachineBasicBlock *MBB = Position.MBB;
1281344a3780SDimitry Andric     Register Reg = Position.Reg;
1282344a3780SDimitry Andric     unsigned SubReg = Position.SubReg;
1283344a3780SDimitry Andric     SlotIndex SI = Slots->getMBBStartIdx(MBB);
1284344a3780SDimitry Andric     PHIValPos VP = {SI, Reg, SubReg};
1285344a3780SDimitry Andric     PHIValToPos.insert(std::make_pair(PHIIt.first, VP));
1286344a3780SDimitry Andric     RegToPHIIdx[Reg].push_back(PHIIt.first);
1287344a3780SDimitry Andric   }
1288344a3780SDimitry Andric 
12894a16efa3SDimitry Andric   ModifiedMF = Changed;
1290cf099d11SDimitry Andric   return Changed;
1291cf099d11SDimitry Andric }
1292cf099d11SDimitry Andric 
removeDebugInstrs(MachineFunction & mf)1293b60736ecSDimitry Andric static void removeDebugInstrs(MachineFunction &mf) {
129467c32a98SDimitry Andric   for (MachineBasicBlock &MBB : mf) {
1295c0981da4SDimitry Andric     for (MachineInstr &MI : llvm::make_early_inc_range(MBB))
1296c0981da4SDimitry Andric       if (MI.isDebugInstr())
1297c0981da4SDimitry Andric         MBB.erase(&MI);
129867c32a98SDimitry Andric   }
129967c32a98SDimitry Andric }
130067c32a98SDimitry Andric 
runOnMachineFunction(MachineFunction & mf)1301cf099d11SDimitry Andric bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
1302cf099d11SDimitry Andric   if (!EnableLDV)
1303cf099d11SDimitry Andric     return false;
1304044eb2f6SDimitry Andric   if (!mf.getFunction().getSubprogram()) {
1305b60736ecSDimitry Andric     removeDebugInstrs(mf);
130667c32a98SDimitry Andric     return false;
130767c32a98SDimitry Andric   }
1308344a3780SDimitry Andric 
1309344a3780SDimitry Andric   // Have we been asked to track variable locations using instruction
1310344a3780SDimitry Andric   // referencing?
1311c0981da4SDimitry Andric   bool InstrRef = mf.useDebugInstrRef();
1312344a3780SDimitry Andric 
1313cf099d11SDimitry Andric   if (!pImpl)
1314cf099d11SDimitry Andric     pImpl = new LDVImpl(this);
1315344a3780SDimitry Andric   return static_cast<LDVImpl *>(pImpl)->runOnMachineFunction(mf, InstrRef);
1316cf099d11SDimitry Andric }
1317cf099d11SDimitry Andric 
releaseMemory()1318cf099d11SDimitry Andric void LiveDebugVariables::releaseMemory() {
1319cf099d11SDimitry Andric   if (pImpl)
1320cf099d11SDimitry Andric     static_cast<LDVImpl*>(pImpl)->clear();
1321cf099d11SDimitry Andric }
1322cf099d11SDimitry Andric 
~LiveDebugVariables()1323cf099d11SDimitry Andric LiveDebugVariables::~LiveDebugVariables() {
1324cf099d11SDimitry Andric   if (pImpl)
1325cf099d11SDimitry Andric     delete static_cast<LDVImpl*>(pImpl);
1326cf099d11SDimitry Andric }
1327cf099d11SDimitry Andric 
132856fe8f14SDimitry Andric //===----------------------------------------------------------------------===//
132956fe8f14SDimitry Andric //                           Live Range Splitting
133056fe8f14SDimitry Andric //===----------------------------------------------------------------------===//
133156fe8f14SDimitry Andric 
133256fe8f14SDimitry Andric bool
splitLocation(unsigned OldLocNo,ArrayRef<Register> NewRegs,LiveIntervals & LIS)1333cfca06d7SDimitry Andric UserValue::splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs,
1334f8af5cf6SDimitry Andric                          LiveIntervals& LIS) {
1335eb11fae6SDimitry Andric   LLVM_DEBUG({
133656fe8f14SDimitry Andric     dbgs() << "Splitting Loc" << OldLocNo << '\t';
13375ca98fd9SDimitry Andric     print(dbgs(), nullptr);
133856fe8f14SDimitry Andric   });
133956fe8f14SDimitry Andric   bool DidChange = false;
134056fe8f14SDimitry Andric   LocMap::iterator LocMapI;
134156fe8f14SDimitry Andric   LocMapI.setMap(locInts);
134277fc4c14SDimitry Andric   for (Register NewReg : NewRegs) {
134377fc4c14SDimitry Andric     LiveInterval *LI = &LIS.getInterval(NewReg);
134456fe8f14SDimitry Andric     if (LI->empty())
134556fe8f14SDimitry Andric       continue;
134656fe8f14SDimitry Andric 
134756fe8f14SDimitry Andric     // Don't allocate the new LocNo until it is needed.
1348044eb2f6SDimitry Andric     unsigned NewLocNo = UndefLocNo;
134956fe8f14SDimitry Andric 
135056fe8f14SDimitry Andric     // Iterate over the overlaps between locInts and LI.
135156fe8f14SDimitry Andric     LocMapI.find(LI->beginIndex());
135256fe8f14SDimitry Andric     if (!LocMapI.valid())
135356fe8f14SDimitry Andric       continue;
135456fe8f14SDimitry Andric     LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
135556fe8f14SDimitry Andric     LiveInterval::iterator LIE = LI->end();
135656fe8f14SDimitry Andric     while (LocMapI.valid() && LII != LIE) {
135756fe8f14SDimitry Andric       // At this point, we know that LocMapI.stop() > LII->start.
135856fe8f14SDimitry Andric       LII = LI->advanceTo(LII, LocMapI.start());
135956fe8f14SDimitry Andric       if (LII == LIE)
136056fe8f14SDimitry Andric         break;
136156fe8f14SDimitry Andric 
136256fe8f14SDimitry Andric       // Now LII->end > LocMapI.start(). Do we have an overlap?
1363344a3780SDimitry Andric       if (LocMapI.value().containsLocNo(OldLocNo) &&
1364cfca06d7SDimitry Andric           LII->start < LocMapI.stop()) {
136556fe8f14SDimitry Andric         // Overlapping correct location. Allocate NewLocNo now.
1366044eb2f6SDimitry Andric         if (NewLocNo == UndefLocNo) {
1367b60736ecSDimitry Andric           MachineOperand MO = MachineOperand::CreateReg(LI->reg(), false);
136856fe8f14SDimitry Andric           MO.setSubReg(locations[OldLocNo].getSubReg());
136956fe8f14SDimitry Andric           NewLocNo = getLocationNo(MO);
137056fe8f14SDimitry Andric           DidChange = true;
137156fe8f14SDimitry Andric         }
137256fe8f14SDimitry Andric 
137356fe8f14SDimitry Andric         SlotIndex LStart = LocMapI.start();
137456fe8f14SDimitry Andric         SlotIndex LStop = LocMapI.stop();
1375cfca06d7SDimitry Andric         DbgVariableValue OldDbgValue = LocMapI.value();
137656fe8f14SDimitry Andric 
137756fe8f14SDimitry Andric         // Trim LocMapI down to the LII overlap.
137856fe8f14SDimitry Andric         if (LStart < LII->start)
137956fe8f14SDimitry Andric           LocMapI.setStartUnchecked(LII->start);
138056fe8f14SDimitry Andric         if (LStop > LII->end)
138156fe8f14SDimitry Andric           LocMapI.setStopUnchecked(LII->end);
138256fe8f14SDimitry Andric 
138356fe8f14SDimitry Andric         // Change the value in the overlap. This may trigger coalescing.
1384344a3780SDimitry Andric         LocMapI.setValue(OldDbgValue.changeLocNo(OldLocNo, NewLocNo));
138556fe8f14SDimitry Andric 
1386cfca06d7SDimitry Andric         // Re-insert any removed OldDbgValue ranges.
138756fe8f14SDimitry Andric         if (LStart < LocMapI.start()) {
1388cfca06d7SDimitry Andric           LocMapI.insert(LStart, LocMapI.start(), OldDbgValue);
138956fe8f14SDimitry Andric           ++LocMapI;
139056fe8f14SDimitry Andric           assert(LocMapI.valid() && "Unexpected coalescing");
139156fe8f14SDimitry Andric         }
139256fe8f14SDimitry Andric         if (LStop > LocMapI.stop()) {
139356fe8f14SDimitry Andric           ++LocMapI;
1394cfca06d7SDimitry Andric           LocMapI.insert(LII->end, LStop, OldDbgValue);
139556fe8f14SDimitry Andric           --LocMapI;
139656fe8f14SDimitry Andric         }
139756fe8f14SDimitry Andric       }
139856fe8f14SDimitry Andric 
139956fe8f14SDimitry Andric       // Advance to the next overlap.
140056fe8f14SDimitry Andric       if (LII->end < LocMapI.stop()) {
140156fe8f14SDimitry Andric         if (++LII == LIE)
140256fe8f14SDimitry Andric           break;
140356fe8f14SDimitry Andric         LocMapI.advanceTo(LII->start);
140456fe8f14SDimitry Andric       } else {
140556fe8f14SDimitry Andric         ++LocMapI;
140656fe8f14SDimitry Andric         if (!LocMapI.valid())
140756fe8f14SDimitry Andric           break;
140856fe8f14SDimitry Andric         LII = LI->advanceTo(LII, LocMapI.start());
140956fe8f14SDimitry Andric       }
141056fe8f14SDimitry Andric     }
141156fe8f14SDimitry Andric   }
141256fe8f14SDimitry Andric 
1413706b4fc4SDimitry Andric   // Finally, remove OldLocNo unless it is still used by some interval in the
1414706b4fc4SDimitry Andric   // locInts map. One case when OldLocNo still is in use is when the register
1415706b4fc4SDimitry Andric   // has been spilled. In such situations the spilled register is kept as a
1416706b4fc4SDimitry Andric   // location until rewriteLocations is called (VirtRegMap is mapping the old
1417706b4fc4SDimitry Andric   // register to the spill slot). So for a while we can have locations that map
1418706b4fc4SDimitry Andric   // to virtual registers that have been removed from both the MachineFunction
1419706b4fc4SDimitry Andric   // and from LiveIntervals.
1420cfca06d7SDimitry Andric   //
1421cfca06d7SDimitry Andric   // We may also just be using the location for a value with a different
1422cfca06d7SDimitry Andric   // expression.
1423706b4fc4SDimitry Andric   removeLocationIfUnused(OldLocNo);
142456fe8f14SDimitry Andric 
1425eb11fae6SDimitry Andric   LLVM_DEBUG({
1426eb11fae6SDimitry Andric     dbgs() << "Split result: \t";
1427eb11fae6SDimitry Andric     print(dbgs(), nullptr);
1428eb11fae6SDimitry Andric   });
142956fe8f14SDimitry Andric   return DidChange;
143056fe8f14SDimitry Andric }
143156fe8f14SDimitry Andric 
143256fe8f14SDimitry Andric bool
splitRegister(Register OldReg,ArrayRef<Register> NewRegs,LiveIntervals & LIS)1433cfca06d7SDimitry Andric UserValue::splitRegister(Register OldReg, ArrayRef<Register> NewRegs,
1434f8af5cf6SDimitry Andric                          LiveIntervals &LIS) {
143556fe8f14SDimitry Andric   bool DidChange = false;
143656fe8f14SDimitry Andric   // Split locations referring to OldReg. Iterate backwards so splitLocation can
143763faed5bSDimitry Andric   // safely erase unused locations.
143856fe8f14SDimitry Andric   for (unsigned i = locations.size(); i ; --i) {
143956fe8f14SDimitry Andric     unsigned LocNo = i-1;
144056fe8f14SDimitry Andric     const MachineOperand *Loc = &locations[LocNo];
144156fe8f14SDimitry Andric     if (!Loc->isReg() || Loc->getReg() != OldReg)
144256fe8f14SDimitry Andric       continue;
1443f8af5cf6SDimitry Andric     DidChange |= splitLocation(LocNo, NewRegs, LIS);
144456fe8f14SDimitry Andric   }
144556fe8f14SDimitry Andric   return DidChange;
144656fe8f14SDimitry Andric }
144756fe8f14SDimitry Andric 
splitPHIRegister(Register OldReg,ArrayRef<Register> NewRegs)1448344a3780SDimitry Andric void LDVImpl::splitPHIRegister(Register OldReg, ArrayRef<Register> NewRegs) {
1449344a3780SDimitry Andric   auto RegIt = RegToPHIIdx.find(OldReg);
1450344a3780SDimitry Andric   if (RegIt == RegToPHIIdx.end())
1451344a3780SDimitry Andric     return;
1452344a3780SDimitry Andric 
1453344a3780SDimitry Andric   std::vector<std::pair<Register, unsigned>> NewRegIdxes;
1454344a3780SDimitry Andric   // Iterate over all the debug instruction numbers affected by this split.
1455344a3780SDimitry Andric   for (unsigned InstrID : RegIt->second) {
1456344a3780SDimitry Andric     auto PHIIt = PHIValToPos.find(InstrID);
1457344a3780SDimitry Andric     assert(PHIIt != PHIValToPos.end());
1458344a3780SDimitry Andric     const SlotIndex &Slot = PHIIt->second.SI;
1459344a3780SDimitry Andric     assert(OldReg == PHIIt->second.Reg);
1460344a3780SDimitry Andric 
1461344a3780SDimitry Andric     // Find the new register that covers this position.
1462344a3780SDimitry Andric     for (auto NewReg : NewRegs) {
1463344a3780SDimitry Andric       const LiveInterval &LI = LIS->getInterval(NewReg);
1464344a3780SDimitry Andric       auto LII = LI.find(Slot);
1465344a3780SDimitry Andric       if (LII != LI.end() && LII->start <= Slot) {
1466344a3780SDimitry Andric         // This new register covers this PHI position, record this for indexing.
1467344a3780SDimitry Andric         NewRegIdxes.push_back(std::make_pair(NewReg, InstrID));
1468344a3780SDimitry Andric         // Record that this value lives in a different VReg now.
1469344a3780SDimitry Andric         PHIIt->second.Reg = NewReg;
1470344a3780SDimitry Andric         break;
1471344a3780SDimitry Andric       }
1472344a3780SDimitry Andric     }
1473344a3780SDimitry Andric 
1474344a3780SDimitry Andric     // If we do not find a new register covering this PHI, then register
1475344a3780SDimitry Andric     // allocation has dropped its location, for example because it's not live.
1476344a3780SDimitry Andric     // The old VReg will not be mapped to a physreg, and the instruction
1477344a3780SDimitry Andric     // number will have been optimized out.
1478344a3780SDimitry Andric   }
1479344a3780SDimitry Andric 
1480344a3780SDimitry Andric   // Re-create register index using the new register numbers.
1481344a3780SDimitry Andric   RegToPHIIdx.erase(RegIt);
1482344a3780SDimitry Andric   for (auto &RegAndInstr : NewRegIdxes)
1483344a3780SDimitry Andric     RegToPHIIdx[RegAndInstr.first].push_back(RegAndInstr.second);
1484344a3780SDimitry Andric }
1485344a3780SDimitry Andric 
splitRegister(Register OldReg,ArrayRef<Register> NewRegs)1486cfca06d7SDimitry Andric void LDVImpl::splitRegister(Register OldReg, ArrayRef<Register> NewRegs) {
1487344a3780SDimitry Andric   // Consider whether this split range affects any PHI locations.
1488344a3780SDimitry Andric   splitPHIRegister(OldReg, NewRegs);
1489344a3780SDimitry Andric 
1490344a3780SDimitry Andric   // Check whether any intervals mapped by a DBG_VALUE were split and need
1491344a3780SDimitry Andric   // updating.
149256fe8f14SDimitry Andric   bool DidChange = false;
1493706b4fc4SDimitry Andric   for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
1494f8af5cf6SDimitry Andric     DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
149556fe8f14SDimitry Andric 
149656fe8f14SDimitry Andric   if (!DidChange)
149756fe8f14SDimitry Andric     return;
149856fe8f14SDimitry Andric 
149956fe8f14SDimitry Andric   // Map all of the new virtual registers.
1500706b4fc4SDimitry Andric   UserValue *UV = lookupVirtReg(OldReg);
150177fc4c14SDimitry Andric   for (Register NewReg : NewRegs)
150277fc4c14SDimitry Andric     mapVirtReg(NewReg, UV);
150356fe8f14SDimitry Andric }
150456fe8f14SDimitry Andric 
150556fe8f14SDimitry Andric void LiveDebugVariables::
splitRegister(Register OldReg,ArrayRef<Register> NewRegs,LiveIntervals & LIS)1506cfca06d7SDimitry Andric splitRegister(Register OldReg, ArrayRef<Register> NewRegs, LiveIntervals &LIS) {
150756fe8f14SDimitry Andric   if (pImpl)
150856fe8f14SDimitry Andric     static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
150956fe8f14SDimitry Andric }
151056fe8f14SDimitry Andric 
rewriteLocations(VirtRegMap & VRM,const MachineFunction & MF,const TargetInstrInfo & TII,const TargetRegisterInfo & TRI,SpillOffsetMap & SpillOffsets)1511d8e91e46SDimitry Andric void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
1512d8e91e46SDimitry Andric                                  const TargetInstrInfo &TII,
1513d8e91e46SDimitry Andric                                  const TargetRegisterInfo &TRI,
1514d8e91e46SDimitry Andric                                  SpillOffsetMap &SpillOffsets) {
1515044eb2f6SDimitry Andric   // Build a set of new locations with new numbers so we can coalesce our
1516044eb2f6SDimitry Andric   // IntervalMap if two vreg intervals collapse to the same physical location.
1517044eb2f6SDimitry Andric   // Use MapVector instead of SetVector because MapVector::insert returns the
1518044eb2f6SDimitry Andric   // position of the previously or newly inserted element. The boolean value
1519044eb2f6SDimitry Andric   // tracks if the location was produced by a spill.
1520044eb2f6SDimitry Andric   // FIXME: This will be problematic if we ever support direct and indirect
1521044eb2f6SDimitry Andric   // frame index locations, i.e. expressing both variables in memory and
1522044eb2f6SDimitry Andric   // 'int x, *px = &x'. The "spilled" bit must become part of the location.
1523d8e91e46SDimitry Andric   MapVector<MachineOperand, std::pair<bool, unsigned>> NewLocations;
1524044eb2f6SDimitry Andric   SmallVector<unsigned, 4> LocNoMap(locations.size());
1525044eb2f6SDimitry Andric   for (unsigned I = 0, E = locations.size(); I != E; ++I) {
1526044eb2f6SDimitry Andric     bool Spilled = false;
1527d8e91e46SDimitry Andric     unsigned SpillOffset = 0;
1528044eb2f6SDimitry Andric     MachineOperand Loc = locations[I];
1529cf099d11SDimitry Andric     // Only virtual registers are rewritten.
1530e3b55780SDimitry Andric     if (Loc.isReg() && Loc.getReg() && Loc.getReg().isVirtual()) {
15311d5ae102SDimitry Andric       Register VirtReg = Loc.getReg();
1532cf099d11SDimitry Andric       if (VRM.isAssignedReg(VirtReg) &&
15331d5ae102SDimitry Andric           Register::isPhysicalRegister(VRM.getPhys(VirtReg))) {
153456fe8f14SDimitry Andric         // This can create a %noreg operand in rare cases when the sub-register
153556fe8f14SDimitry Andric         // index is no longer available. That means the user value is in a
153656fe8f14SDimitry Andric         // non-existent sub-register, and %noreg is exactly what we want.
1537cf099d11SDimitry Andric         Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
153863faed5bSDimitry Andric       } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
1539d8e91e46SDimitry Andric         // Retrieve the stack slot offset.
1540d8e91e46SDimitry Andric         unsigned SpillSize;
1541d8e91e46SDimitry Andric         const MachineRegisterInfo &MRI = MF.getRegInfo();
1542d8e91e46SDimitry Andric         const TargetRegisterClass *TRC = MRI.getRegClass(VirtReg);
1543d8e91e46SDimitry Andric         bool Success = TII.getStackSlotRange(TRC, Loc.getSubReg(), SpillSize,
1544d8e91e46SDimitry Andric                                              SpillOffset, MF);
1545d8e91e46SDimitry Andric 
1546d8e91e46SDimitry Andric         // FIXME: Invalidate the location if the offset couldn't be calculated.
1547d8e91e46SDimitry Andric         (void)Success;
1548d8e91e46SDimitry Andric 
1549cf099d11SDimitry Andric         Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
1550044eb2f6SDimitry Andric         Spilled = true;
1551cf099d11SDimitry Andric       } else {
1552cf099d11SDimitry Andric         Loc.setReg(0);
1553cf099d11SDimitry Andric         Loc.setSubReg(0);
1554cf099d11SDimitry Andric       }
1555044eb2f6SDimitry Andric     }
1556044eb2f6SDimitry Andric 
1557044eb2f6SDimitry Andric     // Insert this location if it doesn't already exist and record a mapping
1558044eb2f6SDimitry Andric     // from the old number to the new number.
1559d8e91e46SDimitry Andric     auto InsertResult = NewLocations.insert({Loc, {Spilled, SpillOffset}});
1560044eb2f6SDimitry Andric     unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first);
1561044eb2f6SDimitry Andric     LocNoMap[I] = NewLocNo;
1562044eb2f6SDimitry Andric   }
1563044eb2f6SDimitry Andric 
1564d8e91e46SDimitry Andric   // Rewrite the locations and record the stack slot offsets for spills.
1565044eb2f6SDimitry Andric   locations.clear();
1566d8e91e46SDimitry Andric   SpillOffsets.clear();
1567044eb2f6SDimitry Andric   for (auto &Pair : NewLocations) {
1568d8e91e46SDimitry Andric     bool Spilled;
1569d8e91e46SDimitry Andric     unsigned SpillOffset;
1570d8e91e46SDimitry Andric     std::tie(Spilled, SpillOffset) = Pair.second;
1571044eb2f6SDimitry Andric     locations.push_back(Pair.first);
1572d8e91e46SDimitry Andric     if (Spilled) {
1573044eb2f6SDimitry Andric       unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair);
1574d8e91e46SDimitry Andric       SpillOffsets[NewLocNo] = SpillOffset;
1575cf099d11SDimitry Andric     }
1576cf099d11SDimitry Andric   }
1577cf099d11SDimitry Andric 
1578044eb2f6SDimitry Andric   // Update the interval map, but only coalesce left, since intervals to the
1579044eb2f6SDimitry Andric   // right use the old location numbers. This should merge two contiguous
1580044eb2f6SDimitry Andric   // DBG_VALUE intervals with different vregs that were allocated to the same
1581044eb2f6SDimitry Andric   // physical register.
1582044eb2f6SDimitry Andric   for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
1583344a3780SDimitry Andric     I.setValueUnchecked(I.value().remapLocNos(LocNoMap));
1584044eb2f6SDimitry Andric     I.setStart(I.start());
1585044eb2f6SDimitry Andric   }
1586044eb2f6SDimitry Andric }
1587044eb2f6SDimitry Andric 
1588044eb2f6SDimitry Andric /// Find an iterator for inserting a DBG_VALUE instruction.
1589cf099d11SDimitry Andric static MachineBasicBlock::iterator
findInsertLocation(MachineBasicBlock * MBB,SlotIndex Idx,LiveIntervals & LIS,BlockSkipInstsMap & BBSkipInstsMap)1590344a3780SDimitry Andric findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx, LiveIntervals &LIS,
1591344a3780SDimitry Andric                    BlockSkipInstsMap &BBSkipInstsMap) {
1592cf099d11SDimitry Andric   SlotIndex Start = LIS.getMBBStartIdx(MBB);
1593cf099d11SDimitry Andric   Idx = Idx.getBaseIndex();
1594cf099d11SDimitry Andric 
1595cf099d11SDimitry Andric   // Try to find an insert location by going backwards from Idx.
1596cf099d11SDimitry Andric   MachineInstr *MI;
1597cf099d11SDimitry Andric   while (!(MI = LIS.getInstructionFromIndex(Idx))) {
1598cf099d11SDimitry Andric     // We've reached the beginning of MBB.
1599cf099d11SDimitry Andric     if (Idx == Start) {
1600344a3780SDimitry Andric       // Retrieve the last PHI/Label/Debug location found when calling
1601344a3780SDimitry Andric       // SkipPHIsLabelsAndDebug last time. Start searching from there.
1602344a3780SDimitry Andric       //
1603344a3780SDimitry Andric       // Note the iterator kept in BBSkipInstsMap is one step back based
1604344a3780SDimitry Andric       // on the iterator returned by SkipPHIsLabelsAndDebug last time.
1605344a3780SDimitry Andric       // One exception is when SkipPHIsLabelsAndDebug returns MBB->begin(),
1606344a3780SDimitry Andric       // BBSkipInstsMap won't save it. This is to consider the case that
1607344a3780SDimitry Andric       // new instructions may be inserted at the beginning of MBB after
1608344a3780SDimitry Andric       // last call of SkipPHIsLabelsAndDebug. If we save MBB->begin() in
1609344a3780SDimitry Andric       // BBSkipInstsMap, after new non-phi/non-label/non-debug instructions
1610344a3780SDimitry Andric       // are inserted at the beginning of the MBB, the iterator in
1611344a3780SDimitry Andric       // BBSkipInstsMap won't point to the beginning of the MBB anymore.
1612344a3780SDimitry Andric       // Therefore The next search in SkipPHIsLabelsAndDebug will skip those
1613344a3780SDimitry Andric       // newly added instructions and that is unwanted.
1614344a3780SDimitry Andric       MachineBasicBlock::iterator BeginIt;
1615344a3780SDimitry Andric       auto MapIt = BBSkipInstsMap.find(MBB);
1616344a3780SDimitry Andric       if (MapIt == BBSkipInstsMap.end())
1617344a3780SDimitry Andric         BeginIt = MBB->begin();
1618344a3780SDimitry Andric       else
1619344a3780SDimitry Andric         BeginIt = std::next(MapIt->second);
1620344a3780SDimitry Andric       auto I = MBB->SkipPHIsLabelsAndDebug(BeginIt);
1621344a3780SDimitry Andric       if (I != BeginIt)
1622344a3780SDimitry Andric         BBSkipInstsMap[MBB] = std::prev(I);
1623cf099d11SDimitry Andric       return I;
1624cf099d11SDimitry Andric     }
1625cf099d11SDimitry Andric     Idx = Idx.getPrevIndex();
1626cf099d11SDimitry Andric   }
1627cf099d11SDimitry Andric 
1628cf099d11SDimitry Andric   // Don't insert anything after the first terminator, though.
162963faed5bSDimitry Andric   return MI->isTerminator() ? MBB->getFirstTerminator() :
16305ca98fd9SDimitry Andric                               std::next(MachineBasicBlock::iterator(MI));
1631cf099d11SDimitry Andric }
1632cf099d11SDimitry Andric 
1633044eb2f6SDimitry Andric /// Find an iterator for inserting the next DBG_VALUE instruction
1634044eb2f6SDimitry Andric /// (or end if no more insert locations found).
1635044eb2f6SDimitry Andric static MachineBasicBlock::iterator
findNextInsertLocation(MachineBasicBlock * MBB,MachineBasicBlock::iterator I,SlotIndex StopIdx,ArrayRef<MachineOperand> LocMOs,LiveIntervals & LIS,const TargetRegisterInfo & TRI)1636344a3780SDimitry Andric findNextInsertLocation(MachineBasicBlock *MBB, MachineBasicBlock::iterator I,
1637344a3780SDimitry Andric                        SlotIndex StopIdx, ArrayRef<MachineOperand> LocMOs,
1638344a3780SDimitry Andric                        LiveIntervals &LIS, const TargetRegisterInfo &TRI) {
1639344a3780SDimitry Andric   SmallVector<Register, 4> Regs;
1640344a3780SDimitry Andric   for (const MachineOperand &LocMO : LocMOs)
1641344a3780SDimitry Andric     if (LocMO.isReg())
1642344a3780SDimitry Andric       Regs.push_back(LocMO.getReg());
1643344a3780SDimitry Andric   if (Regs.empty())
1644044eb2f6SDimitry Andric     return MBB->instr_end();
1645044eb2f6SDimitry Andric 
1646044eb2f6SDimitry Andric   // Find the next instruction in the MBB that define the register Reg.
1647eb11fae6SDimitry Andric   while (I != MBB->end() && !I->isTerminator()) {
1648044eb2f6SDimitry Andric     if (!LIS.isNotInMIMap(*I) &&
1649044eb2f6SDimitry Andric         SlotIndex::isEarlierEqualInstr(StopIdx, LIS.getInstructionIndex(*I)))
1650044eb2f6SDimitry Andric       break;
1651344a3780SDimitry Andric     if (any_of(Regs, [&I, &TRI](Register &Reg) {
1652344a3780SDimitry Andric           return I->definesRegister(Reg, &TRI);
1653344a3780SDimitry Andric         }))
1654044eb2f6SDimitry Andric       // The insert location is directly after the instruction/bundle.
1655044eb2f6SDimitry Andric       return std::next(I);
1656044eb2f6SDimitry Andric     ++I;
1657044eb2f6SDimitry Andric   }
1658044eb2f6SDimitry Andric   return MBB->end();
1659044eb2f6SDimitry Andric }
1660044eb2f6SDimitry Andric 
insertDebugValue(MachineBasicBlock * MBB,SlotIndex StartIdx,SlotIndex StopIdx,DbgVariableValue DbgValue,ArrayRef<bool> LocSpills,ArrayRef<unsigned> SpillOffsets,LiveIntervals & LIS,const TargetInstrInfo & TII,const TargetRegisterInfo & TRI,BlockSkipInstsMap & BBSkipInstsMap)1661044eb2f6SDimitry Andric void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
1662cfca06d7SDimitry Andric                                  SlotIndex StopIdx, DbgVariableValue DbgValue,
1663344a3780SDimitry Andric                                  ArrayRef<bool> LocSpills,
1664344a3780SDimitry Andric                                  ArrayRef<unsigned> SpillOffsets,
1665d8e91e46SDimitry Andric                                  LiveIntervals &LIS, const TargetInstrInfo &TII,
1666344a3780SDimitry Andric                                  const TargetRegisterInfo &TRI,
1667344a3780SDimitry Andric                                  BlockSkipInstsMap &BBSkipInstsMap) {
1668044eb2f6SDimitry Andric   SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB);
1669044eb2f6SDimitry Andric   // Only search within the current MBB.
1670044eb2f6SDimitry Andric   StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx;
1671344a3780SDimitry Andric   MachineBasicBlock::iterator I =
1672344a3780SDimitry Andric       findInsertLocation(MBB, StartIdx, LIS, BBSkipInstsMap);
1673eb11fae6SDimitry Andric   // Undef values don't exist in locations so create new "noreg" register MOs
1674eb11fae6SDimitry Andric   // for them. See getLocationNo().
1675344a3780SDimitry Andric   SmallVector<MachineOperand, 8> MOs;
1676344a3780SDimitry Andric   if (DbgValue.isUndef()) {
1677344a3780SDimitry Andric     MOs.assign(DbgValue.loc_nos().size(),
1678344a3780SDimitry Andric                MachineOperand::CreateReg(
1679cfca06d7SDimitry Andric                    /* Reg */ 0, /* isDef */ false, /* isImp */ false,
1680eb11fae6SDimitry Andric                    /* isKill */ false, /* isDead */ false,
1681eb11fae6SDimitry Andric                    /* isUndef */ false, /* isEarlyClobber */ false,
1682344a3780SDimitry Andric                    /* SubReg */ 0, /* isDebug */ true));
1683344a3780SDimitry Andric   } else {
1684344a3780SDimitry Andric     for (unsigned LocNo : DbgValue.loc_nos())
1685344a3780SDimitry Andric       MOs.push_back(locations[LocNo]);
1686344a3780SDimitry Andric   }
1687eb11fae6SDimitry Andric 
168830815c53SDimitry Andric   ++NumInsertedDebugValues;
1689cf099d11SDimitry Andric 
16905a5ac124SDimitry Andric   assert(cast<DILocalVariable>(Variable)
16915a5ac124SDimitry Andric              ->isValidLocationForIntrinsic(getDebugLoc()) &&
16925a5ac124SDimitry Andric          "Expected inlined-at fields to agree");
1693044eb2f6SDimitry Andric 
1694044eb2f6SDimitry Andric   // If the location was spilled, the new DBG_VALUE will be indirect. If the
1695044eb2f6SDimitry Andric   // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
1696d8e91e46SDimitry Andric   // that the original virtual register was a pointer. Also, add the stack slot
1697d8e91e46SDimitry Andric   // offset for the spilled register to the expression.
1698cfca06d7SDimitry Andric   const DIExpression *Expr = DbgValue.getExpression();
1699cfca06d7SDimitry Andric   bool IsIndirect = DbgValue.getWasIndirect();
1700344a3780SDimitry Andric   bool IsList = DbgValue.getWasList();
1701344a3780SDimitry Andric   for (unsigned I = 0, E = LocSpills.size(); I != E; ++I) {
1702344a3780SDimitry Andric     if (LocSpills[I]) {
1703344a3780SDimitry Andric       if (!IsList) {
1704344a3780SDimitry Andric         uint8_t DIExprFlags = DIExpression::ApplyOffset;
1705cfca06d7SDimitry Andric         if (IsIndirect)
1706cfca06d7SDimitry Andric           DIExprFlags |= DIExpression::DerefAfter;
1707344a3780SDimitry Andric         Expr = DIExpression::prepend(Expr, DIExprFlags, SpillOffsets[I]);
1708cfca06d7SDimitry Andric         IsIndirect = true;
1709344a3780SDimitry Andric       } else {
1710344a3780SDimitry Andric         SmallVector<uint64_t, 4> Ops;
1711344a3780SDimitry Andric         DIExpression::appendOffset(Ops, SpillOffsets[I]);
1712344a3780SDimitry Andric         Ops.push_back(dwarf::DW_OP_deref);
1713344a3780SDimitry Andric         Expr = DIExpression::appendOpsToArg(Expr, Ops, I);
1714344a3780SDimitry Andric       }
1715cfca06d7SDimitry Andric     }
1716044eb2f6SDimitry Andric 
1717344a3780SDimitry Andric     assert((!LocSpills[I] || MOs[I].isFI()) &&
1718344a3780SDimitry Andric            "a spilled location must be a frame index");
1719344a3780SDimitry Andric   }
1720044eb2f6SDimitry Andric 
1721344a3780SDimitry Andric   unsigned DbgValueOpcode =
1722344a3780SDimitry Andric       IsList ? TargetOpcode::DBG_VALUE_LIST : TargetOpcode::DBG_VALUE;
1723044eb2f6SDimitry Andric   do {
1724344a3780SDimitry Andric     BuildMI(*MBB, I, getDebugLoc(), TII.get(DbgValueOpcode), IsIndirect, MOs,
1725344a3780SDimitry Andric             Variable, Expr);
1726044eb2f6SDimitry Andric 
1727344a3780SDimitry Andric     // Continue and insert DBG_VALUES after every redefinition of a register
1728044eb2f6SDimitry Andric     // associated with the debug value within the range
1729344a3780SDimitry Andric     I = findNextInsertLocation(MBB, I, StopIdx, MOs, LIS, TRI);
1730044eb2f6SDimitry Andric   } while (I != MBB->end());
1731cf099d11SDimitry Andric }
1732cf099d11SDimitry Andric 
insertDebugLabel(MachineBasicBlock * MBB,SlotIndex Idx,LiveIntervals & LIS,const TargetInstrInfo & TII,BlockSkipInstsMap & BBSkipInstsMap)1733e6d15924SDimitry Andric void UserLabel::insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
1734344a3780SDimitry Andric                                  LiveIntervals &LIS, const TargetInstrInfo &TII,
1735344a3780SDimitry Andric                                  BlockSkipInstsMap &BBSkipInstsMap) {
1736344a3780SDimitry Andric   MachineBasicBlock::iterator I =
1737344a3780SDimitry Andric       findInsertLocation(MBB, Idx, LIS, BBSkipInstsMap);
1738e6d15924SDimitry Andric   ++NumInsertedDebugLabels;
1739e6d15924SDimitry Andric   BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_LABEL))
1740e6d15924SDimitry Andric       .addMetadata(Label);
1741e6d15924SDimitry Andric }
1742e6d15924SDimitry Andric 
emitDebugValues(VirtRegMap * VRM,LiveIntervals & LIS,const TargetInstrInfo & TII,const TargetRegisterInfo & TRI,const SpillOffsetMap & SpillOffsets,BlockSkipInstsMap & BBSkipInstsMap)1743cf099d11SDimitry Andric void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
1744044eb2f6SDimitry Andric                                 const TargetInstrInfo &TII,
1745044eb2f6SDimitry Andric                                 const TargetRegisterInfo &TRI,
1746344a3780SDimitry Andric                                 const SpillOffsetMap &SpillOffsets,
1747344a3780SDimitry Andric                                 BlockSkipInstsMap &BBSkipInstsMap) {
1748cf099d11SDimitry Andric   MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
1749cf099d11SDimitry Andric 
1750cf099d11SDimitry Andric   for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
1751cf099d11SDimitry Andric     SlotIndex Start = I.start();
1752cf099d11SDimitry Andric     SlotIndex Stop = I.stop();
1753cfca06d7SDimitry Andric     DbgVariableValue DbgValue = I.value();
1754344a3780SDimitry Andric 
1755344a3780SDimitry Andric     SmallVector<bool> SpilledLocs;
1756344a3780SDimitry Andric     SmallVector<unsigned> LocSpillOffsets;
1757344a3780SDimitry Andric     for (unsigned LocNo : DbgValue.loc_nos()) {
1758344a3780SDimitry Andric       auto SpillIt =
1759344a3780SDimitry Andric           !DbgValue.isUndef() ? SpillOffsets.find(LocNo) : SpillOffsets.end();
1760d8e91e46SDimitry Andric       bool Spilled = SpillIt != SpillOffsets.end();
1761344a3780SDimitry Andric       SpilledLocs.push_back(Spilled);
1762344a3780SDimitry Andric       LocSpillOffsets.push_back(Spilled ? SpillIt->second : 0);
1763344a3780SDimitry Andric     }
1764044eb2f6SDimitry Andric 
1765cfca06d7SDimitry Andric     // If the interval start was trimmed to the lexical scope insert the
1766cfca06d7SDimitry Andric     // DBG_VALUE at the previous index (otherwise it appears after the
1767cfca06d7SDimitry Andric     // first instruction in the range).
1768cfca06d7SDimitry Andric     if (trimmedDefs.count(Start))
1769cfca06d7SDimitry Andric       Start = Start.getPrevIndex();
1770cfca06d7SDimitry Andric 
1771344a3780SDimitry Andric     LLVM_DEBUG(auto &dbg = dbgs(); dbg << "\t[" << Start << ';' << Stop << "):";
1772344a3780SDimitry Andric                DbgValue.printLocNos(dbg));
1773dd58ef01SDimitry Andric     MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
1774dd58ef01SDimitry Andric     SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
1775cf099d11SDimitry Andric 
1776eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1777344a3780SDimitry Andric     insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs, LocSpillOffsets,
1778344a3780SDimitry Andric                      LIS, TII, TRI, BBSkipInstsMap);
1779cf099d11SDimitry Andric     // This interval may span multiple basic blocks.
1780cf099d11SDimitry Andric     // Insert a DBG_VALUE into each one.
1781cf099d11SDimitry Andric     while (Stop > MBBEnd) {
1782cf099d11SDimitry Andric       // Move to the next block.
1783cf099d11SDimitry Andric       Start = MBBEnd;
1784cf099d11SDimitry Andric       if (++MBB == MFEnd)
1785cf099d11SDimitry Andric         break;
1786dd58ef01SDimitry Andric       MBBEnd = LIS.getMBBEndIdx(&*MBB);
1787eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1788344a3780SDimitry Andric       insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs,
1789344a3780SDimitry Andric                        LocSpillOffsets, LIS, TII, TRI, BBSkipInstsMap);
1790cf099d11SDimitry Andric     }
1791eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << '\n');
1792cf099d11SDimitry Andric     if (MBB == MFEnd)
1793cf099d11SDimitry Andric       break;
1794cf099d11SDimitry Andric 
1795cf099d11SDimitry Andric     ++I;
1796cf099d11SDimitry Andric   }
1797cf099d11SDimitry Andric }
1798cf099d11SDimitry Andric 
emitDebugLabel(LiveIntervals & LIS,const TargetInstrInfo & TII,BlockSkipInstsMap & BBSkipInstsMap)1799344a3780SDimitry Andric void UserLabel::emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
1800344a3780SDimitry Andric                                BlockSkipInstsMap &BBSkipInstsMap) {
1801e6d15924SDimitry Andric   LLVM_DEBUG(dbgs() << "\t" << loc);
1802e6d15924SDimitry Andric   MachineFunction::iterator MBB = LIS.getMBBFromIndex(loc)->getIterator();
1803e6d15924SDimitry Andric 
1804e6d15924SDimitry Andric   LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB));
1805344a3780SDimitry Andric   insertDebugLabel(&*MBB, loc, LIS, TII, BBSkipInstsMap);
1806e6d15924SDimitry Andric 
1807e6d15924SDimitry Andric   LLVM_DEBUG(dbgs() << '\n');
1808e6d15924SDimitry Andric }
1809e6d15924SDimitry Andric 
emitDebugValues(VirtRegMap * VRM)1810cf099d11SDimitry Andric void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
1811eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
181267c32a98SDimitry Andric   if (!MF)
181367c32a98SDimitry Andric     return;
1814344a3780SDimitry Andric 
1815344a3780SDimitry Andric   BlockSkipInstsMap BBSkipInstsMap;
181667c32a98SDimitry Andric   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1817d8e91e46SDimitry Andric   SpillOffsetMap SpillOffsets;
1818e6d15924SDimitry Andric   for (auto &userValue : userValues) {
1819e6d15924SDimitry Andric     LLVM_DEBUG(userValue->print(dbgs(), TRI));
1820e6d15924SDimitry Andric     userValue->rewriteLocations(*VRM, *MF, *TII, *TRI, SpillOffsets);
1821344a3780SDimitry Andric     userValue->emitDebugValues(VRM, *LIS, *TII, *TRI, SpillOffsets,
1822344a3780SDimitry Andric                                BBSkipInstsMap);
1823e6d15924SDimitry Andric   }
1824e6d15924SDimitry Andric   LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG LABELS **********\n");
1825e6d15924SDimitry Andric   for (auto &userLabel : userLabels) {
1826e6d15924SDimitry Andric     LLVM_DEBUG(userLabel->print(dbgs(), TRI));
1827344a3780SDimitry Andric     userLabel->emitDebugLabel(*LIS, *TII, BBSkipInstsMap);
1828cf099d11SDimitry Andric   }
1829b60736ecSDimitry Andric 
1830344a3780SDimitry Andric   LLVM_DEBUG(dbgs() << "********** EMITTING DEBUG PHIS **********\n");
1831344a3780SDimitry Andric 
1832344a3780SDimitry Andric   auto Slots = LIS->getSlotIndexes();
1833344a3780SDimitry Andric   for (auto &It : PHIValToPos) {
1834344a3780SDimitry Andric     // For each ex-PHI, identify its physreg location or stack slot, and emit
1835344a3780SDimitry Andric     // a DBG_PHI for it.
1836344a3780SDimitry Andric     unsigned InstNum = It.first;
1837344a3780SDimitry Andric     auto Slot = It.second.SI;
1838344a3780SDimitry Andric     Register Reg = It.second.Reg;
1839344a3780SDimitry Andric     unsigned SubReg = It.second.SubReg;
1840344a3780SDimitry Andric 
1841344a3780SDimitry Andric     MachineBasicBlock *OrigMBB = Slots->getMBBFromIndex(Slot);
1842344a3780SDimitry Andric     if (VRM->isAssignedReg(Reg) &&
1843344a3780SDimitry Andric         Register::isPhysicalRegister(VRM->getPhys(Reg))) {
1844344a3780SDimitry Andric       unsigned PhysReg = VRM->getPhys(Reg);
1845344a3780SDimitry Andric       if (SubReg != 0)
1846344a3780SDimitry Andric         PhysReg = TRI->getSubReg(PhysReg, SubReg);
1847344a3780SDimitry Andric 
1848344a3780SDimitry Andric       auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(),
1849344a3780SDimitry Andric                              TII->get(TargetOpcode::DBG_PHI));
1850344a3780SDimitry Andric       Builder.addReg(PhysReg);
1851344a3780SDimitry Andric       Builder.addImm(InstNum);
1852344a3780SDimitry Andric     } else if (VRM->getStackSlot(Reg) != VirtRegMap::NO_STACK_SLOT) {
1853344a3780SDimitry Andric       const MachineRegisterInfo &MRI = MF->getRegInfo();
1854344a3780SDimitry Andric       const TargetRegisterClass *TRC = MRI.getRegClass(Reg);
1855344a3780SDimitry Andric       unsigned SpillSize, SpillOffset;
1856344a3780SDimitry Andric 
1857145449b1SDimitry Andric       unsigned regSizeInBits = TRI->getRegSizeInBits(*TRC);
1858145449b1SDimitry Andric       if (SubReg)
1859145449b1SDimitry Andric         regSizeInBits = TRI->getSubRegIdxSize(SubReg);
1860145449b1SDimitry Andric 
1861145449b1SDimitry Andric       // Test whether this location is legal with the given subreg. If the
1862145449b1SDimitry Andric       // subregister has a nonzero offset, drop this location, it's too complex
1863145449b1SDimitry Andric       // to describe. (TODO: future work).
1864344a3780SDimitry Andric       bool Success =
1865344a3780SDimitry Andric           TII->getStackSlotRange(TRC, SubReg, SpillSize, SpillOffset, *MF);
1866344a3780SDimitry Andric 
1867145449b1SDimitry Andric       if (Success && SpillOffset == 0) {
1868344a3780SDimitry Andric         auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(),
1869344a3780SDimitry Andric                                TII->get(TargetOpcode::DBG_PHI));
1870344a3780SDimitry Andric         Builder.addFrameIndex(VRM->getStackSlot(Reg));
1871344a3780SDimitry Andric         Builder.addImm(InstNum);
1872145449b1SDimitry Andric         // Record how large the original value is. The stack slot might be
1873145449b1SDimitry Andric         // merged and altered during optimisation, but we will want to know how
1874145449b1SDimitry Andric         // large the value is, at this DBG_PHI.
1875145449b1SDimitry Andric         Builder.addImm(regSizeInBits);
1876344a3780SDimitry Andric       }
1877145449b1SDimitry Andric 
1878145449b1SDimitry Andric       LLVM_DEBUG(
1879145449b1SDimitry Andric       if (SpillOffset != 0) {
1880145449b1SDimitry Andric         dbgs() << "DBG_PHI for Vreg " << Reg << " subreg " << SubReg <<
1881145449b1SDimitry Andric                   " has nonzero offset\n";
1882145449b1SDimitry Andric       }
1883145449b1SDimitry Andric       );
1884344a3780SDimitry Andric     }
1885344a3780SDimitry Andric     // If there was no mapping for a value ID, it's optimized out. Create no
1886344a3780SDimitry Andric     // DBG_PHI, and any variables using this value will become optimized out.
1887344a3780SDimitry Andric   }
1888344a3780SDimitry Andric   MF->DebugPHIPositions.clear();
1889344a3780SDimitry Andric 
1890b60736ecSDimitry Andric   LLVM_DEBUG(dbgs() << "********** EMITTING INSTR REFERENCES **********\n");
1891b60736ecSDimitry Andric 
1892f65dcba8SDimitry Andric   // Re-insert any debug instrs back in the position they were. We must
1893f65dcba8SDimitry Andric   // re-insert in the same order to ensure that debug instructions don't swap,
1894f65dcba8SDimitry Andric   // which could re-order assignments. Do so in a batch -- once we find the
1895f65dcba8SDimitry Andric   // insert position, insert all instructions at the same SlotIdx. They are
1896f65dcba8SDimitry Andric   // guaranteed to appear in-sequence in StashedDebugInstrs because we insert
1897f65dcba8SDimitry Andric   // them in order.
18984b4fe385SDimitry Andric   for (auto *StashIt = StashedDebugInstrs.begin();
1899f65dcba8SDimitry Andric        StashIt != StashedDebugInstrs.end(); ++StashIt) {
1900f65dcba8SDimitry Andric     SlotIndex Idx = StashIt->Idx;
1901f65dcba8SDimitry Andric     MachineBasicBlock *MBB = StashIt->MBB;
1902f65dcba8SDimitry Andric     MachineInstr *MI = StashIt->MI;
1903f65dcba8SDimitry Andric 
1904f65dcba8SDimitry Andric     auto EmitInstsHere = [this, &StashIt, MBB, Idx,
1905f65dcba8SDimitry Andric                           MI](MachineBasicBlock::iterator InsertPos) {
1906f65dcba8SDimitry Andric       // Insert this debug instruction.
1907f65dcba8SDimitry Andric       MBB->insert(InsertPos, MI);
1908f65dcba8SDimitry Andric 
1909f65dcba8SDimitry Andric       // Look at subsequent stashed debug instructions: if they're at the same
1910f65dcba8SDimitry Andric       // index, insert those too.
1911f65dcba8SDimitry Andric       auto NextItem = std::next(StashIt);
1912f65dcba8SDimitry Andric       while (NextItem != StashedDebugInstrs.end() && NextItem->Idx == Idx) {
1913f65dcba8SDimitry Andric         assert(NextItem->MBB == MBB && "Instrs with same slot index should be"
1914f65dcba8SDimitry Andric                "in the same block");
1915f65dcba8SDimitry Andric         MBB->insert(InsertPos, NextItem->MI);
1916f65dcba8SDimitry Andric         StashIt = NextItem;
1917f65dcba8SDimitry Andric         NextItem = std::next(StashIt);
1918f65dcba8SDimitry Andric       };
1919f65dcba8SDimitry Andric     };
1920344a3780SDimitry Andric 
1921344a3780SDimitry Andric     // Start block index: find the first non-debug instr in the block, and
1922344a3780SDimitry Andric     // insert before it.
1923f65dcba8SDimitry Andric     if (Idx == Slots->getMBBStartIdx(MBB)) {
1924344a3780SDimitry Andric       MachineBasicBlock::iterator InsertPos =
1925f65dcba8SDimitry Andric           findInsertLocation(MBB, Idx, *LIS, BBSkipInstsMap);
1926f65dcba8SDimitry Andric       EmitInstsHere(InsertPos);
1927344a3780SDimitry Andric       continue;
1928344a3780SDimitry Andric     }
1929344a3780SDimitry Andric 
1930344a3780SDimitry Andric     if (MachineInstr *Pos = Slots->getInstructionFromIndex(Idx)) {
1931344a3780SDimitry Andric       // Insert at the end of any debug instructions.
1932344a3780SDimitry Andric       auto PostDebug = std::next(Pos->getIterator());
1933f65dcba8SDimitry Andric       PostDebug = skipDebugInstructionsForward(PostDebug, MBB->instr_end());
1934f65dcba8SDimitry Andric       EmitInstsHere(PostDebug);
1935344a3780SDimitry Andric     } else {
1936344a3780SDimitry Andric       // Insert position disappeared; walk forwards through slots until we
1937344a3780SDimitry Andric       // find a new one.
1938f65dcba8SDimitry Andric       SlotIndex End = Slots->getMBBEndIdx(MBB);
1939344a3780SDimitry Andric       for (; Idx < End; Idx = Slots->getNextNonNullIndex(Idx)) {
1940344a3780SDimitry Andric         Pos = Slots->getInstructionFromIndex(Idx);
1941344a3780SDimitry Andric         if (Pos) {
1942f65dcba8SDimitry Andric           EmitInstsHere(Pos->getIterator());
1943344a3780SDimitry Andric           break;
1944344a3780SDimitry Andric         }
1945344a3780SDimitry Andric       }
1946344a3780SDimitry Andric 
1947344a3780SDimitry Andric       // We have reached the end of the block and didn't find anywhere to
1948344a3780SDimitry Andric       // insert! It's not safe to discard any debug instructions; place them
1949344a3780SDimitry Andric       // in front of the first terminator, or in front of end().
1950344a3780SDimitry Andric       if (Idx >= End) {
1951f65dcba8SDimitry Andric         auto TermIt = MBB->getFirstTerminator();
1952f65dcba8SDimitry Andric         EmitInstsHere(TermIt);
1953344a3780SDimitry Andric       }
1954b60736ecSDimitry Andric     }
1955b60736ecSDimitry Andric   }
1956b60736ecSDimitry Andric 
19574a16efa3SDimitry Andric   EmitDone = true;
1958344a3780SDimitry Andric   BBSkipInstsMap.clear();
1959cf099d11SDimitry Andric }
1960cf099d11SDimitry Andric 
emitDebugValues(VirtRegMap * VRM)1961cf099d11SDimitry Andric void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
1962cf099d11SDimitry Andric   if (pImpl)
1963cf099d11SDimitry Andric     static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
1964cf099d11SDimitry Andric }
1965cf099d11SDimitry Andric 
196671d5a254SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const196708bbd35aSDimitry Andric LLVM_DUMP_METHOD void LiveDebugVariables::dump() const {
1968cf099d11SDimitry Andric   if (pImpl)
1969cf099d11SDimitry Andric     static_cast<LDVImpl*>(pImpl)->print(dbgs());
1970cf099d11SDimitry Andric }
1971cf099d11SDimitry Andric #endif
1972