10b57cec5SDimitry Andric //===- LiveDebugVariables.cpp - Tracking debug info variables -------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the LiveDebugVariables analysis.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric // Remove all DBG_VALUE instructions referencing virtual registers and replace
120b57cec5SDimitry Andric // them with a data structure tracking where live user variables are kept - in a
130b57cec5SDimitry Andric // virtual register or in a stack slot.
140b57cec5SDimitry Andric //
150b57cec5SDimitry Andric // Allow the data structure to be updated during register allocation when values
160b57cec5SDimitry Andric // are moved between registers and stack slots. Finally emit new DBG_VALUE
170b57cec5SDimitry Andric // instructions after register allocation is complete.
180b57cec5SDimitry Andric //
190b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
200b57cec5SDimitry Andric 
210b57cec5SDimitry Andric #include "LiveDebugVariables.h"
220b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
230b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
240b57cec5SDimitry Andric #include "llvm/ADT/IntervalMap.h"
250b57cec5SDimitry Andric #include "llvm/ADT/MapVector.h"
260b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
270b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
280b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
290b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
300b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
3181ad6265SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
320b57cec5SDimitry Andric #include "llvm/CodeGen/LexicalScopes.h"
330b57cec5SDimitry Andric #include "llvm/CodeGen/LiveInterval.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
350b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
360b57cec5SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
370b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
380b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
390b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
400b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
410b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
420b57cec5SDimitry Andric #include "llvm/CodeGen/SlotIndexes.h"
430b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
440b57cec5SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
450b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
460b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
470b57cec5SDimitry Andric #include "llvm/CodeGen/VirtRegMap.h"
480b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
490b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
500b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
510b57cec5SDimitry Andric #include "llvm/IR/Function.h"
52480093f4SDimitry Andric #include "llvm/InitializePasses.h"
530b57cec5SDimitry Andric #include "llvm/Pass.h"
540b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
550b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
560b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
570b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
580b57cec5SDimitry Andric #include <algorithm>
590b57cec5SDimitry Andric #include <cassert>
600b57cec5SDimitry Andric #include <iterator>
615f757f3fSDimitry Andric #include <map>
620b57cec5SDimitry Andric #include <memory>
63bdd1243dSDimitry Andric #include <optional>
640b57cec5SDimitry Andric #include <utility>
650b57cec5SDimitry Andric 
660b57cec5SDimitry Andric using namespace llvm;
670b57cec5SDimitry Andric 
680b57cec5SDimitry Andric #define DEBUG_TYPE "livedebugvars"
690b57cec5SDimitry Andric 
700b57cec5SDimitry Andric static cl::opt<bool>
710b57cec5SDimitry Andric EnableLDV("live-debug-variables", cl::init(true),
720b57cec5SDimitry Andric           cl::desc("Enable the live debug variables pass"), cl::Hidden);
730b57cec5SDimitry Andric 
740b57cec5SDimitry Andric STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
750b57cec5SDimitry Andric STATISTIC(NumInsertedDebugLabels, "Number of DBG_LABELs inserted");
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric char LiveDebugVariables::ID = 0;
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE,
800b57cec5SDimitry Andric                 "Debug Variable Analysis", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)810b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
820b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
830b57cec5SDimitry Andric INITIALIZE_PASS_END(LiveDebugVariables, DEBUG_TYPE,
840b57cec5SDimitry Andric                 "Debug Variable Analysis", false, false)
850b57cec5SDimitry Andric 
860b57cec5SDimitry Andric void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
870b57cec5SDimitry Andric   AU.addRequired<MachineDominatorTree>();
880b57cec5SDimitry Andric   AU.addRequiredTransitive<LiveIntervals>();
890b57cec5SDimitry Andric   AU.setPreservesAll();
900b57cec5SDimitry Andric   MachineFunctionPass::getAnalysisUsage(AU);
910b57cec5SDimitry Andric }
920b57cec5SDimitry Andric 
LiveDebugVariables()930b57cec5SDimitry Andric LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID) {
940b57cec5SDimitry Andric   initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
950b57cec5SDimitry Andric }
960b57cec5SDimitry Andric 
970b57cec5SDimitry Andric enum : unsigned { UndefLocNo = ~0U };
980b57cec5SDimitry Andric 
99e8d8bef9SDimitry Andric namespace {
1005ffd83dbSDimitry Andric /// Describes a debug variable value by location number and expression along
1015ffd83dbSDimitry Andric /// with some flags about the original usage of the location.
1025ffd83dbSDimitry Andric class DbgVariableValue {
1030b57cec5SDimitry Andric public:
DbgVariableValue(ArrayRef<unsigned> NewLocs,bool WasIndirect,bool WasList,const DIExpression & Expr)104fe6060f1SDimitry Andric   DbgVariableValue(ArrayRef<unsigned> NewLocs, bool WasIndirect, bool WasList,
105fe6060f1SDimitry Andric                    const DIExpression &Expr)
106fe6060f1SDimitry Andric       : WasIndirect(WasIndirect), WasList(WasList), Expression(&Expr) {
107fe6060f1SDimitry Andric     assert(!(WasIndirect && WasList) &&
108fe6060f1SDimitry Andric            "DBG_VALUE_LISTs should not be indirect.");
109fe6060f1SDimitry Andric     SmallVector<unsigned> LocNoVec;
110fe6060f1SDimitry Andric     for (unsigned LocNo : NewLocs) {
111fe6060f1SDimitry Andric       auto It = find(LocNoVec, LocNo);
112fe6060f1SDimitry Andric       if (It == LocNoVec.end())
113fe6060f1SDimitry Andric         LocNoVec.push_back(LocNo);
114fe6060f1SDimitry Andric       else {
115fe6060f1SDimitry Andric         // Loc duplicates an element in LocNos; replace references to Op
116fe6060f1SDimitry Andric         // with references to the duplicating element.
117fe6060f1SDimitry Andric         unsigned OpIdx = LocNoVec.size();
118fe6060f1SDimitry Andric         unsigned DuplicatingIdx = std::distance(LocNoVec.begin(), It);
119fe6060f1SDimitry Andric         Expression =
120fe6060f1SDimitry Andric             DIExpression::replaceArg(Expression, OpIdx, DuplicatingIdx);
121fe6060f1SDimitry Andric       }
122fe6060f1SDimitry Andric     }
123fe6060f1SDimitry Andric     // FIXME: Debug values referencing 64+ unique machine locations are rare and
124fe6060f1SDimitry Andric     // currently unsupported for performance reasons. If we can verify that
125fe6060f1SDimitry Andric     // performance is acceptable for such debug values, we can increase the
126fe6060f1SDimitry Andric     // bit-width of LocNoCount to 14 to enable up to 16384 unique machine
127fe6060f1SDimitry Andric     // locations. We will also need to verify that this does not cause issues
128fe6060f1SDimitry Andric     // with LiveDebugVariables' use of IntervalMap.
129fe6060f1SDimitry Andric     if (LocNoVec.size() < 64) {
130fe6060f1SDimitry Andric       LocNoCount = LocNoVec.size();
131fe6060f1SDimitry Andric       if (LocNoCount > 0) {
132fe6060f1SDimitry Andric         LocNos = std::make_unique<unsigned[]>(LocNoCount);
133fe6060f1SDimitry Andric         std::copy(LocNoVec.begin(), LocNoVec.end(), loc_nos_begin());
134fe6060f1SDimitry Andric       }
135fe6060f1SDimitry Andric     } else {
136fe6060f1SDimitry Andric       LLVM_DEBUG(dbgs() << "Found debug value with 64+ unique machine "
137fe6060f1SDimitry Andric                            "locations, dropping...\n");
138fe6060f1SDimitry Andric       LocNoCount = 1;
139fe6060f1SDimitry Andric       // Turn this into an undef debug value list; right now, the simplest form
140fe6060f1SDimitry Andric       // of this is an expression with one arg, and an undef debug operand.
141fe6060f1SDimitry Andric       Expression =
142bdd1243dSDimitry Andric           DIExpression::get(Expr.getContext(), {dwarf::DW_OP_LLVM_arg, 0});
143fe6060f1SDimitry Andric       if (auto FragmentInfoOpt = Expr.getFragmentInfo())
144fe6060f1SDimitry Andric         Expression = *DIExpression::createFragmentExpression(
145fe6060f1SDimitry Andric             Expression, FragmentInfoOpt->OffsetInBits,
146fe6060f1SDimitry Andric             FragmentInfoOpt->SizeInBits);
147fe6060f1SDimitry Andric       LocNos = std::make_unique<unsigned[]>(LocNoCount);
148fe6060f1SDimitry Andric       LocNos[0] = UndefLocNo;
149fe6060f1SDimitry Andric     }
1500b57cec5SDimitry Andric   }
1510b57cec5SDimitry Andric 
DbgVariableValue()15204eeddc0SDimitry Andric   DbgVariableValue() : LocNoCount(0), WasIndirect(false), WasList(false) {}
DbgVariableValue(const DbgVariableValue & Other)153fe6060f1SDimitry Andric   DbgVariableValue(const DbgVariableValue &Other)
154fe6060f1SDimitry Andric       : LocNoCount(Other.LocNoCount), WasIndirect(Other.getWasIndirect()),
155fe6060f1SDimitry Andric         WasList(Other.getWasList()), Expression(Other.getExpression()) {
156fe6060f1SDimitry Andric     if (Other.getLocNoCount()) {
157fe6060f1SDimitry Andric       LocNos.reset(new unsigned[Other.getLocNoCount()]);
158fe6060f1SDimitry Andric       std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin());
159fe6060f1SDimitry Andric     }
160fe6060f1SDimitry Andric   }
161fe6060f1SDimitry Andric 
operator =(const DbgVariableValue & Other)162fe6060f1SDimitry Andric   DbgVariableValue &operator=(const DbgVariableValue &Other) {
163fe6060f1SDimitry Andric     if (this == &Other)
164fe6060f1SDimitry Andric       return *this;
165fe6060f1SDimitry Andric     if (Other.getLocNoCount()) {
166fe6060f1SDimitry Andric       LocNos.reset(new unsigned[Other.getLocNoCount()]);
167fe6060f1SDimitry Andric       std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin());
168fe6060f1SDimitry Andric     } else {
169fe6060f1SDimitry Andric       LocNos.release();
170fe6060f1SDimitry Andric     }
171fe6060f1SDimitry Andric     LocNoCount = Other.getLocNoCount();
172fe6060f1SDimitry Andric     WasIndirect = Other.getWasIndirect();
173fe6060f1SDimitry Andric     WasList = Other.getWasList();
174fe6060f1SDimitry Andric     Expression = Other.getExpression();
175fe6060f1SDimitry Andric     return *this;
176fe6060f1SDimitry Andric   }
1770b57cec5SDimitry Andric 
getExpression() const1785ffd83dbSDimitry Andric   const DIExpression *getExpression() const { return Expression; }
getLocNoCount() const179fe6060f1SDimitry Andric   uint8_t getLocNoCount() const { return LocNoCount; }
containsLocNo(unsigned LocNo) const180fe6060f1SDimitry Andric   bool containsLocNo(unsigned LocNo) const {
181fe6060f1SDimitry Andric     return is_contained(loc_nos(), LocNo);
1820b57cec5SDimitry Andric   }
getWasIndirect() const1835ffd83dbSDimitry Andric   bool getWasIndirect() const { return WasIndirect; }
getWasList() const184fe6060f1SDimitry Andric   bool getWasList() const { return WasList; }
isUndef() const185fe6060f1SDimitry Andric   bool isUndef() const { return LocNoCount == 0 || containsLocNo(UndefLocNo); }
1860b57cec5SDimitry Andric 
decrementLocNosAfterPivot(unsigned Pivot) const187fe6060f1SDimitry Andric   DbgVariableValue decrementLocNosAfterPivot(unsigned Pivot) const {
188fe6060f1SDimitry Andric     SmallVector<unsigned, 4> NewLocNos;
189fe6060f1SDimitry Andric     for (unsigned LocNo : loc_nos())
190fe6060f1SDimitry Andric       NewLocNos.push_back(LocNo != UndefLocNo && LocNo > Pivot ? LocNo - 1
191fe6060f1SDimitry Andric                                                                : LocNo);
192fe6060f1SDimitry Andric     return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
193fe6060f1SDimitry Andric   }
194fe6060f1SDimitry Andric 
remapLocNos(ArrayRef<unsigned> LocNoMap) const195fe6060f1SDimitry Andric   DbgVariableValue remapLocNos(ArrayRef<unsigned> LocNoMap) const {
196fe6060f1SDimitry Andric     SmallVector<unsigned> NewLocNos;
197fe6060f1SDimitry Andric     for (unsigned LocNo : loc_nos())
198fe6060f1SDimitry Andric       // Undef values don't exist in locations (and thus not in LocNoMap
199fe6060f1SDimitry Andric       // either) so skip over them. See getLocationNo().
200fe6060f1SDimitry Andric       NewLocNos.push_back(LocNo == UndefLocNo ? UndefLocNo : LocNoMap[LocNo]);
201fe6060f1SDimitry Andric     return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
202fe6060f1SDimitry Andric   }
203fe6060f1SDimitry Andric 
changeLocNo(unsigned OldLocNo,unsigned NewLocNo) const204fe6060f1SDimitry Andric   DbgVariableValue changeLocNo(unsigned OldLocNo, unsigned NewLocNo) const {
205fe6060f1SDimitry Andric     SmallVector<unsigned> NewLocNos;
206fe6060f1SDimitry Andric     NewLocNos.assign(loc_nos_begin(), loc_nos_end());
207fe6060f1SDimitry Andric     auto OldLocIt = find(NewLocNos, OldLocNo);
208fe6060f1SDimitry Andric     assert(OldLocIt != NewLocNos.end() && "Old location must be present.");
209fe6060f1SDimitry Andric     *OldLocIt = NewLocNo;
210fe6060f1SDimitry Andric     return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
211fe6060f1SDimitry Andric   }
212fe6060f1SDimitry Andric 
hasLocNoGreaterThan(unsigned LocNo) const213fe6060f1SDimitry Andric   bool hasLocNoGreaterThan(unsigned LocNo) const {
214fe6060f1SDimitry Andric     return any_of(loc_nos(),
215fe6060f1SDimitry Andric                   [LocNo](unsigned ThisLocNo) { return ThisLocNo > LocNo; });
216fe6060f1SDimitry Andric   }
217fe6060f1SDimitry Andric 
printLocNos(llvm::raw_ostream & OS) const218fe6060f1SDimitry Andric   void printLocNos(llvm::raw_ostream &OS) const {
219fe6060f1SDimitry Andric     for (const unsigned &Loc : loc_nos())
220fe6060f1SDimitry Andric       OS << (&Loc == loc_nos_begin() ? " " : ", ") << Loc;
2210b57cec5SDimitry Andric   }
2220b57cec5SDimitry Andric 
operator ==(const DbgVariableValue & LHS,const DbgVariableValue & RHS)2235ffd83dbSDimitry Andric   friend inline bool operator==(const DbgVariableValue &LHS,
2245ffd83dbSDimitry Andric                                 const DbgVariableValue &RHS) {
225fe6060f1SDimitry Andric     if (std::tie(LHS.LocNoCount, LHS.WasIndirect, LHS.WasList,
226fe6060f1SDimitry Andric                  LHS.Expression) !=
227fe6060f1SDimitry Andric         std::tie(RHS.LocNoCount, RHS.WasIndirect, RHS.WasList, RHS.Expression))
228fe6060f1SDimitry Andric       return false;
229fe6060f1SDimitry Andric     return std::equal(LHS.loc_nos_begin(), LHS.loc_nos_end(),
230fe6060f1SDimitry Andric                       RHS.loc_nos_begin());
2310b57cec5SDimitry Andric   }
2320b57cec5SDimitry Andric 
operator !=(const DbgVariableValue & LHS,const DbgVariableValue & RHS)2335ffd83dbSDimitry Andric   friend inline bool operator!=(const DbgVariableValue &LHS,
2345ffd83dbSDimitry Andric                                 const DbgVariableValue &RHS) {
2350b57cec5SDimitry Andric     return !(LHS == RHS);
2360b57cec5SDimitry Andric   }
2370b57cec5SDimitry Andric 
loc_nos_begin()238fe6060f1SDimitry Andric   unsigned *loc_nos_begin() { return LocNos.get(); }
loc_nos_begin() const239fe6060f1SDimitry Andric   const unsigned *loc_nos_begin() const { return LocNos.get(); }
loc_nos_end()240fe6060f1SDimitry Andric   unsigned *loc_nos_end() { return LocNos.get() + LocNoCount; }
loc_nos_end() const241fe6060f1SDimitry Andric   const unsigned *loc_nos_end() const { return LocNos.get() + LocNoCount; }
loc_nos() const242fe6060f1SDimitry Andric   ArrayRef<unsigned> loc_nos() const {
243fe6060f1SDimitry Andric     return ArrayRef<unsigned>(LocNos.get(), LocNoCount);
244fe6060f1SDimitry Andric   }
245fe6060f1SDimitry Andric 
2460b57cec5SDimitry Andric private:
247fe6060f1SDimitry Andric   // IntervalMap requires the value object to be very small, to the extent
248fe6060f1SDimitry Andric   // that we do not have enough room for an std::vector. Using a C-style array
249fe6060f1SDimitry Andric   // (with a unique_ptr wrapper for convenience) allows us to optimize for this
250fe6060f1SDimitry Andric   // specific case by packing the array size into only 6 bits (it is highly
251fe6060f1SDimitry Andric   // unlikely that any debug value will need 64+ locations).
252fe6060f1SDimitry Andric   std::unique_ptr<unsigned[]> LocNos;
253fe6060f1SDimitry Andric   uint8_t LocNoCount : 6;
254fe6060f1SDimitry Andric   bool WasIndirect : 1;
255fe6060f1SDimitry Andric   bool WasList : 1;
2565ffd83dbSDimitry Andric   const DIExpression *Expression = nullptr;
2570b57cec5SDimitry Andric };
258e8d8bef9SDimitry Andric } // namespace
2590b57cec5SDimitry Andric 
2605ffd83dbSDimitry Andric /// Map of where a user value is live to that value.
2615ffd83dbSDimitry Andric using LocMap = IntervalMap<SlotIndex, DbgVariableValue, 4>;
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric /// Map of stack slot offsets for spilled locations.
2640b57cec5SDimitry Andric /// Non-spilled locations are not added to the map.
2650b57cec5SDimitry Andric using SpillOffsetMap = DenseMap<unsigned, unsigned>;
2660b57cec5SDimitry Andric 
267fe6060f1SDimitry Andric /// Cache to save the location where it can be used as the starting
268fe6060f1SDimitry Andric /// position as input for calling MachineBasicBlock::SkipPHIsLabelsAndDebug.
269fe6060f1SDimitry Andric /// This is to prevent MachineBasicBlock::SkipPHIsLabelsAndDebug from
270fe6060f1SDimitry Andric /// repeatedly searching the same set of PHIs/Labels/Debug instructions
271fe6060f1SDimitry Andric /// if it is called many times for the same block.
272fe6060f1SDimitry Andric using BlockSkipInstsMap =
273fe6060f1SDimitry Andric     DenseMap<MachineBasicBlock *, MachineBasicBlock::iterator>;
274fe6060f1SDimitry Andric 
2750b57cec5SDimitry Andric namespace {
2760b57cec5SDimitry Andric 
2770b57cec5SDimitry Andric class LDVImpl;
2780b57cec5SDimitry Andric 
2790b57cec5SDimitry Andric /// A user value is a part of a debug info user variable.
2800b57cec5SDimitry Andric ///
2810b57cec5SDimitry Andric /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
2820b57cec5SDimitry Andric /// holds part of a user variable. The part is identified by a byte offset.
283480093f4SDimitry Andric ///
284480093f4SDimitry Andric /// UserValues are grouped into equivalence classes for easier searching. Two
2855ffd83dbSDimitry Andric /// user values are related if they are held by the same virtual register. The
2865ffd83dbSDimitry Andric /// equivalence class is the transitive closure of that relation.
2870b57cec5SDimitry Andric class UserValue {
2880b57cec5SDimitry Andric   const DILocalVariable *Variable; ///< The debug info variable we are part of.
2895ffd83dbSDimitry Andric   /// The part of the variable we describe.
290bdd1243dSDimitry Andric   const std::optional<DIExpression::FragmentInfo> Fragment;
2910b57cec5SDimitry Andric   DebugLoc dl;            ///< The debug location for the variable. This is
2920b57cec5SDimitry Andric                           ///< used by dwarf writer to find lexical scope.
293480093f4SDimitry Andric   UserValue *leader;      ///< Equivalence class leader.
294480093f4SDimitry Andric   UserValue *next = nullptr; ///< Next value in equivalence class, or null.
2950b57cec5SDimitry Andric 
2960b57cec5SDimitry Andric   /// Numbered locations referenced by locmap.
2970b57cec5SDimitry Andric   SmallVector<MachineOperand, 4> locations;
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric   /// Map of slot indices where this value is live.
3000b57cec5SDimitry Andric   LocMap locInts;
3010b57cec5SDimitry Andric 
30213138422SDimitry Andric   /// Set of interval start indexes that have been trimmed to the
30313138422SDimitry Andric   /// lexical scope.
30413138422SDimitry Andric   SmallSet<SlotIndex, 2> trimmedDefs;
30513138422SDimitry Andric 
3065ffd83dbSDimitry Andric   /// Insert a DBG_VALUE into MBB at Idx for DbgValue.
3070b57cec5SDimitry Andric   void insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
3085ffd83dbSDimitry Andric                         SlotIndex StopIdx, DbgVariableValue DbgValue,
309fe6060f1SDimitry Andric                         ArrayRef<bool> LocSpills,
310fe6060f1SDimitry Andric                         ArrayRef<unsigned> SpillOffsets, LiveIntervals &LIS,
3110b57cec5SDimitry Andric                         const TargetInstrInfo &TII,
312fe6060f1SDimitry Andric                         const TargetRegisterInfo &TRI,
313fe6060f1SDimitry Andric                         BlockSkipInstsMap &BBSkipInstsMap);
3140b57cec5SDimitry Andric 
3150b57cec5SDimitry Andric   /// Replace OldLocNo ranges with NewRegs ranges where NewRegs
3160b57cec5SDimitry Andric   /// is live. Returns true if any changes were made.
3175ffd83dbSDimitry Andric   bool splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs,
3180b57cec5SDimitry Andric                      LiveIntervals &LIS);
3190b57cec5SDimitry Andric 
3200b57cec5SDimitry Andric public:
3210b57cec5SDimitry Andric   /// Create a new UserValue.
UserValue(const DILocalVariable * var,std::optional<DIExpression::FragmentInfo> Fragment,DebugLoc L,LocMap::Allocator & alloc)3225ffd83dbSDimitry Andric   UserValue(const DILocalVariable *var,
323bdd1243dSDimitry Andric             std::optional<DIExpression::FragmentInfo> Fragment, DebugLoc L,
3240b57cec5SDimitry Andric             LocMap::Allocator &alloc)
3255ffd83dbSDimitry Andric       : Variable(var), Fragment(Fragment), dl(std::move(L)), leader(this),
326480093f4SDimitry Andric         locInts(alloc) {}
3270b57cec5SDimitry Andric 
328480093f4SDimitry Andric   /// Get the leader of this value's equivalence class.
getLeader()329480093f4SDimitry Andric   UserValue *getLeader() {
330480093f4SDimitry Andric     UserValue *l = leader;
331480093f4SDimitry Andric     while (l != l->leader)
332480093f4SDimitry Andric       l = l->leader;
333480093f4SDimitry Andric     return leader = l;
334480093f4SDimitry Andric   }
335480093f4SDimitry Andric 
336480093f4SDimitry Andric   /// Return the next UserValue in the equivalence class.
getNext() const337480093f4SDimitry Andric   UserValue *getNext() const { return next; }
338480093f4SDimitry Andric 
339480093f4SDimitry Andric   /// Merge equivalence classes.
merge(UserValue * L1,UserValue * L2)340480093f4SDimitry Andric   static UserValue *merge(UserValue *L1, UserValue *L2) {
341480093f4SDimitry Andric     L2 = L2->getLeader();
342480093f4SDimitry Andric     if (!L1)
343480093f4SDimitry Andric       return L2;
344480093f4SDimitry Andric     L1 = L1->getLeader();
345480093f4SDimitry Andric     if (L1 == L2)
346480093f4SDimitry Andric       return L1;
347480093f4SDimitry Andric     // Splice L2 before L1's members.
348480093f4SDimitry Andric     UserValue *End = L2;
349480093f4SDimitry Andric     while (End->next) {
350480093f4SDimitry Andric       End->leader = L1;
351480093f4SDimitry Andric       End = End->next;
352480093f4SDimitry Andric     }
353480093f4SDimitry Andric     End->leader = L1;
354480093f4SDimitry Andric     End->next = L1->next;
355480093f4SDimitry Andric     L1->next = L2;
356480093f4SDimitry Andric     return L1;
3570b57cec5SDimitry Andric   }
3580b57cec5SDimitry Andric 
3590b57cec5SDimitry Andric   /// Return the location number that matches Loc.
3600b57cec5SDimitry Andric   ///
3610b57cec5SDimitry Andric   /// For undef values we always return location number UndefLocNo without
3620b57cec5SDimitry Andric   /// inserting anything in locations. Since locations is a vector and the
3630b57cec5SDimitry Andric   /// location number is the position in the vector and UndefLocNo is ~0,
3640b57cec5SDimitry Andric   /// we would need a very big vector to put the value at the right position.
getLocationNo(const MachineOperand & LocMO)3650b57cec5SDimitry Andric   unsigned getLocationNo(const MachineOperand &LocMO) {
3660b57cec5SDimitry Andric     if (LocMO.isReg()) {
3670b57cec5SDimitry Andric       if (LocMO.getReg() == 0)
3680b57cec5SDimitry Andric         return UndefLocNo;
3690b57cec5SDimitry Andric       // For register locations we dont care about use/def and other flags.
3700b57cec5SDimitry Andric       for (unsigned i = 0, e = locations.size(); i != e; ++i)
3710b57cec5SDimitry Andric         if (locations[i].isReg() &&
3720b57cec5SDimitry Andric             locations[i].getReg() == LocMO.getReg() &&
3730b57cec5SDimitry Andric             locations[i].getSubReg() == LocMO.getSubReg())
3740b57cec5SDimitry Andric           return i;
3750b57cec5SDimitry Andric     } else
3760b57cec5SDimitry Andric       for (unsigned i = 0, e = locations.size(); i != e; ++i)
3770b57cec5SDimitry Andric         if (LocMO.isIdenticalTo(locations[i]))
3780b57cec5SDimitry Andric           return i;
3790b57cec5SDimitry Andric     locations.push_back(LocMO);
3800b57cec5SDimitry Andric     // We are storing a MachineOperand outside a MachineInstr.
3810b57cec5SDimitry Andric     locations.back().clearParent();
3820b57cec5SDimitry Andric     // Don't store def operands.
3830b57cec5SDimitry Andric     if (locations.back().isReg()) {
3840b57cec5SDimitry Andric       if (locations.back().isDef())
3850b57cec5SDimitry Andric         locations.back().setIsDead(false);
3860b57cec5SDimitry Andric       locations.back().setIsUse();
3870b57cec5SDimitry Andric     }
3880b57cec5SDimitry Andric     return locations.size() - 1;
3890b57cec5SDimitry Andric   }
3900b57cec5SDimitry Andric 
391480093f4SDimitry Andric   /// Remove (recycle) a location number. If \p LocNo still is used by the
392480093f4SDimitry Andric   /// locInts nothing is done.
removeLocationIfUnused(unsigned LocNo)393480093f4SDimitry Andric   void removeLocationIfUnused(unsigned LocNo) {
394480093f4SDimitry Andric     // Bail out if LocNo still is used.
395480093f4SDimitry Andric     for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
396fe6060f1SDimitry Andric       const DbgVariableValue &DbgValue = I.value();
397fe6060f1SDimitry Andric       if (DbgValue.containsLocNo(LocNo))
398480093f4SDimitry Andric         return;
399480093f4SDimitry Andric     }
400480093f4SDimitry Andric     // Remove the entry in the locations vector, and adjust all references to
401480093f4SDimitry Andric     // location numbers above the removed entry.
402480093f4SDimitry Andric     locations.erase(locations.begin() + LocNo);
403480093f4SDimitry Andric     for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
404fe6060f1SDimitry Andric       const DbgVariableValue &DbgValue = I.value();
405fe6060f1SDimitry Andric       if (DbgValue.hasLocNoGreaterThan(LocNo))
406fe6060f1SDimitry Andric         I.setValueUnchecked(DbgValue.decrementLocNosAfterPivot(LocNo));
407480093f4SDimitry Andric     }
408480093f4SDimitry Andric   }
409480093f4SDimitry Andric 
4100b57cec5SDimitry Andric   /// Ensure that all virtual register locations are mapped.
4110b57cec5SDimitry Andric   void mapVirtRegs(LDVImpl *LDV);
4120b57cec5SDimitry Andric 
4135ffd83dbSDimitry Andric   /// Add a definition point to this user value.
addDef(SlotIndex Idx,ArrayRef<MachineOperand> LocMOs,bool IsIndirect,bool IsList,const DIExpression & Expr)414fe6060f1SDimitry Andric   void addDef(SlotIndex Idx, ArrayRef<MachineOperand> LocMOs, bool IsIndirect,
415fe6060f1SDimitry Andric               bool IsList, const DIExpression &Expr) {
416fe6060f1SDimitry Andric     SmallVector<unsigned> Locs;
417349cc55cSDimitry Andric     for (const MachineOperand &Op : LocMOs)
418fe6060f1SDimitry Andric       Locs.push_back(getLocationNo(Op));
419fe6060f1SDimitry Andric     DbgVariableValue DbgValue(Locs, IsIndirect, IsList, Expr);
4205ffd83dbSDimitry Andric     // Add a singular (Idx,Idx) -> value mapping.
4210b57cec5SDimitry Andric     LocMap::iterator I = locInts.find(Idx);
4220b57cec5SDimitry Andric     if (!I.valid() || I.start() != Idx)
423fe6060f1SDimitry Andric       I.insert(Idx, Idx.getNextSlot(), std::move(DbgValue));
4240b57cec5SDimitry Andric     else
4250b57cec5SDimitry Andric       // A later DBG_VALUE at the same SlotIndex overrides the old location.
426fe6060f1SDimitry Andric       I.setValue(std::move(DbgValue));
4270b57cec5SDimitry Andric   }
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric   /// Extend the current definition as far as possible down.
4300b57cec5SDimitry Andric   ///
4310b57cec5SDimitry Andric   /// Stop when meeting an existing def or when leaving the live
4320b57cec5SDimitry Andric   /// range of VNI. End points where VNI is no longer live are added to Kills.
4330b57cec5SDimitry Andric   ///
4340b57cec5SDimitry Andric   /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
4350b57cec5SDimitry Andric   /// data-flow analysis to propagate them beyond basic block boundaries.
4360b57cec5SDimitry Andric   ///
4370b57cec5SDimitry Andric   /// \param Idx Starting point for the definition.
4385ffd83dbSDimitry Andric   /// \param DbgValue value to propagate.
439fe6060f1SDimitry Andric   /// \param LiveIntervalInfo For each location number key in this map,
440fe6060f1SDimitry Andric   /// restricts liveness to where the LiveRange has the value equal to the\
441fe6060f1SDimitry Andric   /// VNInfo.
4420b57cec5SDimitry Andric   /// \param [out] Kills Append end points of VNI's live range to Kills.
4430b57cec5SDimitry Andric   /// \param LIS Live intervals analysis.
444bdd1243dSDimitry Andric   void
445bdd1243dSDimitry Andric   extendDef(SlotIndex Idx, DbgVariableValue DbgValue,
446fe6060f1SDimitry Andric             SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>>
447fe6060f1SDimitry Andric                 &LiveIntervalInfo,
448bdd1243dSDimitry Andric             std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills,
4490b57cec5SDimitry Andric             LiveIntervals &LIS);
4500b57cec5SDimitry Andric 
4515ffd83dbSDimitry Andric   /// The value in LI may be copies to other registers. Determine if
4520b57cec5SDimitry Andric   /// any of the copies are available at the kill points, and add defs if
4530b57cec5SDimitry Andric   /// possible.
4540b57cec5SDimitry Andric   ///
4555ffd83dbSDimitry Andric   /// \param DbgValue Location number of LI->reg, and DIExpression.
456fe6060f1SDimitry Andric   /// \param LocIntervals Scan for copies of the value for each location in the
457fe6060f1SDimitry Andric   /// corresponding LiveInterval->reg.
458fe6060f1SDimitry Andric   /// \param KilledAt The point where the range of DbgValue could be extended.
4595ffd83dbSDimitry Andric   /// \param [in,out] NewDefs Append (Idx, DbgValue) of inserted defs here.
4600b57cec5SDimitry Andric   void addDefsFromCopies(
461fe6060f1SDimitry Andric       DbgVariableValue DbgValue,
462fe6060f1SDimitry Andric       SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals,
463fe6060f1SDimitry Andric       SlotIndex KilledAt,
4645ffd83dbSDimitry Andric       SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
4650b57cec5SDimitry Andric       MachineRegisterInfo &MRI, LiveIntervals &LIS);
4660b57cec5SDimitry Andric 
4670b57cec5SDimitry Andric   /// Compute the live intervals of all locations after collecting all their
4680b57cec5SDimitry Andric   /// def points.
4690b57cec5SDimitry Andric   void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
4700b57cec5SDimitry Andric                         LiveIntervals &LIS, LexicalScopes &LS);
4710b57cec5SDimitry Andric 
4720b57cec5SDimitry Andric   /// Replace OldReg ranges with NewRegs ranges where NewRegs is
4730b57cec5SDimitry Andric   /// live. Returns true if any changes were made.
4745ffd83dbSDimitry Andric   bool splitRegister(Register OldReg, ArrayRef<Register> NewRegs,
4750b57cec5SDimitry Andric                      LiveIntervals &LIS);
4760b57cec5SDimitry Andric 
4770b57cec5SDimitry Andric   /// Rewrite virtual register locations according to the provided virtual
4780b57cec5SDimitry Andric   /// register map. Record the stack slot offsets for the locations that
4790b57cec5SDimitry Andric   /// were spilled.
4800b57cec5SDimitry Andric   void rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
4810b57cec5SDimitry Andric                         const TargetInstrInfo &TII,
4820b57cec5SDimitry Andric                         const TargetRegisterInfo &TRI,
4830b57cec5SDimitry Andric                         SpillOffsetMap &SpillOffsets);
4840b57cec5SDimitry Andric 
4850b57cec5SDimitry Andric   /// Recreate DBG_VALUE instruction from data structures.
4860b57cec5SDimitry Andric   void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
4870b57cec5SDimitry Andric                        const TargetInstrInfo &TII,
4880b57cec5SDimitry Andric                        const TargetRegisterInfo &TRI,
489fe6060f1SDimitry Andric                        const SpillOffsetMap &SpillOffsets,
490fe6060f1SDimitry Andric                        BlockSkipInstsMap &BBSkipInstsMap);
4910b57cec5SDimitry Andric 
4920b57cec5SDimitry Andric   /// Return DebugLoc of this UserValue.
getDebugLoc()493fe6060f1SDimitry Andric   const DebugLoc &getDebugLoc() { return dl; }
4940b57cec5SDimitry Andric 
4950b57cec5SDimitry Andric   void print(raw_ostream &, const TargetRegisterInfo *);
4960b57cec5SDimitry Andric };
4970b57cec5SDimitry Andric 
4980b57cec5SDimitry Andric /// A user label is a part of a debug info user label.
4990b57cec5SDimitry Andric class UserLabel {
5000b57cec5SDimitry Andric   const DILabel *Label; ///< The debug info label we are part of.
5010b57cec5SDimitry Andric   DebugLoc dl;          ///< The debug location for the label. This is
5020b57cec5SDimitry Andric                         ///< used by dwarf writer to find lexical scope.
5030b57cec5SDimitry Andric   SlotIndex loc;        ///< Slot used by the debug label.
5040b57cec5SDimitry Andric 
5050b57cec5SDimitry Andric   /// Insert a DBG_LABEL into MBB at Idx.
5060b57cec5SDimitry Andric   void insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
507fe6060f1SDimitry Andric                         LiveIntervals &LIS, const TargetInstrInfo &TII,
508fe6060f1SDimitry Andric                         BlockSkipInstsMap &BBSkipInstsMap);
5090b57cec5SDimitry Andric 
5100b57cec5SDimitry Andric public:
5110b57cec5SDimitry Andric   /// Create a new UserLabel.
UserLabel(const DILabel * label,DebugLoc L,SlotIndex Idx)5120b57cec5SDimitry Andric   UserLabel(const DILabel *label, DebugLoc L, SlotIndex Idx)
5130b57cec5SDimitry Andric       : Label(label), dl(std::move(L)), loc(Idx) {}
5140b57cec5SDimitry Andric 
5150b57cec5SDimitry Andric   /// Does this UserLabel match the parameters?
matches(const DILabel * L,const DILocation * IA,const SlotIndex Index) const5165ffd83dbSDimitry Andric   bool matches(const DILabel *L, const DILocation *IA,
5170b57cec5SDimitry Andric              const SlotIndex Index) const {
5180b57cec5SDimitry Andric     return Label == L && dl->getInlinedAt() == IA && loc == Index;
5190b57cec5SDimitry Andric   }
5200b57cec5SDimitry Andric 
5210b57cec5SDimitry Andric   /// Recreate DBG_LABEL instruction from data structures.
522fe6060f1SDimitry Andric   void emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
523fe6060f1SDimitry Andric                       BlockSkipInstsMap &BBSkipInstsMap);
5240b57cec5SDimitry Andric 
5250b57cec5SDimitry Andric   /// Return DebugLoc of this UserLabel.
getDebugLoc()526fe6060f1SDimitry Andric   const DebugLoc &getDebugLoc() { return dl; }
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric   void print(raw_ostream &, const TargetRegisterInfo *);
5290b57cec5SDimitry Andric };
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric /// Implementation of the LiveDebugVariables pass.
5320b57cec5SDimitry Andric class LDVImpl {
5330b57cec5SDimitry Andric   LiveDebugVariables &pass;
5340b57cec5SDimitry Andric   LocMap::Allocator allocator;
5350b57cec5SDimitry Andric   MachineFunction *MF = nullptr;
5360b57cec5SDimitry Andric   LiveIntervals *LIS;
5370b57cec5SDimitry Andric   const TargetRegisterInfo *TRI;
5380b57cec5SDimitry Andric 
539fe6060f1SDimitry Andric   /// Position and VReg of a PHI instruction during register allocation.
540fe6060f1SDimitry Andric   struct PHIValPos {
541fe6060f1SDimitry Andric     SlotIndex SI;    /// Slot where this PHI occurs.
542fe6060f1SDimitry Andric     Register Reg;    /// VReg this PHI occurs in.
543fe6060f1SDimitry Andric     unsigned SubReg; /// Qualifiying subregister for Reg.
544fe6060f1SDimitry Andric   };
545fe6060f1SDimitry Andric 
546fe6060f1SDimitry Andric   /// Map from debug instruction number to PHI position during allocation.
547fe6060f1SDimitry Andric   std::map<unsigned, PHIValPos> PHIValToPos;
548fe6060f1SDimitry Andric   /// Index of, for each VReg, which debug instruction numbers and corresponding
549fe6060f1SDimitry Andric   /// PHIs are sensitive to splitting. Each VReg may have multiple PHI defs,
550fe6060f1SDimitry Andric   /// at different positions.
551fe6060f1SDimitry Andric   DenseMap<Register, std::vector<unsigned>> RegToPHIIdx;
552fe6060f1SDimitry Andric 
553fe6060f1SDimitry Andric   /// Record for any debug instructions unlinked from their blocks during
554fe6060f1SDimitry Andric   /// regalloc. Stores the instr and it's location, so that they can be
555fe6060f1SDimitry Andric   /// re-inserted after regalloc is over.
556fe6060f1SDimitry Andric   struct InstrPos {
557fe6060f1SDimitry Andric     MachineInstr *MI;       ///< Debug instruction, unlinked from it's block.
558fe6060f1SDimitry Andric     SlotIndex Idx;          ///< Slot position where MI should be re-inserted.
559fe6060f1SDimitry Andric     MachineBasicBlock *MBB; ///< Block that MI was in.
560fe6060f1SDimitry Andric   };
561fe6060f1SDimitry Andric 
562fe6060f1SDimitry Andric   /// Collection of stored debug instructions, preserved until after regalloc.
563fe6060f1SDimitry Andric   SmallVector<InstrPos, 32> StashedDebugInstrs;
564e8d8bef9SDimitry Andric 
5650b57cec5SDimitry Andric   /// Whether emitDebugValues is called.
5660b57cec5SDimitry Andric   bool EmitDone = false;
5670b57cec5SDimitry Andric 
5680b57cec5SDimitry Andric   /// Whether the machine function is modified during the pass.
5690b57cec5SDimitry Andric   bool ModifiedMF = false;
5700b57cec5SDimitry Andric 
5710b57cec5SDimitry Andric   /// All allocated UserValue instances.
5720b57cec5SDimitry Andric   SmallVector<std::unique_ptr<UserValue>, 8> userValues;
5730b57cec5SDimitry Andric 
5740b57cec5SDimitry Andric   /// All allocated UserLabel instances.
5750b57cec5SDimitry Andric   SmallVector<std::unique_ptr<UserLabel>, 2> userLabels;
5760b57cec5SDimitry Andric 
577480093f4SDimitry Andric   /// Map virtual register to eq class leader.
578480093f4SDimitry Andric   using VRMap = DenseMap<unsigned, UserValue *>;
579480093f4SDimitry Andric   VRMap virtRegToEqClass;
5800b57cec5SDimitry Andric 
5815ffd83dbSDimitry Andric   /// Map to find existing UserValue instances.
5825ffd83dbSDimitry Andric   using UVMap = DenseMap<DebugVariable, UserValue *>;
583480093f4SDimitry Andric   UVMap userVarMap;
5840b57cec5SDimitry Andric 
5850b57cec5SDimitry Andric   /// Find or create a UserValue.
5865ffd83dbSDimitry Andric   UserValue *getUserValue(const DILocalVariable *Var,
587bdd1243dSDimitry Andric                           std::optional<DIExpression::FragmentInfo> Fragment,
5880b57cec5SDimitry Andric                           const DebugLoc &DL);
5890b57cec5SDimitry Andric 
590480093f4SDimitry Andric   /// Find the EC leader for VirtReg or null.
5915ffd83dbSDimitry Andric   UserValue *lookupVirtReg(Register VirtReg);
5920b57cec5SDimitry Andric 
5930b57cec5SDimitry Andric   /// Add DBG_VALUE instruction to our maps.
5940b57cec5SDimitry Andric   ///
5950b57cec5SDimitry Andric   /// \param MI DBG_VALUE instruction
5960b57cec5SDimitry Andric   /// \param Idx Last valid SLotIndex before instruction.
5970b57cec5SDimitry Andric   ///
5980b57cec5SDimitry Andric   /// \returns True if the DBG_VALUE instruction should be deleted.
5990b57cec5SDimitry Andric   bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
6000b57cec5SDimitry Andric 
601fe6060f1SDimitry Andric   /// Track variable location debug instructions while using the instruction
602fe6060f1SDimitry Andric   /// referencing implementation. Such debug instructions do not need to be
603fe6060f1SDimitry Andric   /// updated during regalloc because they identify instructions rather than
604fe6060f1SDimitry Andric   /// register locations. However, they needs to be removed from the
605fe6060f1SDimitry Andric   /// MachineFunction during regalloc, then re-inserted later, to avoid
606fe6060f1SDimitry Andric   /// disrupting the allocator.
607e8d8bef9SDimitry Andric   ///
608fe6060f1SDimitry Andric   /// \param MI Any DBG_VALUE / DBG_INSTR_REF / DBG_PHI instruction
609e8d8bef9SDimitry Andric   /// \param Idx Last valid SlotIndex before instruction
610e8d8bef9SDimitry Andric   ///
611fe6060f1SDimitry Andric   /// \returns Iterator to continue processing from after unlinking.
612fe6060f1SDimitry Andric   MachineBasicBlock::iterator handleDebugInstr(MachineInstr &MI, SlotIndex Idx);
613e8d8bef9SDimitry Andric 
6140b57cec5SDimitry Andric   /// Add DBG_LABEL instruction to UserLabel.
6150b57cec5SDimitry Andric   ///
6160b57cec5SDimitry Andric   /// \param MI DBG_LABEL instruction
6170b57cec5SDimitry Andric   /// \param Idx Last valid SlotIndex before instruction.
6180b57cec5SDimitry Andric   ///
6190b57cec5SDimitry Andric   /// \returns True if the DBG_LABEL instruction should be deleted.
6200b57cec5SDimitry Andric   bool handleDebugLabel(MachineInstr &MI, SlotIndex Idx);
6210b57cec5SDimitry Andric 
6220b57cec5SDimitry Andric   /// Collect and erase all DBG_VALUE instructions, adding a UserValue def
6230b57cec5SDimitry Andric   /// for each instruction.
6240b57cec5SDimitry Andric   ///
6250b57cec5SDimitry Andric   /// \param mf MachineFunction to be scanned.
626fe6060f1SDimitry Andric   /// \param InstrRef Whether to operate in instruction referencing mode. If
627fe6060f1SDimitry Andric   ///        true, most of LiveDebugVariables doesn't run.
6280b57cec5SDimitry Andric   ///
6290b57cec5SDimitry Andric   /// \returns True if any debug values were found.
630fe6060f1SDimitry Andric   bool collectDebugValues(MachineFunction &mf, bool InstrRef);
6310b57cec5SDimitry Andric 
6320b57cec5SDimitry Andric   /// Compute the live intervals of all user values after collecting all
6330b57cec5SDimitry Andric   /// their def points.
6340b57cec5SDimitry Andric   void computeIntervals();
6350b57cec5SDimitry Andric 
6360b57cec5SDimitry Andric public:
LDVImpl(LiveDebugVariables * ps)6370b57cec5SDimitry Andric   LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
6380b57cec5SDimitry Andric 
639fe6060f1SDimitry Andric   bool runOnMachineFunction(MachineFunction &mf, bool InstrRef);
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric   /// Release all memory.
clear()6420b57cec5SDimitry Andric   void clear() {
6430b57cec5SDimitry Andric     MF = nullptr;
644fe6060f1SDimitry Andric     PHIValToPos.clear();
645fe6060f1SDimitry Andric     RegToPHIIdx.clear();
646fe6060f1SDimitry Andric     StashedDebugInstrs.clear();
6470b57cec5SDimitry Andric     userValues.clear();
6480b57cec5SDimitry Andric     userLabels.clear();
649480093f4SDimitry Andric     virtRegToEqClass.clear();
650480093f4SDimitry Andric     userVarMap.clear();
6510b57cec5SDimitry Andric     // Make sure we call emitDebugValues if the machine function was modified.
6520b57cec5SDimitry Andric     assert((!ModifiedMF || EmitDone) &&
6530b57cec5SDimitry Andric            "Dbg values are not emitted in LDV");
6540b57cec5SDimitry Andric     EmitDone = false;
6550b57cec5SDimitry Andric     ModifiedMF = false;
6560b57cec5SDimitry Andric   }
6570b57cec5SDimitry Andric 
658480093f4SDimitry Andric   /// Map virtual register to an equivalence class.
6595ffd83dbSDimitry Andric   void mapVirtReg(Register VirtReg, UserValue *EC);
6600b57cec5SDimitry Andric 
661fe6060f1SDimitry Andric   /// Replace any PHI referring to OldReg with its corresponding NewReg, if
662fe6060f1SDimitry Andric   /// present.
663fe6060f1SDimitry Andric   void splitPHIRegister(Register OldReg, ArrayRef<Register> NewRegs);
664fe6060f1SDimitry Andric 
6650b57cec5SDimitry Andric   /// Replace all references to OldReg with NewRegs.
6665ffd83dbSDimitry Andric   void splitRegister(Register OldReg, ArrayRef<Register> NewRegs);
6670b57cec5SDimitry Andric 
6680b57cec5SDimitry Andric   /// Recreate DBG_VALUE instruction from data structures.
6690b57cec5SDimitry Andric   void emitDebugValues(VirtRegMap *VRM);
6700b57cec5SDimitry Andric 
6710b57cec5SDimitry Andric   void print(raw_ostream&);
6720b57cec5SDimitry Andric };
6730b57cec5SDimitry Andric 
6740b57cec5SDimitry Andric } // end anonymous namespace
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
printDebugLoc(const DebugLoc & DL,raw_ostream & CommentOS,const LLVMContext & Ctx)6770b57cec5SDimitry Andric static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
6780b57cec5SDimitry Andric                           const LLVMContext &Ctx) {
6790b57cec5SDimitry Andric   if (!DL)
6800b57cec5SDimitry Andric     return;
6810b57cec5SDimitry Andric 
6820b57cec5SDimitry Andric   auto *Scope = cast<DIScope>(DL.getScope());
6830b57cec5SDimitry Andric   // Omit the directory, because it's likely to be long and uninteresting.
6840b57cec5SDimitry Andric   CommentOS << Scope->getFilename();
6850b57cec5SDimitry Andric   CommentOS << ':' << DL.getLine();
6860b57cec5SDimitry Andric   if (DL.getCol() != 0)
6870b57cec5SDimitry Andric     CommentOS << ':' << DL.getCol();
6880b57cec5SDimitry Andric 
6890b57cec5SDimitry Andric   DebugLoc InlinedAtDL = DL.getInlinedAt();
6900b57cec5SDimitry Andric   if (!InlinedAtDL)
6910b57cec5SDimitry Andric     return;
6920b57cec5SDimitry Andric 
6930b57cec5SDimitry Andric   CommentOS << " @[ ";
6940b57cec5SDimitry Andric   printDebugLoc(InlinedAtDL, CommentOS, Ctx);
6950b57cec5SDimitry Andric   CommentOS << " ]";
6960b57cec5SDimitry Andric }
6970b57cec5SDimitry Andric 
printExtendedName(raw_ostream & OS,const DINode * Node,const DILocation * DL)6980b57cec5SDimitry Andric static void printExtendedName(raw_ostream &OS, const DINode *Node,
6990b57cec5SDimitry Andric                               const DILocation *DL) {
7000b57cec5SDimitry Andric   const LLVMContext &Ctx = Node->getContext();
7010b57cec5SDimitry Andric   StringRef Res;
702480093f4SDimitry Andric   unsigned Line = 0;
7030b57cec5SDimitry Andric   if (const auto *V = dyn_cast<const DILocalVariable>(Node)) {
7040b57cec5SDimitry Andric     Res = V->getName();
7050b57cec5SDimitry Andric     Line = V->getLine();
7060b57cec5SDimitry Andric   } else if (const auto *L = dyn_cast<const DILabel>(Node)) {
7070b57cec5SDimitry Andric     Res = L->getName();
7080b57cec5SDimitry Andric     Line = L->getLine();
7090b57cec5SDimitry Andric   }
7100b57cec5SDimitry Andric 
7110b57cec5SDimitry Andric   if (!Res.empty())
7120b57cec5SDimitry Andric     OS << Res << "," << Line;
7130b57cec5SDimitry Andric   auto *InlinedAt = DL ? DL->getInlinedAt() : nullptr;
7140b57cec5SDimitry Andric   if (InlinedAt) {
7150b57cec5SDimitry Andric     if (DebugLoc InlinedAtDL = InlinedAt) {
7160b57cec5SDimitry Andric       OS << " @[";
7170b57cec5SDimitry Andric       printDebugLoc(InlinedAtDL, OS, Ctx);
7180b57cec5SDimitry Andric       OS << "]";
7190b57cec5SDimitry Andric     }
7200b57cec5SDimitry Andric   }
7210b57cec5SDimitry Andric }
7220b57cec5SDimitry Andric 
print(raw_ostream & OS,const TargetRegisterInfo * TRI)7230b57cec5SDimitry Andric void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
7240b57cec5SDimitry Andric   OS << "!\"";
7250b57cec5SDimitry Andric   printExtendedName(OS, Variable, dl);
7260b57cec5SDimitry Andric 
7270b57cec5SDimitry Andric   OS << "\"\t";
7280b57cec5SDimitry Andric   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
7290b57cec5SDimitry Andric     OS << " [" << I.start() << ';' << I.stop() << "):";
7300b57cec5SDimitry Andric     if (I.value().isUndef())
7310b57cec5SDimitry Andric       OS << " undef";
7320b57cec5SDimitry Andric     else {
733fe6060f1SDimitry Andric       I.value().printLocNos(OS);
7345ffd83dbSDimitry Andric       if (I.value().getWasIndirect())
73513138422SDimitry Andric         OS << " ind";
736fe6060f1SDimitry Andric       else if (I.value().getWasList())
737fe6060f1SDimitry Andric         OS << " list";
7380b57cec5SDimitry Andric     }
7390b57cec5SDimitry Andric   }
7400b57cec5SDimitry Andric   for (unsigned i = 0, e = locations.size(); i != e; ++i) {
7410b57cec5SDimitry Andric     OS << " Loc" << i << '=';
7420b57cec5SDimitry Andric     locations[i].print(OS, TRI);
7430b57cec5SDimitry Andric   }
7440b57cec5SDimitry Andric   OS << '\n';
7450b57cec5SDimitry Andric }
7460b57cec5SDimitry Andric 
print(raw_ostream & OS,const TargetRegisterInfo * TRI)7470b57cec5SDimitry Andric void UserLabel::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
7480b57cec5SDimitry Andric   OS << "!\"";
7490b57cec5SDimitry Andric   printExtendedName(OS, Label, dl);
7500b57cec5SDimitry Andric 
7510b57cec5SDimitry Andric   OS << "\"\t";
7520b57cec5SDimitry Andric   OS << loc;
7530b57cec5SDimitry Andric   OS << '\n';
7540b57cec5SDimitry Andric }
7550b57cec5SDimitry Andric 
print(raw_ostream & OS)7560b57cec5SDimitry Andric void LDVImpl::print(raw_ostream &OS) {
7570b57cec5SDimitry Andric   OS << "********** DEBUG VARIABLES **********\n";
7580b57cec5SDimitry Andric   for (auto &userValue : userValues)
7590b57cec5SDimitry Andric     userValue->print(OS, TRI);
7600b57cec5SDimitry Andric   OS << "********** DEBUG LABELS **********\n";
7610b57cec5SDimitry Andric   for (auto &userLabel : userLabels)
7620b57cec5SDimitry Andric     userLabel->print(OS, TRI);
7630b57cec5SDimitry Andric }
7640b57cec5SDimitry Andric #endif
7650b57cec5SDimitry Andric 
mapVirtRegs(LDVImpl * LDV)7660b57cec5SDimitry Andric void UserValue::mapVirtRegs(LDVImpl *LDV) {
7670b57cec5SDimitry Andric   for (unsigned i = 0, e = locations.size(); i != e; ++i)
768bdd1243dSDimitry Andric     if (locations[i].isReg() && locations[i].getReg().isVirtual())
7690b57cec5SDimitry Andric       LDV->mapVirtReg(locations[i].getReg(), this);
7700b57cec5SDimitry Andric }
7710b57cec5SDimitry Andric 
772bdd1243dSDimitry Andric UserValue *
getUserValue(const DILocalVariable * Var,std::optional<DIExpression::FragmentInfo> Fragment,const DebugLoc & DL)773bdd1243dSDimitry Andric LDVImpl::getUserValue(const DILocalVariable *Var,
774bdd1243dSDimitry Andric                       std::optional<DIExpression::FragmentInfo> Fragment,
7755ffd83dbSDimitry Andric                       const DebugLoc &DL) {
7765ffd83dbSDimitry Andric   // FIXME: Handle partially overlapping fragments. See
7775ffd83dbSDimitry Andric   // https://reviews.llvm.org/D70121#1849741.
7785ffd83dbSDimitry Andric   DebugVariable ID(Var, Fragment, DL->getInlinedAt());
7795ffd83dbSDimitry Andric   UserValue *&UV = userVarMap[ID];
7805ffd83dbSDimitry Andric   if (!UV) {
781480093f4SDimitry Andric     userValues.push_back(
7825ffd83dbSDimitry Andric         std::make_unique<UserValue>(Var, Fragment, DL, allocator));
7835ffd83dbSDimitry Andric     UV = userValues.back().get();
7845ffd83dbSDimitry Andric   }
785480093f4SDimitry Andric   return UV;
786480093f4SDimitry Andric }
787480093f4SDimitry Andric 
mapVirtReg(Register VirtReg,UserValue * EC)7885ffd83dbSDimitry Andric void LDVImpl::mapVirtReg(Register VirtReg, UserValue *EC) {
789bdd1243dSDimitry Andric   assert(VirtReg.isVirtual() && "Only map VirtRegs");
790480093f4SDimitry Andric   UserValue *&Leader = virtRegToEqClass[VirtReg];
791480093f4SDimitry Andric   Leader = UserValue::merge(Leader, EC);
7920b57cec5SDimitry Andric }
7930b57cec5SDimitry Andric 
lookupVirtReg(Register VirtReg)7945ffd83dbSDimitry Andric UserValue *LDVImpl::lookupVirtReg(Register VirtReg) {
795480093f4SDimitry Andric   if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
796480093f4SDimitry Andric     return UV->getLeader();
7970b57cec5SDimitry Andric   return nullptr;
7980b57cec5SDimitry Andric }
7990b57cec5SDimitry Andric 
handleDebugValue(MachineInstr & MI,SlotIndex Idx)8000b57cec5SDimitry Andric bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
801fe6060f1SDimitry Andric   // DBG_VALUE loc, offset, variable, expr
802fe6060f1SDimitry Andric   // DBG_VALUE_LIST variable, expr, locs...
803fe6060f1SDimitry Andric   if (!MI.isDebugValue()) {
804fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't handle non-DBG_VALUE*: " << MI);
805fe6060f1SDimitry Andric     return false;
806fe6060f1SDimitry Andric   }
807fe6060f1SDimitry Andric   if (!MI.getDebugVariableOp().isMetadata()) {
808fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't handle DBG_VALUE* with invalid variable: "
809fe6060f1SDimitry Andric                       << MI);
810fe6060f1SDimitry Andric     return false;
811fe6060f1SDimitry Andric   }
812fe6060f1SDimitry Andric   if (MI.isNonListDebugValue() &&
813fe6060f1SDimitry Andric       (MI.getNumOperands() != 4 ||
814fe6060f1SDimitry Andric        !(MI.getDebugOffset().isImm() || MI.getDebugOffset().isReg()))) {
815fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't handle malformed DBG_VALUE: " << MI);
8160b57cec5SDimitry Andric     return false;
8170b57cec5SDimitry Andric   }
8180b57cec5SDimitry Andric 
8190b57cec5SDimitry Andric   // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual
8200b57cec5SDimitry Andric   // register that hasn't been defined yet. If we do not remove those here, then
8210b57cec5SDimitry Andric   // the re-insertion of the DBG_VALUE instruction after register allocation
8220b57cec5SDimitry Andric   // will be incorrect.
8230b57cec5SDimitry Andric   bool Discard = false;
824fe6060f1SDimitry Andric   for (const MachineOperand &Op : MI.debug_operands()) {
825bdd1243dSDimitry Andric     if (Op.isReg() && Op.getReg().isVirtual()) {
826fe6060f1SDimitry Andric       const Register Reg = Op.getReg();
8270b57cec5SDimitry Andric       if (!LIS->hasInterval(Reg)) {
8280b57cec5SDimitry Andric         // The DBG_VALUE is described by a virtual register that does not have a
8290b57cec5SDimitry Andric         // live interval. Discard the DBG_VALUE.
8300b57cec5SDimitry Andric         Discard = true;
8310b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx
8320b57cec5SDimitry Andric                           << " " << MI);
8330b57cec5SDimitry Andric       } else {
834fe6060f1SDimitry Andric         // The DBG_VALUE is only valid if either Reg is live out from Idx, or
835fe6060f1SDimitry Andric         // Reg is defined dead at Idx (where Idx is the slot index for the
836fe6060f1SDimitry Andric         // instruction preceding the DBG_VALUE).
8370b57cec5SDimitry Andric         const LiveInterval &LI = LIS->getInterval(Reg);
8380b57cec5SDimitry Andric         LiveQueryResult LRQ = LI.Query(Idx);
8390b57cec5SDimitry Andric         if (!LRQ.valueOutOrDead()) {
8400b57cec5SDimitry Andric           // We have found a DBG_VALUE with the value in a virtual register that
8410b57cec5SDimitry Andric           // is not live. Discard the DBG_VALUE.
8420b57cec5SDimitry Andric           Discard = true;
8430b57cec5SDimitry Andric           LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx
8440b57cec5SDimitry Andric                             << " " << MI);
8450b57cec5SDimitry Andric         }
8460b57cec5SDimitry Andric       }
8470b57cec5SDimitry Andric     }
848fe6060f1SDimitry Andric   }
8490b57cec5SDimitry Andric 
8500b57cec5SDimitry Andric   // Get or create the UserValue for (variable,offset) here.
8515ffd83dbSDimitry Andric   bool IsIndirect = MI.isDebugOffsetImm();
85213138422SDimitry Andric   if (IsIndirect)
8535ffd83dbSDimitry Andric     assert(MI.getDebugOffset().getImm() == 0 &&
8545ffd83dbSDimitry Andric            "DBG_VALUE with nonzero offset");
855fe6060f1SDimitry Andric   bool IsList = MI.isDebugValueList();
8560b57cec5SDimitry Andric   const DILocalVariable *Var = MI.getDebugVariable();
8570b57cec5SDimitry Andric   const DIExpression *Expr = MI.getDebugExpression();
8585ffd83dbSDimitry Andric   UserValue *UV = getUserValue(Var, Expr->getFragmentInfo(), MI.getDebugLoc());
8590b57cec5SDimitry Andric   if (!Discard)
860fe6060f1SDimitry Andric     UV->addDef(Idx,
861fe6060f1SDimitry Andric                ArrayRef<MachineOperand>(MI.debug_operands().begin(),
862fe6060f1SDimitry Andric                                         MI.debug_operands().end()),
863fe6060f1SDimitry Andric                IsIndirect, IsList, *Expr);
8640b57cec5SDimitry Andric   else {
8650b57cec5SDimitry Andric     MachineOperand MO = MachineOperand::CreateReg(0U, false);
8660b57cec5SDimitry Andric     MO.setIsDebug();
867fe6060f1SDimitry Andric     // We should still pass a list the same size as MI.debug_operands() even if
868fe6060f1SDimitry Andric     // all MOs are undef, so that DbgVariableValue can correctly adjust the
869fe6060f1SDimitry Andric     // expression while removing the duplicated undefs.
870fe6060f1SDimitry Andric     SmallVector<MachineOperand, 4> UndefMOs(MI.getNumDebugOperands(), MO);
871fe6060f1SDimitry Andric     UV->addDef(Idx, UndefMOs, false, IsList, *Expr);
8720b57cec5SDimitry Andric   }
8730b57cec5SDimitry Andric   return true;
8740b57cec5SDimitry Andric }
8750b57cec5SDimitry Andric 
handleDebugInstr(MachineInstr & MI,SlotIndex Idx)876fe6060f1SDimitry Andric MachineBasicBlock::iterator LDVImpl::handleDebugInstr(MachineInstr &MI,
877fe6060f1SDimitry Andric                                                       SlotIndex Idx) {
878bdd1243dSDimitry Andric   assert(MI.isDebugValueLike() || MI.isDebugPHI());
879fe6060f1SDimitry Andric 
880fe6060f1SDimitry Andric   // In instruction referencing mode, there should be no DBG_VALUE instructions
881fe6060f1SDimitry Andric   // that refer to virtual registers. They might still refer to constants.
882bdd1243dSDimitry Andric   if (MI.isDebugValueLike())
883bdd1243dSDimitry Andric     assert(none_of(MI.debug_operands(),
884bdd1243dSDimitry Andric                    [](const MachineOperand &MO) {
885bdd1243dSDimitry Andric                      return MO.isReg() && MO.getReg().isVirtual();
886bdd1243dSDimitry Andric                    }) &&
887bdd1243dSDimitry Andric            "MIs should not refer to Virtual Registers in InstrRef mode.");
888fe6060f1SDimitry Andric 
889fe6060f1SDimitry Andric   // Unlink the instruction, store it in the debug instructions collection.
890fe6060f1SDimitry Andric   auto NextInst = std::next(MI.getIterator());
891fe6060f1SDimitry Andric   auto *MBB = MI.getParent();
892fe6060f1SDimitry Andric   MI.removeFromParent();
893fe6060f1SDimitry Andric   StashedDebugInstrs.push_back({&MI, Idx, MBB});
894fe6060f1SDimitry Andric   return NextInst;
895e8d8bef9SDimitry Andric }
896e8d8bef9SDimitry Andric 
handleDebugLabel(MachineInstr & MI,SlotIndex Idx)8970b57cec5SDimitry Andric bool LDVImpl::handleDebugLabel(MachineInstr &MI, SlotIndex Idx) {
8980b57cec5SDimitry Andric   // DBG_LABEL label
8990b57cec5SDimitry Andric   if (MI.getNumOperands() != 1 || !MI.getOperand(0).isMetadata()) {
9000b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't handle " << MI);
9010b57cec5SDimitry Andric     return false;
9020b57cec5SDimitry Andric   }
9030b57cec5SDimitry Andric 
9040b57cec5SDimitry Andric   // Get or create the UserLabel for label here.
9050b57cec5SDimitry Andric   const DILabel *Label = MI.getDebugLabel();
9060b57cec5SDimitry Andric   const DebugLoc &DL = MI.getDebugLoc();
9070b57cec5SDimitry Andric   bool Found = false;
9080b57cec5SDimitry Andric   for (auto const &L : userLabels) {
9095ffd83dbSDimitry Andric     if (L->matches(Label, DL->getInlinedAt(), Idx)) {
9100b57cec5SDimitry Andric       Found = true;
9110b57cec5SDimitry Andric       break;
9120b57cec5SDimitry Andric     }
9130b57cec5SDimitry Andric   }
9140b57cec5SDimitry Andric   if (!Found)
9158bcb0991SDimitry Andric     userLabels.push_back(std::make_unique<UserLabel>(Label, DL, Idx));
9160b57cec5SDimitry Andric 
9170b57cec5SDimitry Andric   return true;
9180b57cec5SDimitry Andric }
9190b57cec5SDimitry Andric 
collectDebugValues(MachineFunction & mf,bool InstrRef)920fe6060f1SDimitry Andric bool LDVImpl::collectDebugValues(MachineFunction &mf, bool InstrRef) {
9210b57cec5SDimitry Andric   bool Changed = false;
922fe6060f1SDimitry Andric   for (MachineBasicBlock &MBB : mf) {
923fe6060f1SDimitry Andric     for (MachineBasicBlock::iterator MBBI = MBB.begin(), MBBE = MBB.end();
9240b57cec5SDimitry Andric          MBBI != MBBE;) {
9250b57cec5SDimitry Andric       // Use the first debug instruction in the sequence to get a SlotIndex
9260b57cec5SDimitry Andric       // for following consecutive debug instructions.
927fe6060f1SDimitry Andric       if (!MBBI->isDebugOrPseudoInstr()) {
9280b57cec5SDimitry Andric         ++MBBI;
9290b57cec5SDimitry Andric         continue;
9300b57cec5SDimitry Andric       }
9310b57cec5SDimitry Andric       // Debug instructions has no slot index. Use the previous
9320b57cec5SDimitry Andric       // non-debug instruction's SlotIndex as its SlotIndex.
9330b57cec5SDimitry Andric       SlotIndex Idx =
934fe6060f1SDimitry Andric           MBBI == MBB.begin()
935fe6060f1SDimitry Andric               ? LIS->getMBBStartIdx(&MBB)
9360b57cec5SDimitry Andric               : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
9370b57cec5SDimitry Andric       // Handle consecutive debug instructions with the same slot index.
9380b57cec5SDimitry Andric       do {
939fe6060f1SDimitry Andric         // In instruction referencing mode, pass each instr to handleDebugInstr
940fe6060f1SDimitry Andric         // to be unlinked. Ignore DBG_VALUE_LISTs -- they refer to vregs, and
941fe6060f1SDimitry Andric         // need to go through the normal live interval splitting process.
942fe6060f1SDimitry Andric         if (InstrRef && (MBBI->isNonListDebugValue() || MBBI->isDebugPHI() ||
943fe6060f1SDimitry Andric                          MBBI->isDebugRef())) {
944fe6060f1SDimitry Andric           MBBI = handleDebugInstr(*MBBI, Idx);
945fe6060f1SDimitry Andric           Changed = true;
946fe6060f1SDimitry Andric         // In normal debug mode, use the dedicated DBG_VALUE / DBG_LABEL handler
947fe6060f1SDimitry Andric         // to track things through register allocation, and erase the instr.
948fe6060f1SDimitry Andric         } else if ((MBBI->isDebugValue() && handleDebugValue(*MBBI, Idx)) ||
9490b57cec5SDimitry Andric                    (MBBI->isDebugLabel() && handleDebugLabel(*MBBI, Idx))) {
950fe6060f1SDimitry Andric           MBBI = MBB.erase(MBBI);
9510b57cec5SDimitry Andric           Changed = true;
9520b57cec5SDimitry Andric         } else
9530b57cec5SDimitry Andric           ++MBBI;
954fe6060f1SDimitry Andric       } while (MBBI != MBBE && MBBI->isDebugOrPseudoInstr());
9550b57cec5SDimitry Andric     }
9560b57cec5SDimitry Andric   }
9570b57cec5SDimitry Andric   return Changed;
9580b57cec5SDimitry Andric }
9590b57cec5SDimitry Andric 
extendDef(SlotIndex Idx,DbgVariableValue DbgValue,SmallDenseMap<unsigned,std::pair<LiveRange *,const VNInfo * >> & LiveIntervalInfo,std::optional<std::pair<SlotIndex,SmallVector<unsigned>>> & Kills,LiveIntervals & LIS)960fe6060f1SDimitry Andric void UserValue::extendDef(
961fe6060f1SDimitry Andric     SlotIndex Idx, DbgVariableValue DbgValue,
962fe6060f1SDimitry Andric     SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>>
963fe6060f1SDimitry Andric         &LiveIntervalInfo,
964bdd1243dSDimitry Andric     std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills,
9650b57cec5SDimitry Andric     LiveIntervals &LIS) {
9660b57cec5SDimitry Andric   SlotIndex Start = Idx;
9670b57cec5SDimitry Andric   MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
9680b57cec5SDimitry Andric   SlotIndex Stop = LIS.getMBBEndIdx(MBB);
9690b57cec5SDimitry Andric   LocMap::iterator I = locInts.find(Start);
9700b57cec5SDimitry Andric 
971fe6060f1SDimitry Andric   // Limit to the intersection of the VNIs' live ranges.
972fe6060f1SDimitry Andric   for (auto &LII : LiveIntervalInfo) {
973fe6060f1SDimitry Andric     LiveRange *LR = LII.second.first;
974fe6060f1SDimitry Andric     assert(LR && LII.second.second && "Missing range info for Idx.");
9750b57cec5SDimitry Andric     LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
976fe6060f1SDimitry Andric     assert(Segment && Segment->valno == LII.second.second &&
977fe6060f1SDimitry Andric            "Invalid VNInfo for Idx given?");
9780b57cec5SDimitry Andric     if (Segment->end < Stop) {
9790b57cec5SDimitry Andric       Stop = Segment->end;
980fe6060f1SDimitry Andric       Kills = {Stop, {LII.first}};
98181ad6265SDimitry Andric     } else if (Segment->end == Stop && Kills) {
982fe6060f1SDimitry Andric       // If multiple locations end at the same place, track all of them in
983fe6060f1SDimitry Andric       // Kills.
984fe6060f1SDimitry Andric       Kills->second.push_back(LII.first);
9850b57cec5SDimitry Andric     }
9860b57cec5SDimitry Andric   }
9870b57cec5SDimitry Andric 
9880b57cec5SDimitry Andric   // There could already be a short def at Start.
9890b57cec5SDimitry Andric   if (I.valid() && I.start() <= Start) {
9900b57cec5SDimitry Andric     // Stop when meeting a different location or an already extended interval.
9910b57cec5SDimitry Andric     Start = Start.getNextSlot();
992fe6060f1SDimitry Andric     if (I.value() != DbgValue || I.stop() != Start) {
993fe6060f1SDimitry Andric       // Clear `Kills`, as we have a new def available.
994bdd1243dSDimitry Andric       Kills = std::nullopt;
9950b57cec5SDimitry Andric       return;
996fe6060f1SDimitry Andric     }
9970b57cec5SDimitry Andric     // This is a one-slot placeholder. Just skip it.
9980b57cec5SDimitry Andric     ++I;
9990b57cec5SDimitry Andric   }
10000b57cec5SDimitry Andric 
10010b57cec5SDimitry Andric   // Limited by the next def.
1002fe6060f1SDimitry Andric   if (I.valid() && I.start() < Stop) {
10030b57cec5SDimitry Andric     Stop = I.start();
1004fe6060f1SDimitry Andric     // Clear `Kills`, as we have a new def available.
1005bdd1243dSDimitry Andric     Kills = std::nullopt;
1006fe6060f1SDimitry Andric   }
10070b57cec5SDimitry Andric 
1008fe6060f1SDimitry Andric   if (Start < Stop) {
1009fe6060f1SDimitry Andric     DbgVariableValue ExtDbgValue(DbgValue);
1010fe6060f1SDimitry Andric     I.insert(Start, Stop, std::move(ExtDbgValue));
1011fe6060f1SDimitry Andric   }
10120b57cec5SDimitry Andric }
10130b57cec5SDimitry Andric 
addDefsFromCopies(DbgVariableValue DbgValue,SmallVectorImpl<std::pair<unsigned,LiveInterval * >> & LocIntervals,SlotIndex KilledAt,SmallVectorImpl<std::pair<SlotIndex,DbgVariableValue>> & NewDefs,MachineRegisterInfo & MRI,LiveIntervals & LIS)10140b57cec5SDimitry Andric void UserValue::addDefsFromCopies(
1015fe6060f1SDimitry Andric     DbgVariableValue DbgValue,
1016fe6060f1SDimitry Andric     SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals,
1017fe6060f1SDimitry Andric     SlotIndex KilledAt,
10185ffd83dbSDimitry Andric     SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
10190b57cec5SDimitry Andric     MachineRegisterInfo &MRI, LiveIntervals &LIS) {
10200b57cec5SDimitry Andric   // Don't track copies from physregs, there are too many uses.
1021bdd1243dSDimitry Andric   if (any_of(LocIntervals,
1022bdd1243dSDimitry Andric              [](auto LocI) { return !LocI.second->reg().isVirtual(); }))
10230b57cec5SDimitry Andric     return;
10240b57cec5SDimitry Andric 
10250b57cec5SDimitry Andric   // Collect all the (vreg, valno) pairs that are copies of LI.
1026fe6060f1SDimitry Andric   SmallDenseMap<unsigned,
1027fe6060f1SDimitry Andric                 SmallVector<std::pair<LiveInterval *, const VNInfo *>, 4>>
1028fe6060f1SDimitry Andric       CopyValues;
1029fe6060f1SDimitry Andric   for (auto &LocInterval : LocIntervals) {
1030fe6060f1SDimitry Andric     unsigned LocNo = LocInterval.first;
1031fe6060f1SDimitry Andric     LiveInterval *LI = LocInterval.second;
1032e8d8bef9SDimitry Andric     for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg())) {
10330b57cec5SDimitry Andric       MachineInstr *MI = MO.getParent();
10340b57cec5SDimitry Andric       // Copies of the full value.
10350b57cec5SDimitry Andric       if (MO.getSubReg() || !MI->isCopy())
10360b57cec5SDimitry Andric         continue;
10378bcb0991SDimitry Andric       Register DstReg = MI->getOperand(0).getReg();
10380b57cec5SDimitry Andric 
10390b57cec5SDimitry Andric       // Don't follow copies to physregs. These are usually setting up call
10400b57cec5SDimitry Andric       // arguments, and the argument registers are always call clobbered. We are
1041fe6060f1SDimitry Andric       // better off in the source register which could be a callee-saved
1042fe6060f1SDimitry Andric       // register, or it could be spilled.
1043bdd1243dSDimitry Andric       if (!DstReg.isVirtual())
10440b57cec5SDimitry Andric         continue;
10450b57cec5SDimitry Andric 
10465ffd83dbSDimitry Andric       // Is the value extended to reach this copy? If not, another def may be
10475ffd83dbSDimitry Andric       // blocking it, or we are looking at a wrong value of LI.
10480b57cec5SDimitry Andric       SlotIndex Idx = LIS.getInstructionIndex(*MI);
10490b57cec5SDimitry Andric       LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
10505ffd83dbSDimitry Andric       if (!I.valid() || I.value() != DbgValue)
10510b57cec5SDimitry Andric         continue;
10520b57cec5SDimitry Andric 
10530b57cec5SDimitry Andric       if (!LIS.hasInterval(DstReg))
10540b57cec5SDimitry Andric         continue;
10550b57cec5SDimitry Andric       LiveInterval *DstLI = &LIS.getInterval(DstReg);
10560b57cec5SDimitry Andric       const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
10570b57cec5SDimitry Andric       assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
1058fe6060f1SDimitry Andric       CopyValues[LocNo].push_back(std::make_pair(DstLI, DstVNI));
1059fe6060f1SDimitry Andric     }
10600b57cec5SDimitry Andric   }
10610b57cec5SDimitry Andric 
10620b57cec5SDimitry Andric   if (CopyValues.empty())
10630b57cec5SDimitry Andric     return;
10640b57cec5SDimitry Andric 
1065fe6060f1SDimitry Andric #if !defined(NDEBUG)
1066fe6060f1SDimitry Andric   for (auto &LocInterval : LocIntervals)
1067fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "Got " << CopyValues[LocInterval.first].size()
1068fe6060f1SDimitry Andric                       << " copies of " << *LocInterval.second << '\n');
1069fe6060f1SDimitry Andric #endif
10700b57cec5SDimitry Andric 
1071fe6060f1SDimitry Andric   // Try to add defs of the copied values for the kill point. Check that there
1072fe6060f1SDimitry Andric   // isn't already a def at Idx.
1073fe6060f1SDimitry Andric   LocMap::iterator I = locInts.find(KilledAt);
1074fe6060f1SDimitry Andric   if (I.valid() && I.start() <= KilledAt)
1075fe6060f1SDimitry Andric     return;
1076fe6060f1SDimitry Andric   DbgVariableValue NewValue(DbgValue);
1077fe6060f1SDimitry Andric   for (auto &LocInterval : LocIntervals) {
1078fe6060f1SDimitry Andric     unsigned LocNo = LocInterval.first;
1079fe6060f1SDimitry Andric     bool FoundCopy = false;
1080fe6060f1SDimitry Andric     for (auto &LIAndVNI : CopyValues[LocNo]) {
1081fe6060f1SDimitry Andric       LiveInterval *DstLI = LIAndVNI.first;
1082fe6060f1SDimitry Andric       const VNInfo *DstVNI = LIAndVNI.second;
1083fe6060f1SDimitry Andric       if (DstLI->getVNInfoAt(KilledAt) != DstVNI)
10840b57cec5SDimitry Andric         continue;
1085fe6060f1SDimitry Andric       LLVM_DEBUG(dbgs() << "Kill at " << KilledAt << " covered by valno #"
10860b57cec5SDimitry Andric                         << DstVNI->id << " in " << *DstLI << '\n');
10870b57cec5SDimitry Andric       MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
10880b57cec5SDimitry Andric       assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
1089fe6060f1SDimitry Andric       unsigned NewLocNo = getLocationNo(CopyMI->getOperand(0));
1090fe6060f1SDimitry Andric       NewValue = NewValue.changeLocNo(LocNo, NewLocNo);
1091fe6060f1SDimitry Andric       FoundCopy = true;
10920b57cec5SDimitry Andric       break;
10930b57cec5SDimitry Andric     }
1094fe6060f1SDimitry Andric     // If there are any killed locations we can't find a copy for, we can't
1095fe6060f1SDimitry Andric     // extend the variable value.
1096fe6060f1SDimitry Andric     if (!FoundCopy)
1097fe6060f1SDimitry Andric       return;
10980b57cec5SDimitry Andric   }
1099fe6060f1SDimitry Andric   I.insert(KilledAt, KilledAt.getNextSlot(), NewValue);
1100fe6060f1SDimitry Andric   NewDefs.push_back(std::make_pair(KilledAt, NewValue));
11010b57cec5SDimitry Andric }
11020b57cec5SDimitry Andric 
computeIntervals(MachineRegisterInfo & MRI,const TargetRegisterInfo & TRI,LiveIntervals & LIS,LexicalScopes & LS)11030b57cec5SDimitry Andric void UserValue::computeIntervals(MachineRegisterInfo &MRI,
11040b57cec5SDimitry Andric                                  const TargetRegisterInfo &TRI,
11050b57cec5SDimitry Andric                                  LiveIntervals &LIS, LexicalScopes &LS) {
11065ffd83dbSDimitry Andric   SmallVector<std::pair<SlotIndex, DbgVariableValue>, 16> Defs;
11070b57cec5SDimitry Andric 
11080b57cec5SDimitry Andric   // Collect all defs to be extended (Skipping undefs).
11090b57cec5SDimitry Andric   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
11100b57cec5SDimitry Andric     if (!I.value().isUndef())
11110b57cec5SDimitry Andric       Defs.push_back(std::make_pair(I.start(), I.value()));
11120b57cec5SDimitry Andric 
11130b57cec5SDimitry Andric   // Extend all defs, and possibly add new ones along the way.
11140b57cec5SDimitry Andric   for (unsigned i = 0; i != Defs.size(); ++i) {
11150b57cec5SDimitry Andric     SlotIndex Idx = Defs[i].first;
11165ffd83dbSDimitry Andric     DbgVariableValue DbgValue = Defs[i].second;
1117fe6060f1SDimitry Andric     SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>> LIs;
1118fe6060f1SDimitry Andric     SmallVector<const VNInfo *, 4> VNIs;
1119fe6060f1SDimitry Andric     bool ShouldExtendDef = false;
1120fe6060f1SDimitry Andric     for (unsigned LocNo : DbgValue.loc_nos()) {
1121fe6060f1SDimitry Andric       const MachineOperand &LocMO = locations[LocNo];
1122bdd1243dSDimitry Andric       if (!LocMO.isReg() || !LocMO.getReg().isVirtual()) {
1123fe6060f1SDimitry Andric         ShouldExtendDef |= !LocMO.isReg();
11240b57cec5SDimitry Andric         continue;
11250b57cec5SDimitry Andric       }
1126fe6060f1SDimitry Andric       ShouldExtendDef = true;
11270b57cec5SDimitry Andric       LiveInterval *LI = nullptr;
11280b57cec5SDimitry Andric       const VNInfo *VNI = nullptr;
11290b57cec5SDimitry Andric       if (LIS.hasInterval(LocMO.getReg())) {
11300b57cec5SDimitry Andric         LI = &LIS.getInterval(LocMO.getReg());
11310b57cec5SDimitry Andric         VNI = LI->getVNInfoAt(Idx);
11320b57cec5SDimitry Andric       }
1133fe6060f1SDimitry Andric       if (LI && VNI)
1134fe6060f1SDimitry Andric         LIs[LocNo] = {LI, VNI};
1135fe6060f1SDimitry Andric     }
1136fe6060f1SDimitry Andric     if (ShouldExtendDef) {
1137bdd1243dSDimitry Andric       std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> Kills;
1138fe6060f1SDimitry Andric       extendDef(Idx, DbgValue, LIs, Kills, LIS);
1139fe6060f1SDimitry Andric 
1140fe6060f1SDimitry Andric       if (Kills) {
1141fe6060f1SDimitry Andric         SmallVector<std::pair<unsigned, LiveInterval *>, 2> KilledLocIntervals;
1142fe6060f1SDimitry Andric         bool AnySubreg = false;
1143fe6060f1SDimitry Andric         for (unsigned LocNo : Kills->second) {
1144fe6060f1SDimitry Andric           const MachineOperand &LocMO = this->locations[LocNo];
1145fe6060f1SDimitry Andric           if (LocMO.getSubReg()) {
1146fe6060f1SDimitry Andric             AnySubreg = true;
1147fe6060f1SDimitry Andric             break;
1148fe6060f1SDimitry Andric           }
1149fe6060f1SDimitry Andric           LiveInterval *LI = &LIS.getInterval(LocMO.getReg());
1150fe6060f1SDimitry Andric           KilledLocIntervals.push_back({LocNo, LI});
1151fe6060f1SDimitry Andric         }
1152fe6060f1SDimitry Andric 
11530b57cec5SDimitry Andric         // FIXME: Handle sub-registers in addDefsFromCopies. The problem is that
11540b57cec5SDimitry Andric         // if the original location for example is %vreg0:sub_hi, and we find a
1155fe6060f1SDimitry Andric         // full register copy in addDefsFromCopies (at the moment it only
1156fe6060f1SDimitry Andric         // handles full register copies), then we must add the sub1 sub-register
1157fe6060f1SDimitry Andric         // index to the new location. However, that is only possible if the new
1158fe6060f1SDimitry Andric         // virtual register is of the same regclass (or if there is an
1159fe6060f1SDimitry Andric         // equivalent sub-register in that regclass). For now, simply skip
1160fe6060f1SDimitry Andric         // handling copies if a sub-register is involved.
1161fe6060f1SDimitry Andric         if (!AnySubreg)
1162fe6060f1SDimitry Andric           addDefsFromCopies(DbgValue, KilledLocIntervals, Kills->first, Defs,
1163fe6060f1SDimitry Andric                             MRI, LIS);
1164fe6060f1SDimitry Andric       }
11650b57cec5SDimitry Andric     }
11660b57cec5SDimitry Andric 
11670b57cec5SDimitry Andric     // For physregs, we only mark the start slot idx. DwarfDebug will see it
11680b57cec5SDimitry Andric     // as if the DBG_VALUE is valid up until the end of the basic block, or
11690b57cec5SDimitry Andric     // the next def of the physical register. So we do not need to extend the
11700b57cec5SDimitry Andric     // range. It might actually happen that the DBG_VALUE is the last use of
11710b57cec5SDimitry Andric     // the physical register (e.g. if this is an unused input argument to a
11720b57cec5SDimitry Andric     // function).
11730b57cec5SDimitry Andric   }
11740b57cec5SDimitry Andric 
11750b57cec5SDimitry Andric   // The computed intervals may extend beyond the range of the debug
11760b57cec5SDimitry Andric   // location's lexical scope. In this case, splitting of an interval
11770b57cec5SDimitry Andric   // can result in an interval outside of the scope being created,
11780b57cec5SDimitry Andric   // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
1179fe6060f1SDimitry Andric   // this, trim the intervals to the lexical scope in the case of inlined
1180fe6060f1SDimitry Andric   // variables, since heavy inlining may cause production of dramatically big
1181fe6060f1SDimitry Andric   // number of DBG_VALUEs to be generated.
1182fe6060f1SDimitry Andric   if (!dl.getInlinedAt())
1183fe6060f1SDimitry Andric     return;
11840b57cec5SDimitry Andric 
11850b57cec5SDimitry Andric   LexicalScope *Scope = LS.findLexicalScope(dl);
11860b57cec5SDimitry Andric   if (!Scope)
11870b57cec5SDimitry Andric     return;
11880b57cec5SDimitry Andric 
11890b57cec5SDimitry Andric   SlotIndex PrevEnd;
11900b57cec5SDimitry Andric   LocMap::iterator I = locInts.begin();
11910b57cec5SDimitry Andric 
11920b57cec5SDimitry Andric   // Iterate over the lexical scope ranges. Each time round the loop
11930b57cec5SDimitry Andric   // we check the intervals for overlap with the end of the previous
11940b57cec5SDimitry Andric   // range and the start of the next. The first range is handled as
11950b57cec5SDimitry Andric   // a special case where there is no PrevEnd.
11960b57cec5SDimitry Andric   for (const InsnRange &Range : Scope->getRanges()) {
11970b57cec5SDimitry Andric     SlotIndex RStart = LIS.getInstructionIndex(*Range.first);
11980b57cec5SDimitry Andric     SlotIndex REnd = LIS.getInstructionIndex(*Range.second);
11990b57cec5SDimitry Andric 
120013138422SDimitry Andric     // Variable locations at the first instruction of a block should be
120113138422SDimitry Andric     // based on the block's SlotIndex, not the first instruction's index.
120213138422SDimitry Andric     if (Range.first == Range.first->getParent()->begin())
120313138422SDimitry Andric       RStart = LIS.getSlotIndexes()->getIndexBefore(*Range.first);
120413138422SDimitry Andric 
12050b57cec5SDimitry Andric     // At the start of each iteration I has been advanced so that
12060b57cec5SDimitry Andric     // I.stop() >= PrevEnd. Check for overlap.
12070b57cec5SDimitry Andric     if (PrevEnd && I.start() < PrevEnd) {
12080b57cec5SDimitry Andric       SlotIndex IStop = I.stop();
12095ffd83dbSDimitry Andric       DbgVariableValue DbgValue = I.value();
12100b57cec5SDimitry Andric 
12110b57cec5SDimitry Andric       // Stop overlaps previous end - trim the end of the interval to
12120b57cec5SDimitry Andric       // the scope range.
12130b57cec5SDimitry Andric       I.setStopUnchecked(PrevEnd);
12140b57cec5SDimitry Andric       ++I;
12150b57cec5SDimitry Andric 
12160b57cec5SDimitry Andric       // If the interval also overlaps the start of the "next" (i.e.
121713138422SDimitry Andric       // current) range create a new interval for the remainder (which
121813138422SDimitry Andric       // may be further trimmed).
12190b57cec5SDimitry Andric       if (RStart < IStop)
12205ffd83dbSDimitry Andric         I.insert(RStart, IStop, DbgValue);
12210b57cec5SDimitry Andric     }
12220b57cec5SDimitry Andric 
12230b57cec5SDimitry Andric     // Advance I so that I.stop() >= RStart, and check for overlap.
12240b57cec5SDimitry Andric     I.advanceTo(RStart);
12250b57cec5SDimitry Andric     if (!I.valid())
12260b57cec5SDimitry Andric       return;
12270b57cec5SDimitry Andric 
122813138422SDimitry Andric     if (I.start() < RStart) {
122913138422SDimitry Andric       // Interval start overlaps range - trim to the scope range.
123013138422SDimitry Andric       I.setStartUnchecked(RStart);
123113138422SDimitry Andric       // Remember that this interval was trimmed.
123213138422SDimitry Andric       trimmedDefs.insert(RStart);
123313138422SDimitry Andric     }
123413138422SDimitry Andric 
12350b57cec5SDimitry Andric     // The end of a lexical scope range is the last instruction in the
12360b57cec5SDimitry Andric     // range. To convert to an interval we need the index of the
12370b57cec5SDimitry Andric     // instruction after it.
12380b57cec5SDimitry Andric     REnd = REnd.getNextIndex();
12390b57cec5SDimitry Andric 
12400b57cec5SDimitry Andric     // Advance I to first interval outside current range.
12410b57cec5SDimitry Andric     I.advanceTo(REnd);
12420b57cec5SDimitry Andric     if (!I.valid())
12430b57cec5SDimitry Andric       return;
12440b57cec5SDimitry Andric 
12450b57cec5SDimitry Andric     PrevEnd = REnd;
12460b57cec5SDimitry Andric   }
12470b57cec5SDimitry Andric 
12480b57cec5SDimitry Andric   // Check for overlap with end of final range.
12490b57cec5SDimitry Andric   if (PrevEnd && I.start() < PrevEnd)
12500b57cec5SDimitry Andric     I.setStopUnchecked(PrevEnd);
12510b57cec5SDimitry Andric }
12520b57cec5SDimitry Andric 
computeIntervals()12530b57cec5SDimitry Andric void LDVImpl::computeIntervals() {
12540b57cec5SDimitry Andric   LexicalScopes LS;
12550b57cec5SDimitry Andric   LS.initialize(*MF);
12560b57cec5SDimitry Andric 
12570b57cec5SDimitry Andric   for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
12580b57cec5SDimitry Andric     userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS);
12590b57cec5SDimitry Andric     userValues[i]->mapVirtRegs(this);
12600b57cec5SDimitry Andric   }
12610b57cec5SDimitry Andric }
12620b57cec5SDimitry Andric 
runOnMachineFunction(MachineFunction & mf,bool InstrRef)1263fe6060f1SDimitry Andric bool LDVImpl::runOnMachineFunction(MachineFunction &mf, bool InstrRef) {
12640b57cec5SDimitry Andric   clear();
12650b57cec5SDimitry Andric   MF = &mf;
12660b57cec5SDimitry Andric   LIS = &pass.getAnalysis<LiveIntervals>();
12670b57cec5SDimitry Andric   TRI = mf.getSubtarget().getRegisterInfo();
12680b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
12690b57cec5SDimitry Andric                     << mf.getName() << " **********\n");
12700b57cec5SDimitry Andric 
1271fe6060f1SDimitry Andric   bool Changed = collectDebugValues(mf, InstrRef);
12720b57cec5SDimitry Andric   computeIntervals();
12730b57cec5SDimitry Andric   LLVM_DEBUG(print(dbgs()));
1274fe6060f1SDimitry Andric 
1275fe6060f1SDimitry Andric   // Collect the set of VReg / SlotIndexs where PHIs occur; index the sensitive
1276fe6060f1SDimitry Andric   // VRegs too, for when we're notified of a range split.
1277fe6060f1SDimitry Andric   SlotIndexes *Slots = LIS->getSlotIndexes();
1278fe6060f1SDimitry Andric   for (const auto &PHIIt : MF->DebugPHIPositions) {
1279fe6060f1SDimitry Andric     const MachineFunction::DebugPHIRegallocPos &Position = PHIIt.second;
1280fe6060f1SDimitry Andric     MachineBasicBlock *MBB = Position.MBB;
1281fe6060f1SDimitry Andric     Register Reg = Position.Reg;
1282fe6060f1SDimitry Andric     unsigned SubReg = Position.SubReg;
1283fe6060f1SDimitry Andric     SlotIndex SI = Slots->getMBBStartIdx(MBB);
1284fe6060f1SDimitry Andric     PHIValPos VP = {SI, Reg, SubReg};
1285fe6060f1SDimitry Andric     PHIValToPos.insert(std::make_pair(PHIIt.first, VP));
1286fe6060f1SDimitry Andric     RegToPHIIdx[Reg].push_back(PHIIt.first);
1287fe6060f1SDimitry Andric   }
1288fe6060f1SDimitry Andric 
12890b57cec5SDimitry Andric   ModifiedMF = Changed;
12900b57cec5SDimitry Andric   return Changed;
12910b57cec5SDimitry Andric }
12920b57cec5SDimitry Andric 
removeDebugInstrs(MachineFunction & mf)1293e8d8bef9SDimitry Andric static void removeDebugInstrs(MachineFunction &mf) {
12940b57cec5SDimitry Andric   for (MachineBasicBlock &MBB : mf) {
1295349cc55cSDimitry Andric     for (MachineInstr &MI : llvm::make_early_inc_range(MBB))
1296349cc55cSDimitry Andric       if (MI.isDebugInstr())
1297349cc55cSDimitry Andric         MBB.erase(&MI);
12980b57cec5SDimitry Andric   }
12990b57cec5SDimitry Andric }
13000b57cec5SDimitry Andric 
runOnMachineFunction(MachineFunction & mf)13010b57cec5SDimitry Andric bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
13020b57cec5SDimitry Andric   if (!EnableLDV)
13030b57cec5SDimitry Andric     return false;
13040b57cec5SDimitry Andric   if (!mf.getFunction().getSubprogram()) {
1305e8d8bef9SDimitry Andric     removeDebugInstrs(mf);
13060b57cec5SDimitry Andric     return false;
13070b57cec5SDimitry Andric   }
1308fe6060f1SDimitry Andric 
1309fe6060f1SDimitry Andric   // Have we been asked to track variable locations using instruction
1310fe6060f1SDimitry Andric   // referencing?
1311349cc55cSDimitry Andric   bool InstrRef = mf.useDebugInstrRef();
1312fe6060f1SDimitry Andric 
13130b57cec5SDimitry Andric   if (!pImpl)
13140b57cec5SDimitry Andric     pImpl = new LDVImpl(this);
1315fe6060f1SDimitry Andric   return static_cast<LDVImpl *>(pImpl)->runOnMachineFunction(mf, InstrRef);
13160b57cec5SDimitry Andric }
13170b57cec5SDimitry Andric 
releaseMemory()13180b57cec5SDimitry Andric void LiveDebugVariables::releaseMemory() {
13190b57cec5SDimitry Andric   if (pImpl)
13200b57cec5SDimitry Andric     static_cast<LDVImpl*>(pImpl)->clear();
13210b57cec5SDimitry Andric }
13220b57cec5SDimitry Andric 
~LiveDebugVariables()13230b57cec5SDimitry Andric LiveDebugVariables::~LiveDebugVariables() {
13240b57cec5SDimitry Andric   if (pImpl)
13250b57cec5SDimitry Andric     delete static_cast<LDVImpl*>(pImpl);
13260b57cec5SDimitry Andric }
13270b57cec5SDimitry Andric 
13280b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13290b57cec5SDimitry Andric //                           Live Range Splitting
13300b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13310b57cec5SDimitry Andric 
13320b57cec5SDimitry Andric bool
splitLocation(unsigned OldLocNo,ArrayRef<Register> NewRegs,LiveIntervals & LIS)13335ffd83dbSDimitry Andric UserValue::splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs,
13340b57cec5SDimitry Andric                          LiveIntervals& LIS) {
13350b57cec5SDimitry Andric   LLVM_DEBUG({
13360b57cec5SDimitry Andric     dbgs() << "Splitting Loc" << OldLocNo << '\t';
13370b57cec5SDimitry Andric     print(dbgs(), nullptr);
13380b57cec5SDimitry Andric   });
13390b57cec5SDimitry Andric   bool DidChange = false;
13400b57cec5SDimitry Andric   LocMap::iterator LocMapI;
13410b57cec5SDimitry Andric   LocMapI.setMap(locInts);
13420eae32dcSDimitry Andric   for (Register NewReg : NewRegs) {
13430eae32dcSDimitry Andric     LiveInterval *LI = &LIS.getInterval(NewReg);
13440b57cec5SDimitry Andric     if (LI->empty())
13450b57cec5SDimitry Andric       continue;
13460b57cec5SDimitry Andric 
13470b57cec5SDimitry Andric     // Don't allocate the new LocNo until it is needed.
13480b57cec5SDimitry Andric     unsigned NewLocNo = UndefLocNo;
13490b57cec5SDimitry Andric 
13500b57cec5SDimitry Andric     // Iterate over the overlaps between locInts and LI.
13510b57cec5SDimitry Andric     LocMapI.find(LI->beginIndex());
13520b57cec5SDimitry Andric     if (!LocMapI.valid())
13530b57cec5SDimitry Andric       continue;
13540b57cec5SDimitry Andric     LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
13550b57cec5SDimitry Andric     LiveInterval::iterator LIE = LI->end();
13560b57cec5SDimitry Andric     while (LocMapI.valid() && LII != LIE) {
13570b57cec5SDimitry Andric       // At this point, we know that LocMapI.stop() > LII->start.
13580b57cec5SDimitry Andric       LII = LI->advanceTo(LII, LocMapI.start());
13590b57cec5SDimitry Andric       if (LII == LIE)
13600b57cec5SDimitry Andric         break;
13610b57cec5SDimitry Andric 
13620b57cec5SDimitry Andric       // Now LII->end > LocMapI.start(). Do we have an overlap?
1363fe6060f1SDimitry Andric       if (LocMapI.value().containsLocNo(OldLocNo) &&
13645ffd83dbSDimitry Andric           LII->start < LocMapI.stop()) {
13650b57cec5SDimitry Andric         // Overlapping correct location. Allocate NewLocNo now.
13660b57cec5SDimitry Andric         if (NewLocNo == UndefLocNo) {
1367e8d8bef9SDimitry Andric           MachineOperand MO = MachineOperand::CreateReg(LI->reg(), false);
13680b57cec5SDimitry Andric           MO.setSubReg(locations[OldLocNo].getSubReg());
13690b57cec5SDimitry Andric           NewLocNo = getLocationNo(MO);
13700b57cec5SDimitry Andric           DidChange = true;
13710b57cec5SDimitry Andric         }
13720b57cec5SDimitry Andric 
13730b57cec5SDimitry Andric         SlotIndex LStart = LocMapI.start();
13740b57cec5SDimitry Andric         SlotIndex LStop = LocMapI.stop();
13755ffd83dbSDimitry Andric         DbgVariableValue OldDbgValue = LocMapI.value();
13760b57cec5SDimitry Andric 
13770b57cec5SDimitry Andric         // Trim LocMapI down to the LII overlap.
13780b57cec5SDimitry Andric         if (LStart < LII->start)
13790b57cec5SDimitry Andric           LocMapI.setStartUnchecked(LII->start);
13800b57cec5SDimitry Andric         if (LStop > LII->end)
13810b57cec5SDimitry Andric           LocMapI.setStopUnchecked(LII->end);
13820b57cec5SDimitry Andric 
13830b57cec5SDimitry Andric         // Change the value in the overlap. This may trigger coalescing.
1384fe6060f1SDimitry Andric         LocMapI.setValue(OldDbgValue.changeLocNo(OldLocNo, NewLocNo));
13850b57cec5SDimitry Andric 
13865ffd83dbSDimitry Andric         // Re-insert any removed OldDbgValue ranges.
13870b57cec5SDimitry Andric         if (LStart < LocMapI.start()) {
13885ffd83dbSDimitry Andric           LocMapI.insert(LStart, LocMapI.start(), OldDbgValue);
13890b57cec5SDimitry Andric           ++LocMapI;
13900b57cec5SDimitry Andric           assert(LocMapI.valid() && "Unexpected coalescing");
13910b57cec5SDimitry Andric         }
13920b57cec5SDimitry Andric         if (LStop > LocMapI.stop()) {
13930b57cec5SDimitry Andric           ++LocMapI;
13945ffd83dbSDimitry Andric           LocMapI.insert(LII->end, LStop, OldDbgValue);
13950b57cec5SDimitry Andric           --LocMapI;
13960b57cec5SDimitry Andric         }
13970b57cec5SDimitry Andric       }
13980b57cec5SDimitry Andric 
13990b57cec5SDimitry Andric       // Advance to the next overlap.
14000b57cec5SDimitry Andric       if (LII->end < LocMapI.stop()) {
14010b57cec5SDimitry Andric         if (++LII == LIE)
14020b57cec5SDimitry Andric           break;
14030b57cec5SDimitry Andric         LocMapI.advanceTo(LII->start);
14040b57cec5SDimitry Andric       } else {
14050b57cec5SDimitry Andric         ++LocMapI;
14060b57cec5SDimitry Andric         if (!LocMapI.valid())
14070b57cec5SDimitry Andric           break;
14080b57cec5SDimitry Andric         LII = LI->advanceTo(LII, LocMapI.start());
14090b57cec5SDimitry Andric       }
14100b57cec5SDimitry Andric     }
14110b57cec5SDimitry Andric   }
14120b57cec5SDimitry Andric 
1413480093f4SDimitry Andric   // Finally, remove OldLocNo unless it is still used by some interval in the
1414480093f4SDimitry Andric   // locInts map. One case when OldLocNo still is in use is when the register
1415480093f4SDimitry Andric   // has been spilled. In such situations the spilled register is kept as a
1416480093f4SDimitry Andric   // location until rewriteLocations is called (VirtRegMap is mapping the old
1417480093f4SDimitry Andric   // register to the spill slot). So for a while we can have locations that map
1418480093f4SDimitry Andric   // to virtual registers that have been removed from both the MachineFunction
1419480093f4SDimitry Andric   // and from LiveIntervals.
14205ffd83dbSDimitry Andric   //
14215ffd83dbSDimitry Andric   // We may also just be using the location for a value with a different
14225ffd83dbSDimitry Andric   // expression.
1423480093f4SDimitry Andric   removeLocationIfUnused(OldLocNo);
14240b57cec5SDimitry Andric 
14250b57cec5SDimitry Andric   LLVM_DEBUG({
14260b57cec5SDimitry Andric     dbgs() << "Split result: \t";
14270b57cec5SDimitry Andric     print(dbgs(), nullptr);
14280b57cec5SDimitry Andric   });
14290b57cec5SDimitry Andric   return DidChange;
14300b57cec5SDimitry Andric }
14310b57cec5SDimitry Andric 
14320b57cec5SDimitry Andric bool
splitRegister(Register OldReg,ArrayRef<Register> NewRegs,LiveIntervals & LIS)14335ffd83dbSDimitry Andric UserValue::splitRegister(Register OldReg, ArrayRef<Register> NewRegs,
14340b57cec5SDimitry Andric                          LiveIntervals &LIS) {
14350b57cec5SDimitry Andric   bool DidChange = false;
14360b57cec5SDimitry Andric   // Split locations referring to OldReg. Iterate backwards so splitLocation can
14370b57cec5SDimitry Andric   // safely erase unused locations.
14380b57cec5SDimitry Andric   for (unsigned i = locations.size(); i ; --i) {
14390b57cec5SDimitry Andric     unsigned LocNo = i-1;
14400b57cec5SDimitry Andric     const MachineOperand *Loc = &locations[LocNo];
14410b57cec5SDimitry Andric     if (!Loc->isReg() || Loc->getReg() != OldReg)
14420b57cec5SDimitry Andric       continue;
14430b57cec5SDimitry Andric     DidChange |= splitLocation(LocNo, NewRegs, LIS);
14440b57cec5SDimitry Andric   }
14450b57cec5SDimitry Andric   return DidChange;
14460b57cec5SDimitry Andric }
14470b57cec5SDimitry Andric 
splitPHIRegister(Register OldReg,ArrayRef<Register> NewRegs)1448fe6060f1SDimitry Andric void LDVImpl::splitPHIRegister(Register OldReg, ArrayRef<Register> NewRegs) {
1449fe6060f1SDimitry Andric   auto RegIt = RegToPHIIdx.find(OldReg);
1450fe6060f1SDimitry Andric   if (RegIt == RegToPHIIdx.end())
1451fe6060f1SDimitry Andric     return;
1452fe6060f1SDimitry Andric 
1453fe6060f1SDimitry Andric   std::vector<std::pair<Register, unsigned>> NewRegIdxes;
1454fe6060f1SDimitry Andric   // Iterate over all the debug instruction numbers affected by this split.
1455fe6060f1SDimitry Andric   for (unsigned InstrID : RegIt->second) {
1456fe6060f1SDimitry Andric     auto PHIIt = PHIValToPos.find(InstrID);
1457fe6060f1SDimitry Andric     assert(PHIIt != PHIValToPos.end());
1458fe6060f1SDimitry Andric     const SlotIndex &Slot = PHIIt->second.SI;
1459fe6060f1SDimitry Andric     assert(OldReg == PHIIt->second.Reg);
1460fe6060f1SDimitry Andric 
1461fe6060f1SDimitry Andric     // Find the new register that covers this position.
1462fe6060f1SDimitry Andric     for (auto NewReg : NewRegs) {
1463fe6060f1SDimitry Andric       const LiveInterval &LI = LIS->getInterval(NewReg);
1464fe6060f1SDimitry Andric       auto LII = LI.find(Slot);
1465fe6060f1SDimitry Andric       if (LII != LI.end() && LII->start <= Slot) {
1466fe6060f1SDimitry Andric         // This new register covers this PHI position, record this for indexing.
1467fe6060f1SDimitry Andric         NewRegIdxes.push_back(std::make_pair(NewReg, InstrID));
1468fe6060f1SDimitry Andric         // Record that this value lives in a different VReg now.
1469fe6060f1SDimitry Andric         PHIIt->second.Reg = NewReg;
1470fe6060f1SDimitry Andric         break;
1471fe6060f1SDimitry Andric       }
1472fe6060f1SDimitry Andric     }
1473fe6060f1SDimitry Andric 
1474fe6060f1SDimitry Andric     // If we do not find a new register covering this PHI, then register
1475fe6060f1SDimitry Andric     // allocation has dropped its location, for example because it's not live.
1476fe6060f1SDimitry Andric     // The old VReg will not be mapped to a physreg, and the instruction
1477fe6060f1SDimitry Andric     // number will have been optimized out.
1478fe6060f1SDimitry Andric   }
1479fe6060f1SDimitry Andric 
1480fe6060f1SDimitry Andric   // Re-create register index using the new register numbers.
1481fe6060f1SDimitry Andric   RegToPHIIdx.erase(RegIt);
1482fe6060f1SDimitry Andric   for (auto &RegAndInstr : NewRegIdxes)
1483fe6060f1SDimitry Andric     RegToPHIIdx[RegAndInstr.first].push_back(RegAndInstr.second);
1484fe6060f1SDimitry Andric }
1485fe6060f1SDimitry Andric 
splitRegister(Register OldReg,ArrayRef<Register> NewRegs)14865ffd83dbSDimitry Andric void LDVImpl::splitRegister(Register OldReg, ArrayRef<Register> NewRegs) {
1487fe6060f1SDimitry Andric   // Consider whether this split range affects any PHI locations.
1488fe6060f1SDimitry Andric   splitPHIRegister(OldReg, NewRegs);
1489fe6060f1SDimitry Andric 
1490fe6060f1SDimitry Andric   // Check whether any intervals mapped by a DBG_VALUE were split and need
1491fe6060f1SDimitry Andric   // updating.
14920b57cec5SDimitry Andric   bool DidChange = false;
1493480093f4SDimitry Andric   for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
14940b57cec5SDimitry Andric     DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
14950b57cec5SDimitry Andric 
14960b57cec5SDimitry Andric   if (!DidChange)
14970b57cec5SDimitry Andric     return;
14980b57cec5SDimitry Andric 
14990b57cec5SDimitry Andric   // Map all of the new virtual registers.
1500480093f4SDimitry Andric   UserValue *UV = lookupVirtReg(OldReg);
15010eae32dcSDimitry Andric   for (Register NewReg : NewRegs)
15020eae32dcSDimitry Andric     mapVirtReg(NewReg, UV);
15030b57cec5SDimitry Andric }
15040b57cec5SDimitry Andric 
15050b57cec5SDimitry Andric void LiveDebugVariables::
splitRegister(Register OldReg,ArrayRef<Register> NewRegs,LiveIntervals & LIS)15065ffd83dbSDimitry Andric splitRegister(Register OldReg, ArrayRef<Register> NewRegs, LiveIntervals &LIS) {
15070b57cec5SDimitry Andric   if (pImpl)
15080b57cec5SDimitry Andric     static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
15090b57cec5SDimitry Andric }
15100b57cec5SDimitry Andric 
rewriteLocations(VirtRegMap & VRM,const MachineFunction & MF,const TargetInstrInfo & TII,const TargetRegisterInfo & TRI,SpillOffsetMap & SpillOffsets)15110b57cec5SDimitry Andric void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
15120b57cec5SDimitry Andric                                  const TargetInstrInfo &TII,
15130b57cec5SDimitry Andric                                  const TargetRegisterInfo &TRI,
15140b57cec5SDimitry Andric                                  SpillOffsetMap &SpillOffsets) {
15150b57cec5SDimitry Andric   // Build a set of new locations with new numbers so we can coalesce our
15160b57cec5SDimitry Andric   // IntervalMap if two vreg intervals collapse to the same physical location.
15170b57cec5SDimitry Andric   // Use MapVector instead of SetVector because MapVector::insert returns the
15180b57cec5SDimitry Andric   // position of the previously or newly inserted element. The boolean value
15190b57cec5SDimitry Andric   // tracks if the location was produced by a spill.
15200b57cec5SDimitry Andric   // FIXME: This will be problematic if we ever support direct and indirect
15210b57cec5SDimitry Andric   // frame index locations, i.e. expressing both variables in memory and
15220b57cec5SDimitry Andric   // 'int x, *px = &x'. The "spilled" bit must become part of the location.
15230b57cec5SDimitry Andric   MapVector<MachineOperand, std::pair<bool, unsigned>> NewLocations;
15240b57cec5SDimitry Andric   SmallVector<unsigned, 4> LocNoMap(locations.size());
15250b57cec5SDimitry Andric   for (unsigned I = 0, E = locations.size(); I != E; ++I) {
15260b57cec5SDimitry Andric     bool Spilled = false;
15270b57cec5SDimitry Andric     unsigned SpillOffset = 0;
15280b57cec5SDimitry Andric     MachineOperand Loc = locations[I];
15290b57cec5SDimitry Andric     // Only virtual registers are rewritten.
1530bdd1243dSDimitry Andric     if (Loc.isReg() && Loc.getReg() && Loc.getReg().isVirtual()) {
15318bcb0991SDimitry Andric       Register VirtReg = Loc.getReg();
15320b57cec5SDimitry Andric       if (VRM.isAssignedReg(VirtReg) &&
15338bcb0991SDimitry Andric           Register::isPhysicalRegister(VRM.getPhys(VirtReg))) {
15340b57cec5SDimitry Andric         // This can create a %noreg operand in rare cases when the sub-register
15350b57cec5SDimitry Andric         // index is no longer available. That means the user value is in a
15360b57cec5SDimitry Andric         // non-existent sub-register, and %noreg is exactly what we want.
15370b57cec5SDimitry Andric         Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
15380b57cec5SDimitry Andric       } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
15390b57cec5SDimitry Andric         // Retrieve the stack slot offset.
15400b57cec5SDimitry Andric         unsigned SpillSize;
15410b57cec5SDimitry Andric         const MachineRegisterInfo &MRI = MF.getRegInfo();
15420b57cec5SDimitry Andric         const TargetRegisterClass *TRC = MRI.getRegClass(VirtReg);
15430b57cec5SDimitry Andric         bool Success = TII.getStackSlotRange(TRC, Loc.getSubReg(), SpillSize,
15440b57cec5SDimitry Andric                                              SpillOffset, MF);
15450b57cec5SDimitry Andric 
15460b57cec5SDimitry Andric         // FIXME: Invalidate the location if the offset couldn't be calculated.
15470b57cec5SDimitry Andric         (void)Success;
15480b57cec5SDimitry Andric 
15490b57cec5SDimitry Andric         Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
15500b57cec5SDimitry Andric         Spilled = true;
15510b57cec5SDimitry Andric       } else {
15520b57cec5SDimitry Andric         Loc.setReg(0);
15530b57cec5SDimitry Andric         Loc.setSubReg(0);
15540b57cec5SDimitry Andric       }
15550b57cec5SDimitry Andric     }
15560b57cec5SDimitry Andric 
15570b57cec5SDimitry Andric     // Insert this location if it doesn't already exist and record a mapping
15580b57cec5SDimitry Andric     // from the old number to the new number.
15590b57cec5SDimitry Andric     auto InsertResult = NewLocations.insert({Loc, {Spilled, SpillOffset}});
15600b57cec5SDimitry Andric     unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first);
15610b57cec5SDimitry Andric     LocNoMap[I] = NewLocNo;
15620b57cec5SDimitry Andric   }
15630b57cec5SDimitry Andric 
15640b57cec5SDimitry Andric   // Rewrite the locations and record the stack slot offsets for spills.
15650b57cec5SDimitry Andric   locations.clear();
15660b57cec5SDimitry Andric   SpillOffsets.clear();
15670b57cec5SDimitry Andric   for (auto &Pair : NewLocations) {
15680b57cec5SDimitry Andric     bool Spilled;
15690b57cec5SDimitry Andric     unsigned SpillOffset;
15700b57cec5SDimitry Andric     std::tie(Spilled, SpillOffset) = Pair.second;
15710b57cec5SDimitry Andric     locations.push_back(Pair.first);
15720b57cec5SDimitry Andric     if (Spilled) {
15730b57cec5SDimitry Andric       unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair);
15740b57cec5SDimitry Andric       SpillOffsets[NewLocNo] = SpillOffset;
15750b57cec5SDimitry Andric     }
15760b57cec5SDimitry Andric   }
15770b57cec5SDimitry Andric 
15780b57cec5SDimitry Andric   // Update the interval map, but only coalesce left, since intervals to the
15790b57cec5SDimitry Andric   // right use the old location numbers. This should merge two contiguous
15800b57cec5SDimitry Andric   // DBG_VALUE intervals with different vregs that were allocated to the same
15810b57cec5SDimitry Andric   // physical register.
15820b57cec5SDimitry Andric   for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
1583fe6060f1SDimitry Andric     I.setValueUnchecked(I.value().remapLocNos(LocNoMap));
15840b57cec5SDimitry Andric     I.setStart(I.start());
15850b57cec5SDimitry Andric   }
15860b57cec5SDimitry Andric }
15870b57cec5SDimitry Andric 
15880b57cec5SDimitry Andric /// Find an iterator for inserting a DBG_VALUE instruction.
15890b57cec5SDimitry Andric static MachineBasicBlock::iterator
findInsertLocation(MachineBasicBlock * MBB,SlotIndex Idx,LiveIntervals & LIS,BlockSkipInstsMap & BBSkipInstsMap)1590fe6060f1SDimitry Andric findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx, LiveIntervals &LIS,
1591fe6060f1SDimitry Andric                    BlockSkipInstsMap &BBSkipInstsMap) {
15920b57cec5SDimitry Andric   SlotIndex Start = LIS.getMBBStartIdx(MBB);
15930b57cec5SDimitry Andric   Idx = Idx.getBaseIndex();
15940b57cec5SDimitry Andric 
15950b57cec5SDimitry Andric   // Try to find an insert location by going backwards from Idx.
15960b57cec5SDimitry Andric   MachineInstr *MI;
15970b57cec5SDimitry Andric   while (!(MI = LIS.getInstructionFromIndex(Idx))) {
15980b57cec5SDimitry Andric     // We've reached the beginning of MBB.
15990b57cec5SDimitry Andric     if (Idx == Start) {
1600fe6060f1SDimitry Andric       // Retrieve the last PHI/Label/Debug location found when calling
1601fe6060f1SDimitry Andric       // SkipPHIsLabelsAndDebug last time. Start searching from there.
1602fe6060f1SDimitry Andric       //
1603fe6060f1SDimitry Andric       // Note the iterator kept in BBSkipInstsMap is one step back based
1604fe6060f1SDimitry Andric       // on the iterator returned by SkipPHIsLabelsAndDebug last time.
1605fe6060f1SDimitry Andric       // One exception is when SkipPHIsLabelsAndDebug returns MBB->begin(),
1606fe6060f1SDimitry Andric       // BBSkipInstsMap won't save it. This is to consider the case that
1607fe6060f1SDimitry Andric       // new instructions may be inserted at the beginning of MBB after
1608fe6060f1SDimitry Andric       // last call of SkipPHIsLabelsAndDebug. If we save MBB->begin() in
1609fe6060f1SDimitry Andric       // BBSkipInstsMap, after new non-phi/non-label/non-debug instructions
1610fe6060f1SDimitry Andric       // are inserted at the beginning of the MBB, the iterator in
1611fe6060f1SDimitry Andric       // BBSkipInstsMap won't point to the beginning of the MBB anymore.
1612fe6060f1SDimitry Andric       // Therefore The next search in SkipPHIsLabelsAndDebug will skip those
1613fe6060f1SDimitry Andric       // newly added instructions and that is unwanted.
1614fe6060f1SDimitry Andric       MachineBasicBlock::iterator BeginIt;
1615fe6060f1SDimitry Andric       auto MapIt = BBSkipInstsMap.find(MBB);
1616fe6060f1SDimitry Andric       if (MapIt == BBSkipInstsMap.end())
1617fe6060f1SDimitry Andric         BeginIt = MBB->begin();
1618fe6060f1SDimitry Andric       else
1619fe6060f1SDimitry Andric         BeginIt = std::next(MapIt->second);
1620fe6060f1SDimitry Andric       auto I = MBB->SkipPHIsLabelsAndDebug(BeginIt);
1621fe6060f1SDimitry Andric       if (I != BeginIt)
1622fe6060f1SDimitry Andric         BBSkipInstsMap[MBB] = std::prev(I);
16230b57cec5SDimitry Andric       return I;
16240b57cec5SDimitry Andric     }
16250b57cec5SDimitry Andric     Idx = Idx.getPrevIndex();
16260b57cec5SDimitry Andric   }
16270b57cec5SDimitry Andric 
16280b57cec5SDimitry Andric   // Don't insert anything after the first terminator, though.
16290b57cec5SDimitry Andric   return MI->isTerminator() ? MBB->getFirstTerminator() :
16300b57cec5SDimitry Andric                               std::next(MachineBasicBlock::iterator(MI));
16310b57cec5SDimitry Andric }
16320b57cec5SDimitry Andric 
16330b57cec5SDimitry Andric /// Find an iterator for inserting the next DBG_VALUE instruction
16340b57cec5SDimitry Andric /// (or end if no more insert locations found).
16350b57cec5SDimitry Andric static MachineBasicBlock::iterator
findNextInsertLocation(MachineBasicBlock * MBB,MachineBasicBlock::iterator I,SlotIndex StopIdx,ArrayRef<MachineOperand> LocMOs,LiveIntervals & LIS,const TargetRegisterInfo & TRI)1636fe6060f1SDimitry Andric findNextInsertLocation(MachineBasicBlock *MBB, MachineBasicBlock::iterator I,
1637fe6060f1SDimitry Andric                        SlotIndex StopIdx, ArrayRef<MachineOperand> LocMOs,
1638fe6060f1SDimitry Andric                        LiveIntervals &LIS, const TargetRegisterInfo &TRI) {
1639fe6060f1SDimitry Andric   SmallVector<Register, 4> Regs;
1640fe6060f1SDimitry Andric   for (const MachineOperand &LocMO : LocMOs)
1641fe6060f1SDimitry Andric     if (LocMO.isReg())
1642fe6060f1SDimitry Andric       Regs.push_back(LocMO.getReg());
1643fe6060f1SDimitry Andric   if (Regs.empty())
16440b57cec5SDimitry Andric     return MBB->instr_end();
16450b57cec5SDimitry Andric 
16460b57cec5SDimitry Andric   // Find the next instruction in the MBB that define the register Reg.
16470b57cec5SDimitry Andric   while (I != MBB->end() && !I->isTerminator()) {
16480b57cec5SDimitry Andric     if (!LIS.isNotInMIMap(*I) &&
16490b57cec5SDimitry Andric         SlotIndex::isEarlierEqualInstr(StopIdx, LIS.getInstructionIndex(*I)))
16500b57cec5SDimitry Andric       break;
1651fe6060f1SDimitry Andric     if (any_of(Regs, [&I, &TRI](Register &Reg) {
1652fe6060f1SDimitry Andric           return I->definesRegister(Reg, &TRI);
1653fe6060f1SDimitry Andric         }))
16540b57cec5SDimitry Andric       // The insert location is directly after the instruction/bundle.
16550b57cec5SDimitry Andric       return std::next(I);
16560b57cec5SDimitry Andric     ++I;
16570b57cec5SDimitry Andric   }
16580b57cec5SDimitry Andric   return MBB->end();
16590b57cec5SDimitry Andric }
16600b57cec5SDimitry 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)16610b57cec5SDimitry Andric void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
16625ffd83dbSDimitry Andric                                  SlotIndex StopIdx, DbgVariableValue DbgValue,
1663fe6060f1SDimitry Andric                                  ArrayRef<bool> LocSpills,
1664fe6060f1SDimitry Andric                                  ArrayRef<unsigned> SpillOffsets,
16650b57cec5SDimitry Andric                                  LiveIntervals &LIS, const TargetInstrInfo &TII,
1666fe6060f1SDimitry Andric                                  const TargetRegisterInfo &TRI,
1667fe6060f1SDimitry Andric                                  BlockSkipInstsMap &BBSkipInstsMap) {
16680b57cec5SDimitry Andric   SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB);
16690b57cec5SDimitry Andric   // Only search within the current MBB.
16700b57cec5SDimitry Andric   StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx;
1671fe6060f1SDimitry Andric   MachineBasicBlock::iterator I =
1672fe6060f1SDimitry Andric       findInsertLocation(MBB, StartIdx, LIS, BBSkipInstsMap);
16730b57cec5SDimitry Andric   // Undef values don't exist in locations so create new "noreg" register MOs
16740b57cec5SDimitry Andric   // for them. See getLocationNo().
1675fe6060f1SDimitry Andric   SmallVector<MachineOperand, 8> MOs;
1676fe6060f1SDimitry Andric   if (DbgValue.isUndef()) {
1677fe6060f1SDimitry Andric     MOs.assign(DbgValue.loc_nos().size(),
1678fe6060f1SDimitry Andric                MachineOperand::CreateReg(
16795ffd83dbSDimitry Andric                    /* Reg */ 0, /* isDef */ false, /* isImp */ false,
16800b57cec5SDimitry Andric                    /* isKill */ false, /* isDead */ false,
16810b57cec5SDimitry Andric                    /* isUndef */ false, /* isEarlyClobber */ false,
1682fe6060f1SDimitry Andric                    /* SubReg */ 0, /* isDebug */ true));
1683fe6060f1SDimitry Andric   } else {
1684fe6060f1SDimitry Andric     for (unsigned LocNo : DbgValue.loc_nos())
1685fe6060f1SDimitry Andric       MOs.push_back(locations[LocNo]);
1686fe6060f1SDimitry Andric   }
16870b57cec5SDimitry Andric 
16880b57cec5SDimitry Andric   ++NumInsertedDebugValues;
16890b57cec5SDimitry Andric 
16900b57cec5SDimitry Andric   assert(cast<DILocalVariable>(Variable)
16910b57cec5SDimitry Andric              ->isValidLocationForIntrinsic(getDebugLoc()) &&
16920b57cec5SDimitry Andric          "Expected inlined-at fields to agree");
16930b57cec5SDimitry Andric 
16940b57cec5SDimitry Andric   // If the location was spilled, the new DBG_VALUE will be indirect. If the
16950b57cec5SDimitry Andric   // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
16960b57cec5SDimitry Andric   // that the original virtual register was a pointer. Also, add the stack slot
16970b57cec5SDimitry Andric   // offset for the spilled register to the expression.
16985ffd83dbSDimitry Andric   const DIExpression *Expr = DbgValue.getExpression();
16995ffd83dbSDimitry Andric   bool IsIndirect = DbgValue.getWasIndirect();
1700fe6060f1SDimitry Andric   bool IsList = DbgValue.getWasList();
1701fe6060f1SDimitry Andric   for (unsigned I = 0, E = LocSpills.size(); I != E; ++I) {
1702fe6060f1SDimitry Andric     if (LocSpills[I]) {
1703fe6060f1SDimitry Andric       if (!IsList) {
1704fe6060f1SDimitry Andric         uint8_t DIExprFlags = DIExpression::ApplyOffset;
170513138422SDimitry Andric         if (IsIndirect)
170613138422SDimitry Andric           DIExprFlags |= DIExpression::DerefAfter;
1707fe6060f1SDimitry Andric         Expr = DIExpression::prepend(Expr, DIExprFlags, SpillOffsets[I]);
170813138422SDimitry Andric         IsIndirect = true;
1709fe6060f1SDimitry Andric       } else {
1710fe6060f1SDimitry Andric         SmallVector<uint64_t, 4> Ops;
1711fe6060f1SDimitry Andric         DIExpression::appendOffset(Ops, SpillOffsets[I]);
1712fe6060f1SDimitry Andric         Ops.push_back(dwarf::DW_OP_deref);
1713fe6060f1SDimitry Andric         Expr = DIExpression::appendOpsToArg(Expr, Ops, I);
1714fe6060f1SDimitry Andric       }
171513138422SDimitry Andric     }
17160b57cec5SDimitry Andric 
1717fe6060f1SDimitry Andric     assert((!LocSpills[I] || MOs[I].isFI()) &&
1718fe6060f1SDimitry Andric            "a spilled location must be a frame index");
1719fe6060f1SDimitry Andric   }
17200b57cec5SDimitry Andric 
1721fe6060f1SDimitry Andric   unsigned DbgValueOpcode =
1722fe6060f1SDimitry Andric       IsList ? TargetOpcode::DBG_VALUE_LIST : TargetOpcode::DBG_VALUE;
17230b57cec5SDimitry Andric   do {
1724fe6060f1SDimitry Andric     BuildMI(*MBB, I, getDebugLoc(), TII.get(DbgValueOpcode), IsIndirect, MOs,
1725fe6060f1SDimitry Andric             Variable, Expr);
17260b57cec5SDimitry Andric 
1727fe6060f1SDimitry Andric     // Continue and insert DBG_VALUES after every redefinition of a register
17280b57cec5SDimitry Andric     // associated with the debug value within the range
1729fe6060f1SDimitry Andric     I = findNextInsertLocation(MBB, I, StopIdx, MOs, LIS, TRI);
17300b57cec5SDimitry Andric   } while (I != MBB->end());
17310b57cec5SDimitry Andric }
17320b57cec5SDimitry Andric 
insertDebugLabel(MachineBasicBlock * MBB,SlotIndex Idx,LiveIntervals & LIS,const TargetInstrInfo & TII,BlockSkipInstsMap & BBSkipInstsMap)17330b57cec5SDimitry Andric void UserLabel::insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
1734fe6060f1SDimitry Andric                                  LiveIntervals &LIS, const TargetInstrInfo &TII,
1735fe6060f1SDimitry Andric                                  BlockSkipInstsMap &BBSkipInstsMap) {
1736fe6060f1SDimitry Andric   MachineBasicBlock::iterator I =
1737fe6060f1SDimitry Andric       findInsertLocation(MBB, Idx, LIS, BBSkipInstsMap);
17380b57cec5SDimitry Andric   ++NumInsertedDebugLabels;
17390b57cec5SDimitry Andric   BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_LABEL))
17400b57cec5SDimitry Andric       .addMetadata(Label);
17410b57cec5SDimitry Andric }
17420b57cec5SDimitry Andric 
emitDebugValues(VirtRegMap * VRM,LiveIntervals & LIS,const TargetInstrInfo & TII,const TargetRegisterInfo & TRI,const SpillOffsetMap & SpillOffsets,BlockSkipInstsMap & BBSkipInstsMap)17430b57cec5SDimitry Andric void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
17440b57cec5SDimitry Andric                                 const TargetInstrInfo &TII,
17450b57cec5SDimitry Andric                                 const TargetRegisterInfo &TRI,
1746fe6060f1SDimitry Andric                                 const SpillOffsetMap &SpillOffsets,
1747fe6060f1SDimitry Andric                                 BlockSkipInstsMap &BBSkipInstsMap) {
17480b57cec5SDimitry Andric   MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
17490b57cec5SDimitry Andric 
17500b57cec5SDimitry Andric   for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
17510b57cec5SDimitry Andric     SlotIndex Start = I.start();
17520b57cec5SDimitry Andric     SlotIndex Stop = I.stop();
17535ffd83dbSDimitry Andric     DbgVariableValue DbgValue = I.value();
1754fe6060f1SDimitry Andric 
1755fe6060f1SDimitry Andric     SmallVector<bool> SpilledLocs;
1756fe6060f1SDimitry Andric     SmallVector<unsigned> LocSpillOffsets;
1757fe6060f1SDimitry Andric     for (unsigned LocNo : DbgValue.loc_nos()) {
1758fe6060f1SDimitry Andric       auto SpillIt =
1759fe6060f1SDimitry Andric           !DbgValue.isUndef() ? SpillOffsets.find(LocNo) : SpillOffsets.end();
17600b57cec5SDimitry Andric       bool Spilled = SpillIt != SpillOffsets.end();
1761fe6060f1SDimitry Andric       SpilledLocs.push_back(Spilled);
1762fe6060f1SDimitry Andric       LocSpillOffsets.push_back(Spilled ? SpillIt->second : 0);
1763fe6060f1SDimitry Andric     }
17640b57cec5SDimitry Andric 
176513138422SDimitry Andric     // If the interval start was trimmed to the lexical scope insert the
176613138422SDimitry Andric     // DBG_VALUE at the previous index (otherwise it appears after the
176713138422SDimitry Andric     // first instruction in the range).
176813138422SDimitry Andric     if (trimmedDefs.count(Start))
176913138422SDimitry Andric       Start = Start.getPrevIndex();
177013138422SDimitry Andric 
1771fe6060f1SDimitry Andric     LLVM_DEBUG(auto &dbg = dbgs(); dbg << "\t[" << Start << ';' << Stop << "):";
1772fe6060f1SDimitry Andric                DbgValue.printLocNos(dbg));
17730b57cec5SDimitry Andric     MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
17740b57cec5SDimitry Andric     SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
17750b57cec5SDimitry Andric 
17760b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1777fe6060f1SDimitry Andric     insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs, LocSpillOffsets,
1778fe6060f1SDimitry Andric                      LIS, TII, TRI, BBSkipInstsMap);
17790b57cec5SDimitry Andric     // This interval may span multiple basic blocks.
17800b57cec5SDimitry Andric     // Insert a DBG_VALUE into each one.
17810b57cec5SDimitry Andric     while (Stop > MBBEnd) {
17820b57cec5SDimitry Andric       // Move to the next block.
17830b57cec5SDimitry Andric       Start = MBBEnd;
17840b57cec5SDimitry Andric       if (++MBB == MFEnd)
17850b57cec5SDimitry Andric         break;
17860b57cec5SDimitry Andric       MBBEnd = LIS.getMBBEndIdx(&*MBB);
17870b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1788fe6060f1SDimitry Andric       insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs,
1789fe6060f1SDimitry Andric                        LocSpillOffsets, LIS, TII, TRI, BBSkipInstsMap);
17900b57cec5SDimitry Andric     }
17910b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << '\n');
17920b57cec5SDimitry Andric     if (MBB == MFEnd)
17930b57cec5SDimitry Andric       break;
17940b57cec5SDimitry Andric 
17950b57cec5SDimitry Andric     ++I;
17960b57cec5SDimitry Andric   }
17970b57cec5SDimitry Andric }
17980b57cec5SDimitry Andric 
emitDebugLabel(LiveIntervals & LIS,const TargetInstrInfo & TII,BlockSkipInstsMap & BBSkipInstsMap)1799fe6060f1SDimitry Andric void UserLabel::emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
1800fe6060f1SDimitry Andric                                BlockSkipInstsMap &BBSkipInstsMap) {
18010b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\t" << loc);
18020b57cec5SDimitry Andric   MachineFunction::iterator MBB = LIS.getMBBFromIndex(loc)->getIterator();
18030b57cec5SDimitry Andric 
18040b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB));
1805fe6060f1SDimitry Andric   insertDebugLabel(&*MBB, loc, LIS, TII, BBSkipInstsMap);
18060b57cec5SDimitry Andric 
18070b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << '\n');
18080b57cec5SDimitry Andric }
18090b57cec5SDimitry Andric 
emitDebugValues(VirtRegMap * VRM)18100b57cec5SDimitry Andric void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
18110b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
18120b57cec5SDimitry Andric   if (!MF)
18130b57cec5SDimitry Andric     return;
1814fe6060f1SDimitry Andric 
1815fe6060f1SDimitry Andric   BlockSkipInstsMap BBSkipInstsMap;
18160b57cec5SDimitry Andric   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18170b57cec5SDimitry Andric   SpillOffsetMap SpillOffsets;
18180b57cec5SDimitry Andric   for (auto &userValue : userValues) {
18190b57cec5SDimitry Andric     LLVM_DEBUG(userValue->print(dbgs(), TRI));
18200b57cec5SDimitry Andric     userValue->rewriteLocations(*VRM, *MF, *TII, *TRI, SpillOffsets);
1821fe6060f1SDimitry Andric     userValue->emitDebugValues(VRM, *LIS, *TII, *TRI, SpillOffsets,
1822fe6060f1SDimitry Andric                                BBSkipInstsMap);
18230b57cec5SDimitry Andric   }
18240b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG LABELS **********\n");
18250b57cec5SDimitry Andric   for (auto &userLabel : userLabels) {
18260b57cec5SDimitry Andric     LLVM_DEBUG(userLabel->print(dbgs(), TRI));
1827fe6060f1SDimitry Andric     userLabel->emitDebugLabel(*LIS, *TII, BBSkipInstsMap);
18280b57cec5SDimitry Andric   }
1829e8d8bef9SDimitry Andric 
1830fe6060f1SDimitry Andric   LLVM_DEBUG(dbgs() << "********** EMITTING DEBUG PHIS **********\n");
1831fe6060f1SDimitry Andric 
1832fe6060f1SDimitry Andric   auto Slots = LIS->getSlotIndexes();
1833fe6060f1SDimitry Andric   for (auto &It : PHIValToPos) {
1834fe6060f1SDimitry Andric     // For each ex-PHI, identify its physreg location or stack slot, and emit
1835fe6060f1SDimitry Andric     // a DBG_PHI for it.
1836fe6060f1SDimitry Andric     unsigned InstNum = It.first;
1837fe6060f1SDimitry Andric     auto Slot = It.second.SI;
1838fe6060f1SDimitry Andric     Register Reg = It.second.Reg;
1839fe6060f1SDimitry Andric     unsigned SubReg = It.second.SubReg;
1840fe6060f1SDimitry Andric 
1841fe6060f1SDimitry Andric     MachineBasicBlock *OrigMBB = Slots->getMBBFromIndex(Slot);
1842fe6060f1SDimitry Andric     if (VRM->isAssignedReg(Reg) &&
1843fe6060f1SDimitry Andric         Register::isPhysicalRegister(VRM->getPhys(Reg))) {
1844fe6060f1SDimitry Andric       unsigned PhysReg = VRM->getPhys(Reg);
1845fe6060f1SDimitry Andric       if (SubReg != 0)
1846fe6060f1SDimitry Andric         PhysReg = TRI->getSubReg(PhysReg, SubReg);
1847fe6060f1SDimitry Andric 
1848fe6060f1SDimitry Andric       auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(),
1849fe6060f1SDimitry Andric                              TII->get(TargetOpcode::DBG_PHI));
1850fe6060f1SDimitry Andric       Builder.addReg(PhysReg);
1851fe6060f1SDimitry Andric       Builder.addImm(InstNum);
1852fe6060f1SDimitry Andric     } else if (VRM->getStackSlot(Reg) != VirtRegMap::NO_STACK_SLOT) {
1853fe6060f1SDimitry Andric       const MachineRegisterInfo &MRI = MF->getRegInfo();
1854fe6060f1SDimitry Andric       const TargetRegisterClass *TRC = MRI.getRegClass(Reg);
1855fe6060f1SDimitry Andric       unsigned SpillSize, SpillOffset;
1856fe6060f1SDimitry Andric 
185781ad6265SDimitry Andric       unsigned regSizeInBits = TRI->getRegSizeInBits(*TRC);
185881ad6265SDimitry Andric       if (SubReg)
185981ad6265SDimitry Andric         regSizeInBits = TRI->getSubRegIdxSize(SubReg);
186081ad6265SDimitry Andric 
186181ad6265SDimitry Andric       // Test whether this location is legal with the given subreg. If the
186281ad6265SDimitry Andric       // subregister has a nonzero offset, drop this location, it's too complex
186381ad6265SDimitry Andric       // to describe. (TODO: future work).
1864fe6060f1SDimitry Andric       bool Success =
1865fe6060f1SDimitry Andric           TII->getStackSlotRange(TRC, SubReg, SpillSize, SpillOffset, *MF);
1866fe6060f1SDimitry Andric 
186781ad6265SDimitry Andric       if (Success && SpillOffset == 0) {
1868fe6060f1SDimitry Andric         auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(),
1869fe6060f1SDimitry Andric                                TII->get(TargetOpcode::DBG_PHI));
1870fe6060f1SDimitry Andric         Builder.addFrameIndex(VRM->getStackSlot(Reg));
1871fe6060f1SDimitry Andric         Builder.addImm(InstNum);
187281ad6265SDimitry Andric         // Record how large the original value is. The stack slot might be
187381ad6265SDimitry Andric         // merged and altered during optimisation, but we will want to know how
187481ad6265SDimitry Andric         // large the value is, at this DBG_PHI.
187581ad6265SDimitry Andric         Builder.addImm(regSizeInBits);
1876fe6060f1SDimitry Andric       }
187781ad6265SDimitry Andric 
187881ad6265SDimitry Andric       LLVM_DEBUG(
187981ad6265SDimitry Andric       if (SpillOffset != 0) {
188081ad6265SDimitry Andric         dbgs() << "DBG_PHI for Vreg " << Reg << " subreg " << SubReg <<
188181ad6265SDimitry Andric                   " has nonzero offset\n";
188281ad6265SDimitry Andric       }
188381ad6265SDimitry Andric       );
1884fe6060f1SDimitry Andric     }
1885fe6060f1SDimitry Andric     // If there was no mapping for a value ID, it's optimized out. Create no
1886fe6060f1SDimitry Andric     // DBG_PHI, and any variables using this value will become optimized out.
1887fe6060f1SDimitry Andric   }
1888fe6060f1SDimitry Andric   MF->DebugPHIPositions.clear();
1889fe6060f1SDimitry Andric 
1890e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "********** EMITTING INSTR REFERENCES **********\n");
1891e8d8bef9SDimitry Andric 
18924824e7fdSDimitry Andric   // Re-insert any debug instrs back in the position they were. We must
18934824e7fdSDimitry Andric   // re-insert in the same order to ensure that debug instructions don't swap,
18944824e7fdSDimitry Andric   // which could re-order assignments. Do so in a batch -- once we find the
18954824e7fdSDimitry Andric   // insert position, insert all instructions at the same SlotIdx. They are
18964824e7fdSDimitry Andric   // guaranteed to appear in-sequence in StashedDebugInstrs because we insert
18974824e7fdSDimitry Andric   // them in order.
1898fcaf7f86SDimitry Andric   for (auto *StashIt = StashedDebugInstrs.begin();
18994824e7fdSDimitry Andric        StashIt != StashedDebugInstrs.end(); ++StashIt) {
19004824e7fdSDimitry Andric     SlotIndex Idx = StashIt->Idx;
19014824e7fdSDimitry Andric     MachineBasicBlock *MBB = StashIt->MBB;
19024824e7fdSDimitry Andric     MachineInstr *MI = StashIt->MI;
19034824e7fdSDimitry Andric 
19044824e7fdSDimitry Andric     auto EmitInstsHere = [this, &StashIt, MBB, Idx,
19054824e7fdSDimitry Andric                           MI](MachineBasicBlock::iterator InsertPos) {
19064824e7fdSDimitry Andric       // Insert this debug instruction.
19074824e7fdSDimitry Andric       MBB->insert(InsertPos, MI);
19084824e7fdSDimitry Andric 
19094824e7fdSDimitry Andric       // Look at subsequent stashed debug instructions: if they're at the same
19104824e7fdSDimitry Andric       // index, insert those too.
19114824e7fdSDimitry Andric       auto NextItem = std::next(StashIt);
19124824e7fdSDimitry Andric       while (NextItem != StashedDebugInstrs.end() && NextItem->Idx == Idx) {
19134824e7fdSDimitry Andric         assert(NextItem->MBB == MBB && "Instrs with same slot index should be"
19144824e7fdSDimitry Andric                "in the same block");
19154824e7fdSDimitry Andric         MBB->insert(InsertPos, NextItem->MI);
19164824e7fdSDimitry Andric         StashIt = NextItem;
19174824e7fdSDimitry Andric         NextItem = std::next(StashIt);
19184824e7fdSDimitry Andric       };
19194824e7fdSDimitry Andric     };
1920fe6060f1SDimitry Andric 
1921fe6060f1SDimitry Andric     // Start block index: find the first non-debug instr in the block, and
1922fe6060f1SDimitry Andric     // insert before it.
19234824e7fdSDimitry Andric     if (Idx == Slots->getMBBStartIdx(MBB)) {
1924fe6060f1SDimitry Andric       MachineBasicBlock::iterator InsertPos =
19254824e7fdSDimitry Andric           findInsertLocation(MBB, Idx, *LIS, BBSkipInstsMap);
19264824e7fdSDimitry Andric       EmitInstsHere(InsertPos);
1927fe6060f1SDimitry Andric       continue;
1928fe6060f1SDimitry Andric     }
1929fe6060f1SDimitry Andric 
1930fe6060f1SDimitry Andric     if (MachineInstr *Pos = Slots->getInstructionFromIndex(Idx)) {
1931fe6060f1SDimitry Andric       // Insert at the end of any debug instructions.
1932fe6060f1SDimitry Andric       auto PostDebug = std::next(Pos->getIterator());
19334824e7fdSDimitry Andric       PostDebug = skipDebugInstructionsForward(PostDebug, MBB->instr_end());
19344824e7fdSDimitry Andric       EmitInstsHere(PostDebug);
1935fe6060f1SDimitry Andric     } else {
1936fe6060f1SDimitry Andric       // Insert position disappeared; walk forwards through slots until we
1937fe6060f1SDimitry Andric       // find a new one.
19384824e7fdSDimitry Andric       SlotIndex End = Slots->getMBBEndIdx(MBB);
1939fe6060f1SDimitry Andric       for (; Idx < End; Idx = Slots->getNextNonNullIndex(Idx)) {
1940fe6060f1SDimitry Andric         Pos = Slots->getInstructionFromIndex(Idx);
1941fe6060f1SDimitry Andric         if (Pos) {
19424824e7fdSDimitry Andric           EmitInstsHere(Pos->getIterator());
1943fe6060f1SDimitry Andric           break;
1944fe6060f1SDimitry Andric         }
1945fe6060f1SDimitry Andric       }
1946fe6060f1SDimitry Andric 
1947fe6060f1SDimitry Andric       // We have reached the end of the block and didn't find anywhere to
1948fe6060f1SDimitry Andric       // insert! It's not safe to discard any debug instructions; place them
1949fe6060f1SDimitry Andric       // in front of the first terminator, or in front of end().
1950fe6060f1SDimitry Andric       if (Idx >= End) {
19514824e7fdSDimitry Andric         auto TermIt = MBB->getFirstTerminator();
19524824e7fdSDimitry Andric         EmitInstsHere(TermIt);
1953fe6060f1SDimitry Andric       }
1954e8d8bef9SDimitry Andric     }
1955e8d8bef9SDimitry Andric   }
1956e8d8bef9SDimitry Andric 
19570b57cec5SDimitry Andric   EmitDone = true;
1958fe6060f1SDimitry Andric   BBSkipInstsMap.clear();
19590b57cec5SDimitry Andric }
19600b57cec5SDimitry Andric 
emitDebugValues(VirtRegMap * VRM)19610b57cec5SDimitry Andric void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
19620b57cec5SDimitry Andric   if (pImpl)
19630b57cec5SDimitry Andric     static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
19640b57cec5SDimitry Andric }
19650b57cec5SDimitry Andric 
19660b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const19670b57cec5SDimitry Andric LLVM_DUMP_METHOD void LiveDebugVariables::dump() const {
19680b57cec5SDimitry Andric   if (pImpl)
19690b57cec5SDimitry Andric     static_cast<LDVImpl*>(pImpl)->print(dbgs());
19700b57cec5SDimitry Andric }
19710b57cec5SDimitry Andric #endif
1972