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"
310b57cec5SDimitry Andric #include "llvm/CodeGen/LexicalScopes.h"
320b57cec5SDimitry Andric #include "llvm/CodeGen/LiveInterval.h"
330b57cec5SDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
350b57cec5SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
360b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
370b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
380b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
390b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
400b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
41fe6060f1SDimitry Andric #include "llvm/CodeGen/Passes.h"
420b57cec5SDimitry Andric #include "llvm/CodeGen/SlotIndexes.h"
430b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
440b57cec5SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
45fe6060f1SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h"
460b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
470b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
480b57cec5SDimitry Andric #include "llvm/CodeGen/VirtRegMap.h"
490b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
500b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
510b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
520b57cec5SDimitry Andric #include "llvm/IR/Function.h"
530b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
54480093f4SDimitry Andric #include "llvm/InitializePasses.h"
550b57cec5SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
560b57cec5SDimitry Andric #include "llvm/Pass.h"
570b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
580b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
590b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
600b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
61fe6060f1SDimitry Andric #include "llvm/Target/TargetMachine.h"
620b57cec5SDimitry Andric #include <algorithm>
630b57cec5SDimitry Andric #include <cassert>
640b57cec5SDimitry Andric #include <iterator>
650b57cec5SDimitry Andric #include <memory>
660b57cec5SDimitry Andric #include <utility>
670b57cec5SDimitry Andric 
680b57cec5SDimitry Andric using namespace llvm;
690b57cec5SDimitry Andric 
700b57cec5SDimitry Andric #define DEBUG_TYPE "livedebugvars"
710b57cec5SDimitry Andric 
720b57cec5SDimitry Andric static cl::opt<bool>
730b57cec5SDimitry Andric EnableLDV("live-debug-variables", cl::init(true),
740b57cec5SDimitry Andric           cl::desc("Enable the live debug variables pass"), cl::Hidden);
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
770b57cec5SDimitry Andric STATISTIC(NumInsertedDebugLabels, "Number of DBG_LABELs inserted");
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric char LiveDebugVariables::ID = 0;
800b57cec5SDimitry Andric 
810b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE,
820b57cec5SDimitry Andric                 "Debug Variable Analysis", false, false)
830b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
840b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
850b57cec5SDimitry Andric INITIALIZE_PASS_END(LiveDebugVariables, DEBUG_TYPE,
860b57cec5SDimitry Andric                 "Debug Variable Analysis", false, false)
870b57cec5SDimitry Andric 
880b57cec5SDimitry Andric void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
890b57cec5SDimitry Andric   AU.addRequired<MachineDominatorTree>();
900b57cec5SDimitry Andric   AU.addRequiredTransitive<LiveIntervals>();
910b57cec5SDimitry Andric   AU.setPreservesAll();
920b57cec5SDimitry Andric   MachineFunctionPass::getAnalysisUsage(AU);
930b57cec5SDimitry Andric }
940b57cec5SDimitry Andric 
950b57cec5SDimitry Andric LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID) {
960b57cec5SDimitry Andric   initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
970b57cec5SDimitry Andric }
980b57cec5SDimitry Andric 
990b57cec5SDimitry Andric enum : unsigned { UndefLocNo = ~0U };
1000b57cec5SDimitry Andric 
101e8d8bef9SDimitry Andric namespace {
1025ffd83dbSDimitry Andric /// Describes a debug variable value by location number and expression along
1035ffd83dbSDimitry Andric /// with some flags about the original usage of the location.
1045ffd83dbSDimitry Andric class DbgVariableValue {
1050b57cec5SDimitry Andric public:
106fe6060f1SDimitry Andric   DbgVariableValue(ArrayRef<unsigned> NewLocs, bool WasIndirect, bool WasList,
107fe6060f1SDimitry Andric                    const DIExpression &Expr)
108fe6060f1SDimitry Andric       : WasIndirect(WasIndirect), WasList(WasList), Expression(&Expr) {
109fe6060f1SDimitry Andric     assert(!(WasIndirect && WasList) &&
110fe6060f1SDimitry Andric            "DBG_VALUE_LISTs should not be indirect.");
111fe6060f1SDimitry Andric     SmallVector<unsigned> LocNoVec;
112fe6060f1SDimitry Andric     for (unsigned LocNo : NewLocs) {
113fe6060f1SDimitry Andric       auto It = find(LocNoVec, LocNo);
114fe6060f1SDimitry Andric       if (It == LocNoVec.end())
115fe6060f1SDimitry Andric         LocNoVec.push_back(LocNo);
116fe6060f1SDimitry Andric       else {
117fe6060f1SDimitry Andric         // Loc duplicates an element in LocNos; replace references to Op
118fe6060f1SDimitry Andric         // with references to the duplicating element.
119fe6060f1SDimitry Andric         unsigned OpIdx = LocNoVec.size();
120fe6060f1SDimitry Andric         unsigned DuplicatingIdx = std::distance(LocNoVec.begin(), It);
121fe6060f1SDimitry Andric         Expression =
122fe6060f1SDimitry Andric             DIExpression::replaceArg(Expression, OpIdx, DuplicatingIdx);
123fe6060f1SDimitry Andric       }
124fe6060f1SDimitry Andric     }
125fe6060f1SDimitry Andric     // FIXME: Debug values referencing 64+ unique machine locations are rare and
126fe6060f1SDimitry Andric     // currently unsupported for performance reasons. If we can verify that
127fe6060f1SDimitry Andric     // performance is acceptable for such debug values, we can increase the
128fe6060f1SDimitry Andric     // bit-width of LocNoCount to 14 to enable up to 16384 unique machine
129fe6060f1SDimitry Andric     // locations. We will also need to verify that this does not cause issues
130fe6060f1SDimitry Andric     // with LiveDebugVariables' use of IntervalMap.
131fe6060f1SDimitry Andric     if (LocNoVec.size() < 64) {
132fe6060f1SDimitry Andric       LocNoCount = LocNoVec.size();
133fe6060f1SDimitry Andric       if (LocNoCount > 0) {
134fe6060f1SDimitry Andric         LocNos = std::make_unique<unsigned[]>(LocNoCount);
135fe6060f1SDimitry Andric         std::copy(LocNoVec.begin(), LocNoVec.end(), loc_nos_begin());
136fe6060f1SDimitry Andric       }
137fe6060f1SDimitry Andric     } else {
138fe6060f1SDimitry Andric       LLVM_DEBUG(dbgs() << "Found debug value with 64+ unique machine "
139fe6060f1SDimitry Andric                            "locations, dropping...\n");
140fe6060f1SDimitry Andric       LocNoCount = 1;
141fe6060f1SDimitry Andric       // Turn this into an undef debug value list; right now, the simplest form
142fe6060f1SDimitry Andric       // of this is an expression with one arg, and an undef debug operand.
143fe6060f1SDimitry Andric       Expression =
144fe6060f1SDimitry Andric           DIExpression::get(Expr.getContext(), {dwarf::DW_OP_LLVM_arg, 0,
145fe6060f1SDimitry Andric                                                 dwarf::DW_OP_stack_value});
146fe6060f1SDimitry Andric       if (auto FragmentInfoOpt = Expr.getFragmentInfo())
147fe6060f1SDimitry Andric         Expression = *DIExpression::createFragmentExpression(
148fe6060f1SDimitry Andric             Expression, FragmentInfoOpt->OffsetInBits,
149fe6060f1SDimitry Andric             FragmentInfoOpt->SizeInBits);
150fe6060f1SDimitry Andric       LocNos = std::make_unique<unsigned[]>(LocNoCount);
151fe6060f1SDimitry Andric       LocNos[0] = UndefLocNo;
152fe6060f1SDimitry Andric     }
1530b57cec5SDimitry Andric   }
1540b57cec5SDimitry Andric 
15504eeddc0SDimitry Andric   DbgVariableValue() : LocNoCount(0), WasIndirect(false), WasList(false) {}
156fe6060f1SDimitry Andric   DbgVariableValue(const DbgVariableValue &Other)
157fe6060f1SDimitry Andric       : LocNoCount(Other.LocNoCount), WasIndirect(Other.getWasIndirect()),
158fe6060f1SDimitry Andric         WasList(Other.getWasList()), Expression(Other.getExpression()) {
159fe6060f1SDimitry Andric     if (Other.getLocNoCount()) {
160fe6060f1SDimitry Andric       LocNos.reset(new unsigned[Other.getLocNoCount()]);
161fe6060f1SDimitry Andric       std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin());
162fe6060f1SDimitry Andric     }
163fe6060f1SDimitry Andric   }
164fe6060f1SDimitry Andric 
165fe6060f1SDimitry Andric   DbgVariableValue &operator=(const DbgVariableValue &Other) {
166fe6060f1SDimitry Andric     if (this == &Other)
167fe6060f1SDimitry Andric       return *this;
168fe6060f1SDimitry Andric     if (Other.getLocNoCount()) {
169fe6060f1SDimitry Andric       LocNos.reset(new unsigned[Other.getLocNoCount()]);
170fe6060f1SDimitry Andric       std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin());
171fe6060f1SDimitry Andric     } else {
172fe6060f1SDimitry Andric       LocNos.release();
173fe6060f1SDimitry Andric     }
174fe6060f1SDimitry Andric     LocNoCount = Other.getLocNoCount();
175fe6060f1SDimitry Andric     WasIndirect = Other.getWasIndirect();
176fe6060f1SDimitry Andric     WasList = Other.getWasList();
177fe6060f1SDimitry Andric     Expression = Other.getExpression();
178fe6060f1SDimitry Andric     return *this;
179fe6060f1SDimitry Andric   }
1800b57cec5SDimitry Andric 
1815ffd83dbSDimitry Andric   const DIExpression *getExpression() const { return Expression; }
182fe6060f1SDimitry Andric   uint8_t getLocNoCount() const { return LocNoCount; }
183fe6060f1SDimitry Andric   bool containsLocNo(unsigned LocNo) const {
184fe6060f1SDimitry Andric     return is_contained(loc_nos(), LocNo);
1850b57cec5SDimitry Andric   }
1865ffd83dbSDimitry Andric   bool getWasIndirect() const { return WasIndirect; }
187fe6060f1SDimitry Andric   bool getWasList() const { return WasList; }
188fe6060f1SDimitry Andric   bool isUndef() const { return LocNoCount == 0 || containsLocNo(UndefLocNo); }
1890b57cec5SDimitry Andric 
190fe6060f1SDimitry Andric   DbgVariableValue decrementLocNosAfterPivot(unsigned Pivot) const {
191fe6060f1SDimitry Andric     SmallVector<unsigned, 4> NewLocNos;
192fe6060f1SDimitry Andric     for (unsigned LocNo : loc_nos())
193fe6060f1SDimitry Andric       NewLocNos.push_back(LocNo != UndefLocNo && LocNo > Pivot ? LocNo - 1
194fe6060f1SDimitry Andric                                                                : LocNo);
195fe6060f1SDimitry Andric     return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
196fe6060f1SDimitry Andric   }
197fe6060f1SDimitry Andric 
198fe6060f1SDimitry Andric   DbgVariableValue remapLocNos(ArrayRef<unsigned> LocNoMap) const {
199fe6060f1SDimitry Andric     SmallVector<unsigned> NewLocNos;
200fe6060f1SDimitry Andric     for (unsigned LocNo : loc_nos())
201fe6060f1SDimitry Andric       // Undef values don't exist in locations (and thus not in LocNoMap
202fe6060f1SDimitry Andric       // either) so skip over them. See getLocationNo().
203fe6060f1SDimitry Andric       NewLocNos.push_back(LocNo == UndefLocNo ? UndefLocNo : LocNoMap[LocNo]);
204fe6060f1SDimitry Andric     return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
205fe6060f1SDimitry Andric   }
206fe6060f1SDimitry Andric 
207fe6060f1SDimitry Andric   DbgVariableValue changeLocNo(unsigned OldLocNo, unsigned NewLocNo) const {
208fe6060f1SDimitry Andric     SmallVector<unsigned> NewLocNos;
209fe6060f1SDimitry Andric     NewLocNos.assign(loc_nos_begin(), loc_nos_end());
210fe6060f1SDimitry Andric     auto OldLocIt = find(NewLocNos, OldLocNo);
211fe6060f1SDimitry Andric     assert(OldLocIt != NewLocNos.end() && "Old location must be present.");
212fe6060f1SDimitry Andric     *OldLocIt = NewLocNo;
213fe6060f1SDimitry Andric     return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
214fe6060f1SDimitry Andric   }
215fe6060f1SDimitry Andric 
216fe6060f1SDimitry Andric   bool hasLocNoGreaterThan(unsigned LocNo) const {
217fe6060f1SDimitry Andric     return any_of(loc_nos(),
218fe6060f1SDimitry Andric                   [LocNo](unsigned ThisLocNo) { return ThisLocNo > LocNo; });
219fe6060f1SDimitry Andric   }
220fe6060f1SDimitry Andric 
221fe6060f1SDimitry Andric   void printLocNos(llvm::raw_ostream &OS) const {
222fe6060f1SDimitry Andric     for (const unsigned &Loc : loc_nos())
223fe6060f1SDimitry Andric       OS << (&Loc == loc_nos_begin() ? " " : ", ") << Loc;
2240b57cec5SDimitry Andric   }
2250b57cec5SDimitry Andric 
2265ffd83dbSDimitry Andric   friend inline bool operator==(const DbgVariableValue &LHS,
2275ffd83dbSDimitry Andric                                 const DbgVariableValue &RHS) {
228fe6060f1SDimitry Andric     if (std::tie(LHS.LocNoCount, LHS.WasIndirect, LHS.WasList,
229fe6060f1SDimitry Andric                  LHS.Expression) !=
230fe6060f1SDimitry Andric         std::tie(RHS.LocNoCount, RHS.WasIndirect, RHS.WasList, RHS.Expression))
231fe6060f1SDimitry Andric       return false;
232fe6060f1SDimitry Andric     return std::equal(LHS.loc_nos_begin(), LHS.loc_nos_end(),
233fe6060f1SDimitry Andric                       RHS.loc_nos_begin());
2340b57cec5SDimitry Andric   }
2350b57cec5SDimitry Andric 
2365ffd83dbSDimitry Andric   friend inline bool operator!=(const DbgVariableValue &LHS,
2375ffd83dbSDimitry Andric                                 const DbgVariableValue &RHS) {
2380b57cec5SDimitry Andric     return !(LHS == RHS);
2390b57cec5SDimitry Andric   }
2400b57cec5SDimitry Andric 
241fe6060f1SDimitry Andric   unsigned *loc_nos_begin() { return LocNos.get(); }
242fe6060f1SDimitry Andric   const unsigned *loc_nos_begin() const { return LocNos.get(); }
243fe6060f1SDimitry Andric   unsigned *loc_nos_end() { return LocNos.get() + LocNoCount; }
244fe6060f1SDimitry Andric   const unsigned *loc_nos_end() const { return LocNos.get() + LocNoCount; }
245fe6060f1SDimitry Andric   ArrayRef<unsigned> loc_nos() const {
246fe6060f1SDimitry Andric     return ArrayRef<unsigned>(LocNos.get(), LocNoCount);
247fe6060f1SDimitry Andric   }
248fe6060f1SDimitry Andric 
2490b57cec5SDimitry Andric private:
250fe6060f1SDimitry Andric   // IntervalMap requires the value object to be very small, to the extent
251fe6060f1SDimitry Andric   // that we do not have enough room for an std::vector. Using a C-style array
252fe6060f1SDimitry Andric   // (with a unique_ptr wrapper for convenience) allows us to optimize for this
253fe6060f1SDimitry Andric   // specific case by packing the array size into only 6 bits (it is highly
254fe6060f1SDimitry Andric   // unlikely that any debug value will need 64+ locations).
255fe6060f1SDimitry Andric   std::unique_ptr<unsigned[]> LocNos;
256fe6060f1SDimitry Andric   uint8_t LocNoCount : 6;
257fe6060f1SDimitry Andric   bool WasIndirect : 1;
258fe6060f1SDimitry Andric   bool WasList : 1;
2595ffd83dbSDimitry Andric   const DIExpression *Expression = nullptr;
2600b57cec5SDimitry Andric };
261e8d8bef9SDimitry Andric } // namespace
2620b57cec5SDimitry Andric 
2635ffd83dbSDimitry Andric /// Map of where a user value is live to that value.
2645ffd83dbSDimitry Andric using LocMap = IntervalMap<SlotIndex, DbgVariableValue, 4>;
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric /// Map of stack slot offsets for spilled locations.
2670b57cec5SDimitry Andric /// Non-spilled locations are not added to the map.
2680b57cec5SDimitry Andric using SpillOffsetMap = DenseMap<unsigned, unsigned>;
2690b57cec5SDimitry Andric 
270fe6060f1SDimitry Andric /// Cache to save the location where it can be used as the starting
271fe6060f1SDimitry Andric /// position as input for calling MachineBasicBlock::SkipPHIsLabelsAndDebug.
272fe6060f1SDimitry Andric /// This is to prevent MachineBasicBlock::SkipPHIsLabelsAndDebug from
273fe6060f1SDimitry Andric /// repeatedly searching the same set of PHIs/Labels/Debug instructions
274fe6060f1SDimitry Andric /// if it is called many times for the same block.
275fe6060f1SDimitry Andric using BlockSkipInstsMap =
276fe6060f1SDimitry Andric     DenseMap<MachineBasicBlock *, MachineBasicBlock::iterator>;
277fe6060f1SDimitry Andric 
2780b57cec5SDimitry Andric namespace {
2790b57cec5SDimitry Andric 
2800b57cec5SDimitry Andric class LDVImpl;
2810b57cec5SDimitry Andric 
2820b57cec5SDimitry Andric /// A user value is a part of a debug info user variable.
2830b57cec5SDimitry Andric ///
2840b57cec5SDimitry Andric /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
2850b57cec5SDimitry Andric /// holds part of a user variable. The part is identified by a byte offset.
286480093f4SDimitry Andric ///
287480093f4SDimitry Andric /// UserValues are grouped into equivalence classes for easier searching. Two
2885ffd83dbSDimitry Andric /// user values are related if they are held by the same virtual register. The
2895ffd83dbSDimitry Andric /// equivalence class is the transitive closure of that relation.
2900b57cec5SDimitry Andric class UserValue {
2910b57cec5SDimitry Andric   const DILocalVariable *Variable; ///< The debug info variable we are part of.
2925ffd83dbSDimitry Andric   /// The part of the variable we describe.
2935ffd83dbSDimitry Andric   const Optional<DIExpression::FragmentInfo> Fragment;
2940b57cec5SDimitry Andric   DebugLoc dl;            ///< The debug location for the variable. This is
2950b57cec5SDimitry Andric                           ///< used by dwarf writer to find lexical scope.
296480093f4SDimitry Andric   UserValue *leader;      ///< Equivalence class leader.
297480093f4SDimitry Andric   UserValue *next = nullptr; ///< Next value in equivalence class, or null.
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric   /// Numbered locations referenced by locmap.
3000b57cec5SDimitry Andric   SmallVector<MachineOperand, 4> locations;
3010b57cec5SDimitry Andric 
3020b57cec5SDimitry Andric   /// Map of slot indices where this value is live.
3030b57cec5SDimitry Andric   LocMap locInts;
3040b57cec5SDimitry Andric 
30513138422SDimitry Andric   /// Set of interval start indexes that have been trimmed to the
30613138422SDimitry Andric   /// lexical scope.
30713138422SDimitry Andric   SmallSet<SlotIndex, 2> trimmedDefs;
30813138422SDimitry Andric 
3095ffd83dbSDimitry Andric   /// Insert a DBG_VALUE into MBB at Idx for DbgValue.
3100b57cec5SDimitry Andric   void insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
3115ffd83dbSDimitry Andric                         SlotIndex StopIdx, DbgVariableValue DbgValue,
312fe6060f1SDimitry Andric                         ArrayRef<bool> LocSpills,
313fe6060f1SDimitry Andric                         ArrayRef<unsigned> SpillOffsets, LiveIntervals &LIS,
3140b57cec5SDimitry Andric                         const TargetInstrInfo &TII,
315fe6060f1SDimitry Andric                         const TargetRegisterInfo &TRI,
316fe6060f1SDimitry Andric                         BlockSkipInstsMap &BBSkipInstsMap);
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric   /// Replace OldLocNo ranges with NewRegs ranges where NewRegs
3190b57cec5SDimitry Andric   /// is live. Returns true if any changes were made.
3205ffd83dbSDimitry Andric   bool splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs,
3210b57cec5SDimitry Andric                      LiveIntervals &LIS);
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric public:
3240b57cec5SDimitry Andric   /// Create a new UserValue.
3255ffd83dbSDimitry Andric   UserValue(const DILocalVariable *var,
3265ffd83dbSDimitry Andric             Optional<DIExpression::FragmentInfo> Fragment, DebugLoc L,
3270b57cec5SDimitry Andric             LocMap::Allocator &alloc)
3285ffd83dbSDimitry Andric       : Variable(var), Fragment(Fragment), dl(std::move(L)), leader(this),
329480093f4SDimitry Andric         locInts(alloc) {}
3300b57cec5SDimitry Andric 
331480093f4SDimitry Andric   /// Get the leader of this value's equivalence class.
332480093f4SDimitry Andric   UserValue *getLeader() {
333480093f4SDimitry Andric     UserValue *l = leader;
334480093f4SDimitry Andric     while (l != l->leader)
335480093f4SDimitry Andric       l = l->leader;
336480093f4SDimitry Andric     return leader = l;
337480093f4SDimitry Andric   }
338480093f4SDimitry Andric 
339480093f4SDimitry Andric   /// Return the next UserValue in the equivalence class.
340480093f4SDimitry Andric   UserValue *getNext() const { return next; }
341480093f4SDimitry Andric 
342480093f4SDimitry Andric   /// Merge equivalence classes.
343480093f4SDimitry Andric   static UserValue *merge(UserValue *L1, UserValue *L2) {
344480093f4SDimitry Andric     L2 = L2->getLeader();
345480093f4SDimitry Andric     if (!L1)
346480093f4SDimitry Andric       return L2;
347480093f4SDimitry Andric     L1 = L1->getLeader();
348480093f4SDimitry Andric     if (L1 == L2)
349480093f4SDimitry Andric       return L1;
350480093f4SDimitry Andric     // Splice L2 before L1's members.
351480093f4SDimitry Andric     UserValue *End = L2;
352480093f4SDimitry Andric     while (End->next) {
353480093f4SDimitry Andric       End->leader = L1;
354480093f4SDimitry Andric       End = End->next;
355480093f4SDimitry Andric     }
356480093f4SDimitry Andric     End->leader = L1;
357480093f4SDimitry Andric     End->next = L1->next;
358480093f4SDimitry Andric     L1->next = L2;
359480093f4SDimitry Andric     return L1;
3600b57cec5SDimitry Andric   }
3610b57cec5SDimitry Andric 
3620b57cec5SDimitry Andric   /// Return the location number that matches Loc.
3630b57cec5SDimitry Andric   ///
3640b57cec5SDimitry Andric   /// For undef values we always return location number UndefLocNo without
3650b57cec5SDimitry Andric   /// inserting anything in locations. Since locations is a vector and the
3660b57cec5SDimitry Andric   /// location number is the position in the vector and UndefLocNo is ~0,
3670b57cec5SDimitry Andric   /// we would need a very big vector to put the value at the right position.
3680b57cec5SDimitry Andric   unsigned getLocationNo(const MachineOperand &LocMO) {
3690b57cec5SDimitry Andric     if (LocMO.isReg()) {
3700b57cec5SDimitry Andric       if (LocMO.getReg() == 0)
3710b57cec5SDimitry Andric         return UndefLocNo;
3720b57cec5SDimitry Andric       // For register locations we dont care about use/def and other flags.
3730b57cec5SDimitry Andric       for (unsigned i = 0, e = locations.size(); i != e; ++i)
3740b57cec5SDimitry Andric         if (locations[i].isReg() &&
3750b57cec5SDimitry Andric             locations[i].getReg() == LocMO.getReg() &&
3760b57cec5SDimitry Andric             locations[i].getSubReg() == LocMO.getSubReg())
3770b57cec5SDimitry Andric           return i;
3780b57cec5SDimitry Andric     } else
3790b57cec5SDimitry Andric       for (unsigned i = 0, e = locations.size(); i != e; ++i)
3800b57cec5SDimitry Andric         if (LocMO.isIdenticalTo(locations[i]))
3810b57cec5SDimitry Andric           return i;
3820b57cec5SDimitry Andric     locations.push_back(LocMO);
3830b57cec5SDimitry Andric     // We are storing a MachineOperand outside a MachineInstr.
3840b57cec5SDimitry Andric     locations.back().clearParent();
3850b57cec5SDimitry Andric     // Don't store def operands.
3860b57cec5SDimitry Andric     if (locations.back().isReg()) {
3870b57cec5SDimitry Andric       if (locations.back().isDef())
3880b57cec5SDimitry Andric         locations.back().setIsDead(false);
3890b57cec5SDimitry Andric       locations.back().setIsUse();
3900b57cec5SDimitry Andric     }
3910b57cec5SDimitry Andric     return locations.size() - 1;
3920b57cec5SDimitry Andric   }
3930b57cec5SDimitry Andric 
394480093f4SDimitry Andric   /// Remove (recycle) a location number. If \p LocNo still is used by the
395480093f4SDimitry Andric   /// locInts nothing is done.
396480093f4SDimitry Andric   void removeLocationIfUnused(unsigned LocNo) {
397480093f4SDimitry Andric     // Bail out if LocNo still is used.
398480093f4SDimitry Andric     for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
399fe6060f1SDimitry Andric       const DbgVariableValue &DbgValue = I.value();
400fe6060f1SDimitry Andric       if (DbgValue.containsLocNo(LocNo))
401480093f4SDimitry Andric         return;
402480093f4SDimitry Andric     }
403480093f4SDimitry Andric     // Remove the entry in the locations vector, and adjust all references to
404480093f4SDimitry Andric     // location numbers above the removed entry.
405480093f4SDimitry Andric     locations.erase(locations.begin() + LocNo);
406480093f4SDimitry Andric     for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
407fe6060f1SDimitry Andric       const DbgVariableValue &DbgValue = I.value();
408fe6060f1SDimitry Andric       if (DbgValue.hasLocNoGreaterThan(LocNo))
409fe6060f1SDimitry Andric         I.setValueUnchecked(DbgValue.decrementLocNosAfterPivot(LocNo));
410480093f4SDimitry Andric     }
411480093f4SDimitry Andric   }
412480093f4SDimitry Andric 
4130b57cec5SDimitry Andric   /// Ensure that all virtual register locations are mapped.
4140b57cec5SDimitry Andric   void mapVirtRegs(LDVImpl *LDV);
4150b57cec5SDimitry Andric 
4165ffd83dbSDimitry Andric   /// Add a definition point to this user value.
417fe6060f1SDimitry Andric   void addDef(SlotIndex Idx, ArrayRef<MachineOperand> LocMOs, bool IsIndirect,
418fe6060f1SDimitry Andric               bool IsList, const DIExpression &Expr) {
419fe6060f1SDimitry Andric     SmallVector<unsigned> Locs;
420349cc55cSDimitry Andric     for (const MachineOperand &Op : LocMOs)
421fe6060f1SDimitry Andric       Locs.push_back(getLocationNo(Op));
422fe6060f1SDimitry Andric     DbgVariableValue DbgValue(Locs, IsIndirect, IsList, Expr);
4235ffd83dbSDimitry Andric     // Add a singular (Idx,Idx) -> value mapping.
4240b57cec5SDimitry Andric     LocMap::iterator I = locInts.find(Idx);
4250b57cec5SDimitry Andric     if (!I.valid() || I.start() != Idx)
426fe6060f1SDimitry Andric       I.insert(Idx, Idx.getNextSlot(), std::move(DbgValue));
4270b57cec5SDimitry Andric     else
4280b57cec5SDimitry Andric       // A later DBG_VALUE at the same SlotIndex overrides the old location.
429fe6060f1SDimitry Andric       I.setValue(std::move(DbgValue));
4300b57cec5SDimitry Andric   }
4310b57cec5SDimitry Andric 
4320b57cec5SDimitry Andric   /// Extend the current definition as far as possible down.
4330b57cec5SDimitry Andric   ///
4340b57cec5SDimitry Andric   /// Stop when meeting an existing def or when leaving the live
4350b57cec5SDimitry Andric   /// range of VNI. End points where VNI is no longer live are added to Kills.
4360b57cec5SDimitry Andric   ///
4370b57cec5SDimitry Andric   /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
4380b57cec5SDimitry Andric   /// data-flow analysis to propagate them beyond basic block boundaries.
4390b57cec5SDimitry Andric   ///
4400b57cec5SDimitry Andric   /// \param Idx Starting point for the definition.
4415ffd83dbSDimitry Andric   /// \param DbgValue value to propagate.
442fe6060f1SDimitry Andric   /// \param LiveIntervalInfo For each location number key in this map,
443fe6060f1SDimitry Andric   /// restricts liveness to where the LiveRange has the value equal to the\
444fe6060f1SDimitry Andric   /// VNInfo.
4450b57cec5SDimitry Andric   /// \param [out] Kills Append end points of VNI's live range to Kills.
4460b57cec5SDimitry Andric   /// \param LIS Live intervals analysis.
447fe6060f1SDimitry Andric   void extendDef(SlotIndex Idx, DbgVariableValue DbgValue,
448fe6060f1SDimitry Andric                  SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>>
449fe6060f1SDimitry Andric                      &LiveIntervalInfo,
450fe6060f1SDimitry Andric                  Optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills,
4510b57cec5SDimitry Andric                  LiveIntervals &LIS);
4520b57cec5SDimitry Andric 
4535ffd83dbSDimitry Andric   /// The value in LI may be copies to other registers. Determine if
4540b57cec5SDimitry Andric   /// any of the copies are available at the kill points, and add defs if
4550b57cec5SDimitry Andric   /// possible.
4560b57cec5SDimitry Andric   ///
4575ffd83dbSDimitry Andric   /// \param DbgValue Location number of LI->reg, and DIExpression.
458fe6060f1SDimitry Andric   /// \param LocIntervals Scan for copies of the value for each location in the
459fe6060f1SDimitry Andric   /// corresponding LiveInterval->reg.
460fe6060f1SDimitry Andric   /// \param KilledAt The point where the range of DbgValue could be extended.
4615ffd83dbSDimitry Andric   /// \param [in,out] NewDefs Append (Idx, DbgValue) of inserted defs here.
4620b57cec5SDimitry Andric   void addDefsFromCopies(
463fe6060f1SDimitry Andric       DbgVariableValue DbgValue,
464fe6060f1SDimitry Andric       SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals,
465fe6060f1SDimitry Andric       SlotIndex KilledAt,
4665ffd83dbSDimitry Andric       SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
4670b57cec5SDimitry Andric       MachineRegisterInfo &MRI, LiveIntervals &LIS);
4680b57cec5SDimitry Andric 
4690b57cec5SDimitry Andric   /// Compute the live intervals of all locations after collecting all their
4700b57cec5SDimitry Andric   /// def points.
4710b57cec5SDimitry Andric   void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
4720b57cec5SDimitry Andric                         LiveIntervals &LIS, LexicalScopes &LS);
4730b57cec5SDimitry Andric 
4740b57cec5SDimitry Andric   /// Replace OldReg ranges with NewRegs ranges where NewRegs is
4750b57cec5SDimitry Andric   /// live. Returns true if any changes were made.
4765ffd83dbSDimitry Andric   bool splitRegister(Register OldReg, ArrayRef<Register> NewRegs,
4770b57cec5SDimitry Andric                      LiveIntervals &LIS);
4780b57cec5SDimitry Andric 
4790b57cec5SDimitry Andric   /// Rewrite virtual register locations according to the provided virtual
4800b57cec5SDimitry Andric   /// register map. Record the stack slot offsets for the locations that
4810b57cec5SDimitry Andric   /// were spilled.
4820b57cec5SDimitry Andric   void rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
4830b57cec5SDimitry Andric                         const TargetInstrInfo &TII,
4840b57cec5SDimitry Andric                         const TargetRegisterInfo &TRI,
4850b57cec5SDimitry Andric                         SpillOffsetMap &SpillOffsets);
4860b57cec5SDimitry Andric 
4870b57cec5SDimitry Andric   /// Recreate DBG_VALUE instruction from data structures.
4880b57cec5SDimitry Andric   void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
4890b57cec5SDimitry Andric                        const TargetInstrInfo &TII,
4900b57cec5SDimitry Andric                        const TargetRegisterInfo &TRI,
491fe6060f1SDimitry Andric                        const SpillOffsetMap &SpillOffsets,
492fe6060f1SDimitry Andric                        BlockSkipInstsMap &BBSkipInstsMap);
4930b57cec5SDimitry Andric 
4940b57cec5SDimitry Andric   /// Return DebugLoc of this UserValue.
495fe6060f1SDimitry Andric   const DebugLoc &getDebugLoc() { return dl; }
4960b57cec5SDimitry Andric 
4970b57cec5SDimitry Andric   void print(raw_ostream &, const TargetRegisterInfo *);
4980b57cec5SDimitry Andric };
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric /// A user label is a part of a debug info user label.
5010b57cec5SDimitry Andric class UserLabel {
5020b57cec5SDimitry Andric   const DILabel *Label; ///< The debug info label we are part of.
5030b57cec5SDimitry Andric   DebugLoc dl;          ///< The debug location for the label. This is
5040b57cec5SDimitry Andric                         ///< used by dwarf writer to find lexical scope.
5050b57cec5SDimitry Andric   SlotIndex loc;        ///< Slot used by the debug label.
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric   /// Insert a DBG_LABEL into MBB at Idx.
5080b57cec5SDimitry Andric   void insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
509fe6060f1SDimitry Andric                         LiveIntervals &LIS, const TargetInstrInfo &TII,
510fe6060f1SDimitry Andric                         BlockSkipInstsMap &BBSkipInstsMap);
5110b57cec5SDimitry Andric 
5120b57cec5SDimitry Andric public:
5130b57cec5SDimitry Andric   /// Create a new UserLabel.
5140b57cec5SDimitry Andric   UserLabel(const DILabel *label, DebugLoc L, SlotIndex Idx)
5150b57cec5SDimitry Andric       : Label(label), dl(std::move(L)), loc(Idx) {}
5160b57cec5SDimitry Andric 
5170b57cec5SDimitry Andric   /// Does this UserLabel match the parameters?
5185ffd83dbSDimitry Andric   bool matches(const DILabel *L, const DILocation *IA,
5190b57cec5SDimitry Andric              const SlotIndex Index) const {
5200b57cec5SDimitry Andric     return Label == L && dl->getInlinedAt() == IA && loc == Index;
5210b57cec5SDimitry Andric   }
5220b57cec5SDimitry Andric 
5230b57cec5SDimitry Andric   /// Recreate DBG_LABEL instruction from data structures.
524fe6060f1SDimitry Andric   void emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
525fe6060f1SDimitry Andric                       BlockSkipInstsMap &BBSkipInstsMap);
5260b57cec5SDimitry Andric 
5270b57cec5SDimitry Andric   /// Return DebugLoc of this UserLabel.
528fe6060f1SDimitry Andric   const DebugLoc &getDebugLoc() { return dl; }
5290b57cec5SDimitry Andric 
5300b57cec5SDimitry Andric   void print(raw_ostream &, const TargetRegisterInfo *);
5310b57cec5SDimitry Andric };
5320b57cec5SDimitry Andric 
5330b57cec5SDimitry Andric /// Implementation of the LiveDebugVariables pass.
5340b57cec5SDimitry Andric class LDVImpl {
5350b57cec5SDimitry Andric   LiveDebugVariables &pass;
5360b57cec5SDimitry Andric   LocMap::Allocator allocator;
5370b57cec5SDimitry Andric   MachineFunction *MF = nullptr;
5380b57cec5SDimitry Andric   LiveIntervals *LIS;
5390b57cec5SDimitry Andric   const TargetRegisterInfo *TRI;
5400b57cec5SDimitry Andric 
541fe6060f1SDimitry Andric   /// Position and VReg of a PHI instruction during register allocation.
542fe6060f1SDimitry Andric   struct PHIValPos {
543fe6060f1SDimitry Andric     SlotIndex SI;    /// Slot where this PHI occurs.
544fe6060f1SDimitry Andric     Register Reg;    /// VReg this PHI occurs in.
545fe6060f1SDimitry Andric     unsigned SubReg; /// Qualifiying subregister for Reg.
546fe6060f1SDimitry Andric   };
547fe6060f1SDimitry Andric 
548fe6060f1SDimitry Andric   /// Map from debug instruction number to PHI position during allocation.
549fe6060f1SDimitry Andric   std::map<unsigned, PHIValPos> PHIValToPos;
550fe6060f1SDimitry Andric   /// Index of, for each VReg, which debug instruction numbers and corresponding
551fe6060f1SDimitry Andric   /// PHIs are sensitive to splitting. Each VReg may have multiple PHI defs,
552fe6060f1SDimitry Andric   /// at different positions.
553fe6060f1SDimitry Andric   DenseMap<Register, std::vector<unsigned>> RegToPHIIdx;
554fe6060f1SDimitry Andric 
555fe6060f1SDimitry Andric   /// Record for any debug instructions unlinked from their blocks during
556fe6060f1SDimitry Andric   /// regalloc. Stores the instr and it's location, so that they can be
557fe6060f1SDimitry Andric   /// re-inserted after regalloc is over.
558fe6060f1SDimitry Andric   struct InstrPos {
559fe6060f1SDimitry Andric     MachineInstr *MI;       ///< Debug instruction, unlinked from it's block.
560fe6060f1SDimitry Andric     SlotIndex Idx;          ///< Slot position where MI should be re-inserted.
561fe6060f1SDimitry Andric     MachineBasicBlock *MBB; ///< Block that MI was in.
562fe6060f1SDimitry Andric   };
563fe6060f1SDimitry Andric 
564fe6060f1SDimitry Andric   /// Collection of stored debug instructions, preserved until after regalloc.
565fe6060f1SDimitry Andric   SmallVector<InstrPos, 32> StashedDebugInstrs;
566e8d8bef9SDimitry Andric 
5670b57cec5SDimitry Andric   /// Whether emitDebugValues is called.
5680b57cec5SDimitry Andric   bool EmitDone = false;
5690b57cec5SDimitry Andric 
5700b57cec5SDimitry Andric   /// Whether the machine function is modified during the pass.
5710b57cec5SDimitry Andric   bool ModifiedMF = false;
5720b57cec5SDimitry Andric 
5730b57cec5SDimitry Andric   /// All allocated UserValue instances.
5740b57cec5SDimitry Andric   SmallVector<std::unique_ptr<UserValue>, 8> userValues;
5750b57cec5SDimitry Andric 
5760b57cec5SDimitry Andric   /// All allocated UserLabel instances.
5770b57cec5SDimitry Andric   SmallVector<std::unique_ptr<UserLabel>, 2> userLabels;
5780b57cec5SDimitry Andric 
579480093f4SDimitry Andric   /// Map virtual register to eq class leader.
580480093f4SDimitry Andric   using VRMap = DenseMap<unsigned, UserValue *>;
581480093f4SDimitry Andric   VRMap virtRegToEqClass;
5820b57cec5SDimitry Andric 
5835ffd83dbSDimitry Andric   /// Map to find existing UserValue instances.
5845ffd83dbSDimitry Andric   using UVMap = DenseMap<DebugVariable, UserValue *>;
585480093f4SDimitry Andric   UVMap userVarMap;
5860b57cec5SDimitry Andric 
5870b57cec5SDimitry Andric   /// Find or create a UserValue.
5885ffd83dbSDimitry Andric   UserValue *getUserValue(const DILocalVariable *Var,
5895ffd83dbSDimitry Andric                           Optional<DIExpression::FragmentInfo> Fragment,
5900b57cec5SDimitry Andric                           const DebugLoc &DL);
5910b57cec5SDimitry Andric 
592480093f4SDimitry Andric   /// Find the EC leader for VirtReg or null.
5935ffd83dbSDimitry Andric   UserValue *lookupVirtReg(Register VirtReg);
5940b57cec5SDimitry Andric 
5950b57cec5SDimitry Andric   /// Add DBG_VALUE instruction to our maps.
5960b57cec5SDimitry Andric   ///
5970b57cec5SDimitry Andric   /// \param MI DBG_VALUE instruction
5980b57cec5SDimitry Andric   /// \param Idx Last valid SLotIndex before instruction.
5990b57cec5SDimitry Andric   ///
6000b57cec5SDimitry Andric   /// \returns True if the DBG_VALUE instruction should be deleted.
6010b57cec5SDimitry Andric   bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
6020b57cec5SDimitry Andric 
603fe6060f1SDimitry Andric   /// Track variable location debug instructions while using the instruction
604fe6060f1SDimitry Andric   /// referencing implementation. Such debug instructions do not need to be
605fe6060f1SDimitry Andric   /// updated during regalloc because they identify instructions rather than
606fe6060f1SDimitry Andric   /// register locations. However, they needs to be removed from the
607fe6060f1SDimitry Andric   /// MachineFunction during regalloc, then re-inserted later, to avoid
608fe6060f1SDimitry Andric   /// disrupting the allocator.
609e8d8bef9SDimitry Andric   ///
610fe6060f1SDimitry Andric   /// \param MI Any DBG_VALUE / DBG_INSTR_REF / DBG_PHI instruction
611e8d8bef9SDimitry Andric   /// \param Idx Last valid SlotIndex before instruction
612e8d8bef9SDimitry Andric   ///
613fe6060f1SDimitry Andric   /// \returns Iterator to continue processing from after unlinking.
614fe6060f1SDimitry Andric   MachineBasicBlock::iterator handleDebugInstr(MachineInstr &MI, SlotIndex Idx);
615e8d8bef9SDimitry Andric 
6160b57cec5SDimitry Andric   /// Add DBG_LABEL instruction to UserLabel.
6170b57cec5SDimitry Andric   ///
6180b57cec5SDimitry Andric   /// \param MI DBG_LABEL instruction
6190b57cec5SDimitry Andric   /// \param Idx Last valid SlotIndex before instruction.
6200b57cec5SDimitry Andric   ///
6210b57cec5SDimitry Andric   /// \returns True if the DBG_LABEL instruction should be deleted.
6220b57cec5SDimitry Andric   bool handleDebugLabel(MachineInstr &MI, SlotIndex Idx);
6230b57cec5SDimitry Andric 
6240b57cec5SDimitry Andric   /// Collect and erase all DBG_VALUE instructions, adding a UserValue def
6250b57cec5SDimitry Andric   /// for each instruction.
6260b57cec5SDimitry Andric   ///
6270b57cec5SDimitry Andric   /// \param mf MachineFunction to be scanned.
628fe6060f1SDimitry Andric   /// \param InstrRef Whether to operate in instruction referencing mode. If
629fe6060f1SDimitry Andric   ///        true, most of LiveDebugVariables doesn't run.
6300b57cec5SDimitry Andric   ///
6310b57cec5SDimitry Andric   /// \returns True if any debug values were found.
632fe6060f1SDimitry Andric   bool collectDebugValues(MachineFunction &mf, bool InstrRef);
6330b57cec5SDimitry Andric 
6340b57cec5SDimitry Andric   /// Compute the live intervals of all user values after collecting all
6350b57cec5SDimitry Andric   /// their def points.
6360b57cec5SDimitry Andric   void computeIntervals();
6370b57cec5SDimitry Andric 
6380b57cec5SDimitry Andric public:
6390b57cec5SDimitry Andric   LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
6400b57cec5SDimitry Andric 
641fe6060f1SDimitry Andric   bool runOnMachineFunction(MachineFunction &mf, bool InstrRef);
6420b57cec5SDimitry Andric 
6430b57cec5SDimitry Andric   /// Release all memory.
6440b57cec5SDimitry Andric   void clear() {
6450b57cec5SDimitry Andric     MF = nullptr;
646fe6060f1SDimitry Andric     PHIValToPos.clear();
647fe6060f1SDimitry Andric     RegToPHIIdx.clear();
648fe6060f1SDimitry Andric     StashedDebugInstrs.clear();
6490b57cec5SDimitry Andric     userValues.clear();
6500b57cec5SDimitry Andric     userLabels.clear();
651480093f4SDimitry Andric     virtRegToEqClass.clear();
652480093f4SDimitry Andric     userVarMap.clear();
6530b57cec5SDimitry Andric     // Make sure we call emitDebugValues if the machine function was modified.
6540b57cec5SDimitry Andric     assert((!ModifiedMF || EmitDone) &&
6550b57cec5SDimitry Andric            "Dbg values are not emitted in LDV");
6560b57cec5SDimitry Andric     EmitDone = false;
6570b57cec5SDimitry Andric     ModifiedMF = false;
6580b57cec5SDimitry Andric   }
6590b57cec5SDimitry Andric 
660480093f4SDimitry Andric   /// Map virtual register to an equivalence class.
6615ffd83dbSDimitry Andric   void mapVirtReg(Register VirtReg, UserValue *EC);
6620b57cec5SDimitry Andric 
663fe6060f1SDimitry Andric   /// Replace any PHI referring to OldReg with its corresponding NewReg, if
664fe6060f1SDimitry Andric   /// present.
665fe6060f1SDimitry Andric   void splitPHIRegister(Register OldReg, ArrayRef<Register> NewRegs);
666fe6060f1SDimitry Andric 
6670b57cec5SDimitry Andric   /// Replace all references to OldReg with NewRegs.
6685ffd83dbSDimitry Andric   void splitRegister(Register OldReg, ArrayRef<Register> NewRegs);
6690b57cec5SDimitry Andric 
6700b57cec5SDimitry Andric   /// Recreate DBG_VALUE instruction from data structures.
6710b57cec5SDimitry Andric   void emitDebugValues(VirtRegMap *VRM);
6720b57cec5SDimitry Andric 
6730b57cec5SDimitry Andric   void print(raw_ostream&);
6740b57cec5SDimitry Andric };
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric } // end anonymous namespace
6770b57cec5SDimitry Andric 
6780b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
6790b57cec5SDimitry Andric static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
6800b57cec5SDimitry Andric                           const LLVMContext &Ctx) {
6810b57cec5SDimitry Andric   if (!DL)
6820b57cec5SDimitry Andric     return;
6830b57cec5SDimitry Andric 
6840b57cec5SDimitry Andric   auto *Scope = cast<DIScope>(DL.getScope());
6850b57cec5SDimitry Andric   // Omit the directory, because it's likely to be long and uninteresting.
6860b57cec5SDimitry Andric   CommentOS << Scope->getFilename();
6870b57cec5SDimitry Andric   CommentOS << ':' << DL.getLine();
6880b57cec5SDimitry Andric   if (DL.getCol() != 0)
6890b57cec5SDimitry Andric     CommentOS << ':' << DL.getCol();
6900b57cec5SDimitry Andric 
6910b57cec5SDimitry Andric   DebugLoc InlinedAtDL = DL.getInlinedAt();
6920b57cec5SDimitry Andric   if (!InlinedAtDL)
6930b57cec5SDimitry Andric     return;
6940b57cec5SDimitry Andric 
6950b57cec5SDimitry Andric   CommentOS << " @[ ";
6960b57cec5SDimitry Andric   printDebugLoc(InlinedAtDL, CommentOS, Ctx);
6970b57cec5SDimitry Andric   CommentOS << " ]";
6980b57cec5SDimitry Andric }
6990b57cec5SDimitry Andric 
7000b57cec5SDimitry Andric static void printExtendedName(raw_ostream &OS, const DINode *Node,
7010b57cec5SDimitry Andric                               const DILocation *DL) {
7020b57cec5SDimitry Andric   const LLVMContext &Ctx = Node->getContext();
7030b57cec5SDimitry Andric   StringRef Res;
704480093f4SDimitry Andric   unsigned Line = 0;
7050b57cec5SDimitry Andric   if (const auto *V = dyn_cast<const DILocalVariable>(Node)) {
7060b57cec5SDimitry Andric     Res = V->getName();
7070b57cec5SDimitry Andric     Line = V->getLine();
7080b57cec5SDimitry Andric   } else if (const auto *L = dyn_cast<const DILabel>(Node)) {
7090b57cec5SDimitry Andric     Res = L->getName();
7100b57cec5SDimitry Andric     Line = L->getLine();
7110b57cec5SDimitry Andric   }
7120b57cec5SDimitry Andric 
7130b57cec5SDimitry Andric   if (!Res.empty())
7140b57cec5SDimitry Andric     OS << Res << "," << Line;
7150b57cec5SDimitry Andric   auto *InlinedAt = DL ? DL->getInlinedAt() : nullptr;
7160b57cec5SDimitry Andric   if (InlinedAt) {
7170b57cec5SDimitry Andric     if (DebugLoc InlinedAtDL = InlinedAt) {
7180b57cec5SDimitry Andric       OS << " @[";
7190b57cec5SDimitry Andric       printDebugLoc(InlinedAtDL, OS, Ctx);
7200b57cec5SDimitry Andric       OS << "]";
7210b57cec5SDimitry Andric     }
7220b57cec5SDimitry Andric   }
7230b57cec5SDimitry Andric }
7240b57cec5SDimitry Andric 
7250b57cec5SDimitry Andric void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
7260b57cec5SDimitry Andric   OS << "!\"";
7270b57cec5SDimitry Andric   printExtendedName(OS, Variable, dl);
7280b57cec5SDimitry Andric 
7290b57cec5SDimitry Andric   OS << "\"\t";
7300b57cec5SDimitry Andric   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
7310b57cec5SDimitry Andric     OS << " [" << I.start() << ';' << I.stop() << "):";
7320b57cec5SDimitry Andric     if (I.value().isUndef())
7330b57cec5SDimitry Andric       OS << " undef";
7340b57cec5SDimitry Andric     else {
735fe6060f1SDimitry Andric       I.value().printLocNos(OS);
7365ffd83dbSDimitry Andric       if (I.value().getWasIndirect())
73713138422SDimitry Andric         OS << " ind";
738fe6060f1SDimitry Andric       else if (I.value().getWasList())
739fe6060f1SDimitry Andric         OS << " list";
7400b57cec5SDimitry Andric     }
7410b57cec5SDimitry Andric   }
7420b57cec5SDimitry Andric   for (unsigned i = 0, e = locations.size(); i != e; ++i) {
7430b57cec5SDimitry Andric     OS << " Loc" << i << '=';
7440b57cec5SDimitry Andric     locations[i].print(OS, TRI);
7450b57cec5SDimitry Andric   }
7460b57cec5SDimitry Andric   OS << '\n';
7470b57cec5SDimitry Andric }
7480b57cec5SDimitry Andric 
7490b57cec5SDimitry Andric void UserLabel::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
7500b57cec5SDimitry Andric   OS << "!\"";
7510b57cec5SDimitry Andric   printExtendedName(OS, Label, dl);
7520b57cec5SDimitry Andric 
7530b57cec5SDimitry Andric   OS << "\"\t";
7540b57cec5SDimitry Andric   OS << loc;
7550b57cec5SDimitry Andric   OS << '\n';
7560b57cec5SDimitry Andric }
7570b57cec5SDimitry Andric 
7580b57cec5SDimitry Andric void LDVImpl::print(raw_ostream &OS) {
7590b57cec5SDimitry Andric   OS << "********** DEBUG VARIABLES **********\n";
7600b57cec5SDimitry Andric   for (auto &userValue : userValues)
7610b57cec5SDimitry Andric     userValue->print(OS, TRI);
7620b57cec5SDimitry Andric   OS << "********** DEBUG LABELS **********\n";
7630b57cec5SDimitry Andric   for (auto &userLabel : userLabels)
7640b57cec5SDimitry Andric     userLabel->print(OS, TRI);
7650b57cec5SDimitry Andric }
7660b57cec5SDimitry Andric #endif
7670b57cec5SDimitry Andric 
7680b57cec5SDimitry Andric void UserValue::mapVirtRegs(LDVImpl *LDV) {
7690b57cec5SDimitry Andric   for (unsigned i = 0, e = locations.size(); i != e; ++i)
7700b57cec5SDimitry Andric     if (locations[i].isReg() &&
7718bcb0991SDimitry Andric         Register::isVirtualRegister(locations[i].getReg()))
7720b57cec5SDimitry Andric       LDV->mapVirtReg(locations[i].getReg(), this);
7730b57cec5SDimitry Andric }
7740b57cec5SDimitry Andric 
7750b57cec5SDimitry Andric UserValue *LDVImpl::getUserValue(const DILocalVariable *Var,
7765ffd83dbSDimitry Andric                                  Optional<DIExpression::FragmentInfo> Fragment,
7775ffd83dbSDimitry Andric                                  const DebugLoc &DL) {
7785ffd83dbSDimitry Andric   // FIXME: Handle partially overlapping fragments. See
7795ffd83dbSDimitry Andric   // https://reviews.llvm.org/D70121#1849741.
7805ffd83dbSDimitry Andric   DebugVariable ID(Var, Fragment, DL->getInlinedAt());
7815ffd83dbSDimitry Andric   UserValue *&UV = userVarMap[ID];
7825ffd83dbSDimitry Andric   if (!UV) {
783480093f4SDimitry Andric     userValues.push_back(
7845ffd83dbSDimitry Andric         std::make_unique<UserValue>(Var, Fragment, DL, allocator));
7855ffd83dbSDimitry Andric     UV = userValues.back().get();
7865ffd83dbSDimitry Andric   }
787480093f4SDimitry Andric   return UV;
788480093f4SDimitry Andric }
789480093f4SDimitry Andric 
7905ffd83dbSDimitry Andric void LDVImpl::mapVirtReg(Register VirtReg, UserValue *EC) {
7918bcb0991SDimitry Andric   assert(Register::isVirtualRegister(VirtReg) && "Only map VirtRegs");
792480093f4SDimitry Andric   UserValue *&Leader = virtRegToEqClass[VirtReg];
793480093f4SDimitry Andric   Leader = UserValue::merge(Leader, EC);
7940b57cec5SDimitry Andric }
7950b57cec5SDimitry Andric 
7965ffd83dbSDimitry Andric UserValue *LDVImpl::lookupVirtReg(Register VirtReg) {
797480093f4SDimitry Andric   if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
798480093f4SDimitry Andric     return UV->getLeader();
7990b57cec5SDimitry Andric   return nullptr;
8000b57cec5SDimitry Andric }
8010b57cec5SDimitry Andric 
8020b57cec5SDimitry Andric bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
803fe6060f1SDimitry Andric   // DBG_VALUE loc, offset, variable, expr
804fe6060f1SDimitry Andric   // DBG_VALUE_LIST variable, expr, locs...
805fe6060f1SDimitry Andric   if (!MI.isDebugValue()) {
806fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't handle non-DBG_VALUE*: " << MI);
807fe6060f1SDimitry Andric     return false;
808fe6060f1SDimitry Andric   }
809fe6060f1SDimitry Andric   if (!MI.getDebugVariableOp().isMetadata()) {
810fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't handle DBG_VALUE* with invalid variable: "
811fe6060f1SDimitry Andric                       << MI);
812fe6060f1SDimitry Andric     return false;
813fe6060f1SDimitry Andric   }
814fe6060f1SDimitry Andric   if (MI.isNonListDebugValue() &&
815fe6060f1SDimitry Andric       (MI.getNumOperands() != 4 ||
816fe6060f1SDimitry Andric        !(MI.getDebugOffset().isImm() || MI.getDebugOffset().isReg()))) {
817fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't handle malformed DBG_VALUE: " << MI);
8180b57cec5SDimitry Andric     return false;
8190b57cec5SDimitry Andric   }
8200b57cec5SDimitry Andric 
8210b57cec5SDimitry Andric   // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual
8220b57cec5SDimitry Andric   // register that hasn't been defined yet. If we do not remove those here, then
8230b57cec5SDimitry Andric   // the re-insertion of the DBG_VALUE instruction after register allocation
8240b57cec5SDimitry Andric   // will be incorrect.
8250b57cec5SDimitry Andric   bool Discard = false;
826fe6060f1SDimitry Andric   for (const MachineOperand &Op : MI.debug_operands()) {
827fe6060f1SDimitry Andric     if (Op.isReg() && Register::isVirtualRegister(Op.getReg())) {
828fe6060f1SDimitry Andric       const Register Reg = Op.getReg();
8290b57cec5SDimitry Andric       if (!LIS->hasInterval(Reg)) {
8300b57cec5SDimitry Andric         // The DBG_VALUE is described by a virtual register that does not have a
8310b57cec5SDimitry Andric         // live interval. Discard the DBG_VALUE.
8320b57cec5SDimitry Andric         Discard = true;
8330b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx
8340b57cec5SDimitry Andric                           << " " << MI);
8350b57cec5SDimitry Andric       } else {
836fe6060f1SDimitry Andric         // The DBG_VALUE is only valid if either Reg is live out from Idx, or
837fe6060f1SDimitry Andric         // Reg is defined dead at Idx (where Idx is the slot index for the
838fe6060f1SDimitry Andric         // instruction preceding the DBG_VALUE).
8390b57cec5SDimitry Andric         const LiveInterval &LI = LIS->getInterval(Reg);
8400b57cec5SDimitry Andric         LiveQueryResult LRQ = LI.Query(Idx);
8410b57cec5SDimitry Andric         if (!LRQ.valueOutOrDead()) {
8420b57cec5SDimitry Andric           // We have found a DBG_VALUE with the value in a virtual register that
8430b57cec5SDimitry Andric           // is not live. Discard the DBG_VALUE.
8440b57cec5SDimitry Andric           Discard = true;
8450b57cec5SDimitry Andric           LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx
8460b57cec5SDimitry Andric                             << " " << MI);
8470b57cec5SDimitry Andric         }
8480b57cec5SDimitry Andric       }
8490b57cec5SDimitry Andric     }
850fe6060f1SDimitry Andric   }
8510b57cec5SDimitry Andric 
8520b57cec5SDimitry Andric   // Get or create the UserValue for (variable,offset) here.
8535ffd83dbSDimitry Andric   bool IsIndirect = MI.isDebugOffsetImm();
85413138422SDimitry Andric   if (IsIndirect)
8555ffd83dbSDimitry Andric     assert(MI.getDebugOffset().getImm() == 0 &&
8565ffd83dbSDimitry Andric            "DBG_VALUE with nonzero offset");
857fe6060f1SDimitry Andric   bool IsList = MI.isDebugValueList();
8580b57cec5SDimitry Andric   const DILocalVariable *Var = MI.getDebugVariable();
8590b57cec5SDimitry Andric   const DIExpression *Expr = MI.getDebugExpression();
8605ffd83dbSDimitry Andric   UserValue *UV = getUserValue(Var, Expr->getFragmentInfo(), MI.getDebugLoc());
8610b57cec5SDimitry Andric   if (!Discard)
862fe6060f1SDimitry Andric     UV->addDef(Idx,
863fe6060f1SDimitry Andric                ArrayRef<MachineOperand>(MI.debug_operands().begin(),
864fe6060f1SDimitry Andric                                         MI.debug_operands().end()),
865fe6060f1SDimitry Andric                IsIndirect, IsList, *Expr);
8660b57cec5SDimitry Andric   else {
8670b57cec5SDimitry Andric     MachineOperand MO = MachineOperand::CreateReg(0U, false);
8680b57cec5SDimitry Andric     MO.setIsDebug();
869fe6060f1SDimitry Andric     // We should still pass a list the same size as MI.debug_operands() even if
870fe6060f1SDimitry Andric     // all MOs are undef, so that DbgVariableValue can correctly adjust the
871fe6060f1SDimitry Andric     // expression while removing the duplicated undefs.
872fe6060f1SDimitry Andric     SmallVector<MachineOperand, 4> UndefMOs(MI.getNumDebugOperands(), MO);
873fe6060f1SDimitry Andric     UV->addDef(Idx, UndefMOs, false, IsList, *Expr);
8740b57cec5SDimitry Andric   }
8750b57cec5SDimitry Andric   return true;
8760b57cec5SDimitry Andric }
8770b57cec5SDimitry Andric 
878fe6060f1SDimitry Andric MachineBasicBlock::iterator LDVImpl::handleDebugInstr(MachineInstr &MI,
879fe6060f1SDimitry Andric                                                       SlotIndex Idx) {
880fe6060f1SDimitry Andric   assert(MI.isDebugValue() || MI.isDebugRef() || MI.isDebugPHI());
881fe6060f1SDimitry Andric 
882fe6060f1SDimitry Andric   // In instruction referencing mode, there should be no DBG_VALUE instructions
883fe6060f1SDimitry Andric   // that refer to virtual registers. They might still refer to constants.
884fe6060f1SDimitry Andric   if (MI.isDebugValue())
885fe6060f1SDimitry Andric     assert(!MI.getOperand(0).isReg() || !MI.getOperand(0).getReg().isVirtual());
886fe6060f1SDimitry Andric 
887fe6060f1SDimitry Andric   // Unlink the instruction, store it in the debug instructions collection.
888fe6060f1SDimitry Andric   auto NextInst = std::next(MI.getIterator());
889fe6060f1SDimitry Andric   auto *MBB = MI.getParent();
890fe6060f1SDimitry Andric   MI.removeFromParent();
891fe6060f1SDimitry Andric   StashedDebugInstrs.push_back({&MI, Idx, MBB});
892fe6060f1SDimitry Andric   return NextInst;
893e8d8bef9SDimitry Andric }
894e8d8bef9SDimitry Andric 
8950b57cec5SDimitry Andric bool LDVImpl::handleDebugLabel(MachineInstr &MI, SlotIndex Idx) {
8960b57cec5SDimitry Andric   // DBG_LABEL label
8970b57cec5SDimitry Andric   if (MI.getNumOperands() != 1 || !MI.getOperand(0).isMetadata()) {
8980b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't handle " << MI);
8990b57cec5SDimitry Andric     return false;
9000b57cec5SDimitry Andric   }
9010b57cec5SDimitry Andric 
9020b57cec5SDimitry Andric   // Get or create the UserLabel for label here.
9030b57cec5SDimitry Andric   const DILabel *Label = MI.getDebugLabel();
9040b57cec5SDimitry Andric   const DebugLoc &DL = MI.getDebugLoc();
9050b57cec5SDimitry Andric   bool Found = false;
9060b57cec5SDimitry Andric   for (auto const &L : userLabels) {
9075ffd83dbSDimitry Andric     if (L->matches(Label, DL->getInlinedAt(), Idx)) {
9080b57cec5SDimitry Andric       Found = true;
9090b57cec5SDimitry Andric       break;
9100b57cec5SDimitry Andric     }
9110b57cec5SDimitry Andric   }
9120b57cec5SDimitry Andric   if (!Found)
9138bcb0991SDimitry Andric     userLabels.push_back(std::make_unique<UserLabel>(Label, DL, Idx));
9140b57cec5SDimitry Andric 
9150b57cec5SDimitry Andric   return true;
9160b57cec5SDimitry Andric }
9170b57cec5SDimitry Andric 
918fe6060f1SDimitry Andric bool LDVImpl::collectDebugValues(MachineFunction &mf, bool InstrRef) {
9190b57cec5SDimitry Andric   bool Changed = false;
920fe6060f1SDimitry Andric   for (MachineBasicBlock &MBB : mf) {
921fe6060f1SDimitry Andric     for (MachineBasicBlock::iterator MBBI = MBB.begin(), MBBE = MBB.end();
9220b57cec5SDimitry Andric          MBBI != MBBE;) {
9230b57cec5SDimitry Andric       // Use the first debug instruction in the sequence to get a SlotIndex
9240b57cec5SDimitry Andric       // for following consecutive debug instructions.
925fe6060f1SDimitry Andric       if (!MBBI->isDebugOrPseudoInstr()) {
9260b57cec5SDimitry Andric         ++MBBI;
9270b57cec5SDimitry Andric         continue;
9280b57cec5SDimitry Andric       }
9290b57cec5SDimitry Andric       // Debug instructions has no slot index. Use the previous
9300b57cec5SDimitry Andric       // non-debug instruction's SlotIndex as its SlotIndex.
9310b57cec5SDimitry Andric       SlotIndex Idx =
932fe6060f1SDimitry Andric           MBBI == MBB.begin()
933fe6060f1SDimitry Andric               ? LIS->getMBBStartIdx(&MBB)
9340b57cec5SDimitry Andric               : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
9350b57cec5SDimitry Andric       // Handle consecutive debug instructions with the same slot index.
9360b57cec5SDimitry Andric       do {
937fe6060f1SDimitry Andric         // In instruction referencing mode, pass each instr to handleDebugInstr
938fe6060f1SDimitry Andric         // to be unlinked. Ignore DBG_VALUE_LISTs -- they refer to vregs, and
939fe6060f1SDimitry Andric         // need to go through the normal live interval splitting process.
940fe6060f1SDimitry Andric         if (InstrRef && (MBBI->isNonListDebugValue() || MBBI->isDebugPHI() ||
941fe6060f1SDimitry Andric                          MBBI->isDebugRef())) {
942fe6060f1SDimitry Andric           MBBI = handleDebugInstr(*MBBI, Idx);
943fe6060f1SDimitry Andric           Changed = true;
944fe6060f1SDimitry Andric         // In normal debug mode, use the dedicated DBG_VALUE / DBG_LABEL handler
945fe6060f1SDimitry Andric         // to track things through register allocation, and erase the instr.
946fe6060f1SDimitry Andric         } else if ((MBBI->isDebugValue() && handleDebugValue(*MBBI, Idx)) ||
9470b57cec5SDimitry Andric                    (MBBI->isDebugLabel() && handleDebugLabel(*MBBI, Idx))) {
948fe6060f1SDimitry Andric           MBBI = MBB.erase(MBBI);
9490b57cec5SDimitry Andric           Changed = true;
9500b57cec5SDimitry Andric         } else
9510b57cec5SDimitry Andric           ++MBBI;
952fe6060f1SDimitry Andric       } while (MBBI != MBBE && MBBI->isDebugOrPseudoInstr());
9530b57cec5SDimitry Andric     }
9540b57cec5SDimitry Andric   }
9550b57cec5SDimitry Andric   return Changed;
9560b57cec5SDimitry Andric }
9570b57cec5SDimitry Andric 
958fe6060f1SDimitry Andric void UserValue::extendDef(
959fe6060f1SDimitry Andric     SlotIndex Idx, DbgVariableValue DbgValue,
960fe6060f1SDimitry Andric     SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>>
961fe6060f1SDimitry Andric         &LiveIntervalInfo,
962fe6060f1SDimitry Andric     Optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills,
9630b57cec5SDimitry Andric     LiveIntervals &LIS) {
9640b57cec5SDimitry Andric   SlotIndex Start = Idx;
9650b57cec5SDimitry Andric   MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
9660b57cec5SDimitry Andric   SlotIndex Stop = LIS.getMBBEndIdx(MBB);
9670b57cec5SDimitry Andric   LocMap::iterator I = locInts.find(Start);
9680b57cec5SDimitry Andric 
969fe6060f1SDimitry Andric   // Limit to the intersection of the VNIs' live ranges.
970fe6060f1SDimitry Andric   for (auto &LII : LiveIntervalInfo) {
971fe6060f1SDimitry Andric     LiveRange *LR = LII.second.first;
972fe6060f1SDimitry Andric     assert(LR && LII.second.second && "Missing range info for Idx.");
9730b57cec5SDimitry Andric     LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
974fe6060f1SDimitry Andric     assert(Segment && Segment->valno == LII.second.second &&
975fe6060f1SDimitry Andric            "Invalid VNInfo for Idx given?");
9760b57cec5SDimitry Andric     if (Segment->end < Stop) {
9770b57cec5SDimitry Andric       Stop = Segment->end;
978fe6060f1SDimitry Andric       Kills = {Stop, {LII.first}};
979fe6060f1SDimitry Andric     } else if (Segment->end == Stop && Kills.hasValue()) {
980fe6060f1SDimitry Andric       // If multiple locations end at the same place, track all of them in
981fe6060f1SDimitry Andric       // Kills.
982fe6060f1SDimitry Andric       Kills->second.push_back(LII.first);
9830b57cec5SDimitry Andric     }
9840b57cec5SDimitry Andric   }
9850b57cec5SDimitry Andric 
9860b57cec5SDimitry Andric   // There could already be a short def at Start.
9870b57cec5SDimitry Andric   if (I.valid() && I.start() <= Start) {
9880b57cec5SDimitry Andric     // Stop when meeting a different location or an already extended interval.
9890b57cec5SDimitry Andric     Start = Start.getNextSlot();
990fe6060f1SDimitry Andric     if (I.value() != DbgValue || I.stop() != Start) {
991fe6060f1SDimitry Andric       // Clear `Kills`, as we have a new def available.
992fe6060f1SDimitry Andric       Kills = None;
9930b57cec5SDimitry Andric       return;
994fe6060f1SDimitry Andric     }
9950b57cec5SDimitry Andric     // This is a one-slot placeholder. Just skip it.
9960b57cec5SDimitry Andric     ++I;
9970b57cec5SDimitry Andric   }
9980b57cec5SDimitry Andric 
9990b57cec5SDimitry Andric   // Limited by the next def.
1000fe6060f1SDimitry Andric   if (I.valid() && I.start() < Stop) {
10010b57cec5SDimitry Andric     Stop = I.start();
1002fe6060f1SDimitry Andric     // Clear `Kills`, as we have a new def available.
1003fe6060f1SDimitry Andric     Kills = None;
1004fe6060f1SDimitry Andric   }
10050b57cec5SDimitry Andric 
1006fe6060f1SDimitry Andric   if (Start < Stop) {
1007fe6060f1SDimitry Andric     DbgVariableValue ExtDbgValue(DbgValue);
1008fe6060f1SDimitry Andric     I.insert(Start, Stop, std::move(ExtDbgValue));
1009fe6060f1SDimitry Andric   }
10100b57cec5SDimitry Andric }
10110b57cec5SDimitry Andric 
10120b57cec5SDimitry Andric void UserValue::addDefsFromCopies(
1013fe6060f1SDimitry Andric     DbgVariableValue DbgValue,
1014fe6060f1SDimitry Andric     SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals,
1015fe6060f1SDimitry Andric     SlotIndex KilledAt,
10165ffd83dbSDimitry Andric     SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
10170b57cec5SDimitry Andric     MachineRegisterInfo &MRI, LiveIntervals &LIS) {
10180b57cec5SDimitry Andric   // Don't track copies from physregs, there are too many uses.
1019fe6060f1SDimitry Andric   if (any_of(LocIntervals, [](auto LocI) {
1020fe6060f1SDimitry Andric         return !Register::isVirtualRegister(LocI.second->reg());
1021fe6060f1SDimitry Andric       }))
10220b57cec5SDimitry Andric     return;
10230b57cec5SDimitry Andric 
10240b57cec5SDimitry Andric   // Collect all the (vreg, valno) pairs that are copies of LI.
1025fe6060f1SDimitry Andric   SmallDenseMap<unsigned,
1026fe6060f1SDimitry Andric                 SmallVector<std::pair<LiveInterval *, const VNInfo *>, 4>>
1027fe6060f1SDimitry Andric       CopyValues;
1028fe6060f1SDimitry Andric   for (auto &LocInterval : LocIntervals) {
1029fe6060f1SDimitry Andric     unsigned LocNo = LocInterval.first;
1030fe6060f1SDimitry Andric     LiveInterval *LI = LocInterval.second;
1031e8d8bef9SDimitry Andric     for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg())) {
10320b57cec5SDimitry Andric       MachineInstr *MI = MO.getParent();
10330b57cec5SDimitry Andric       // Copies of the full value.
10340b57cec5SDimitry Andric       if (MO.getSubReg() || !MI->isCopy())
10350b57cec5SDimitry Andric         continue;
10368bcb0991SDimitry Andric       Register DstReg = MI->getOperand(0).getReg();
10370b57cec5SDimitry Andric 
10380b57cec5SDimitry Andric       // Don't follow copies to physregs. These are usually setting up call
10390b57cec5SDimitry Andric       // arguments, and the argument registers are always call clobbered. We are
1040fe6060f1SDimitry Andric       // better off in the source register which could be a callee-saved
1041fe6060f1SDimitry Andric       // register, or it could be spilled.
10428bcb0991SDimitry Andric       if (!Register::isVirtualRegister(DstReg))
10430b57cec5SDimitry Andric         continue;
10440b57cec5SDimitry Andric 
10455ffd83dbSDimitry Andric       // Is the value extended to reach this copy? If not, another def may be
10465ffd83dbSDimitry Andric       // blocking it, or we are looking at a wrong value of LI.
10470b57cec5SDimitry Andric       SlotIndex Idx = LIS.getInstructionIndex(*MI);
10480b57cec5SDimitry Andric       LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
10495ffd83dbSDimitry Andric       if (!I.valid() || I.value() != DbgValue)
10500b57cec5SDimitry Andric         continue;
10510b57cec5SDimitry Andric 
10520b57cec5SDimitry Andric       if (!LIS.hasInterval(DstReg))
10530b57cec5SDimitry Andric         continue;
10540b57cec5SDimitry Andric       LiveInterval *DstLI = &LIS.getInterval(DstReg);
10550b57cec5SDimitry Andric       const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
10560b57cec5SDimitry Andric       assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
1057fe6060f1SDimitry Andric       CopyValues[LocNo].push_back(std::make_pair(DstLI, DstVNI));
1058fe6060f1SDimitry Andric     }
10590b57cec5SDimitry Andric   }
10600b57cec5SDimitry Andric 
10610b57cec5SDimitry Andric   if (CopyValues.empty())
10620b57cec5SDimitry Andric     return;
10630b57cec5SDimitry Andric 
1064fe6060f1SDimitry Andric #if !defined(NDEBUG)
1065fe6060f1SDimitry Andric   for (auto &LocInterval : LocIntervals)
1066fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "Got " << CopyValues[LocInterval.first].size()
1067fe6060f1SDimitry Andric                       << " copies of " << *LocInterval.second << '\n');
1068fe6060f1SDimitry Andric #endif
10690b57cec5SDimitry Andric 
1070fe6060f1SDimitry Andric   // Try to add defs of the copied values for the kill point. Check that there
1071fe6060f1SDimitry Andric   // isn't already a def at Idx.
1072fe6060f1SDimitry Andric   LocMap::iterator I = locInts.find(KilledAt);
1073fe6060f1SDimitry Andric   if (I.valid() && I.start() <= KilledAt)
1074fe6060f1SDimitry Andric     return;
1075fe6060f1SDimitry Andric   DbgVariableValue NewValue(DbgValue);
1076fe6060f1SDimitry Andric   for (auto &LocInterval : LocIntervals) {
1077fe6060f1SDimitry Andric     unsigned LocNo = LocInterval.first;
1078fe6060f1SDimitry Andric     bool FoundCopy = false;
1079fe6060f1SDimitry Andric     for (auto &LIAndVNI : CopyValues[LocNo]) {
1080fe6060f1SDimitry Andric       LiveInterval *DstLI = LIAndVNI.first;
1081fe6060f1SDimitry Andric       const VNInfo *DstVNI = LIAndVNI.second;
1082fe6060f1SDimitry Andric       if (DstLI->getVNInfoAt(KilledAt) != DstVNI)
10830b57cec5SDimitry Andric         continue;
1084fe6060f1SDimitry Andric       LLVM_DEBUG(dbgs() << "Kill at " << KilledAt << " covered by valno #"
10850b57cec5SDimitry Andric                         << DstVNI->id << " in " << *DstLI << '\n');
10860b57cec5SDimitry Andric       MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
10870b57cec5SDimitry Andric       assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
1088fe6060f1SDimitry Andric       unsigned NewLocNo = getLocationNo(CopyMI->getOperand(0));
1089fe6060f1SDimitry Andric       NewValue = NewValue.changeLocNo(LocNo, NewLocNo);
1090fe6060f1SDimitry Andric       FoundCopy = true;
10910b57cec5SDimitry Andric       break;
10920b57cec5SDimitry Andric     }
1093fe6060f1SDimitry Andric     // If there are any killed locations we can't find a copy for, we can't
1094fe6060f1SDimitry Andric     // extend the variable value.
1095fe6060f1SDimitry Andric     if (!FoundCopy)
1096fe6060f1SDimitry Andric       return;
10970b57cec5SDimitry Andric   }
1098fe6060f1SDimitry Andric   I.insert(KilledAt, KilledAt.getNextSlot(), NewValue);
1099fe6060f1SDimitry Andric   NewDefs.push_back(std::make_pair(KilledAt, NewValue));
11000b57cec5SDimitry Andric }
11010b57cec5SDimitry Andric 
11020b57cec5SDimitry Andric void UserValue::computeIntervals(MachineRegisterInfo &MRI,
11030b57cec5SDimitry Andric                                  const TargetRegisterInfo &TRI,
11040b57cec5SDimitry Andric                                  LiveIntervals &LIS, LexicalScopes &LS) {
11055ffd83dbSDimitry Andric   SmallVector<std::pair<SlotIndex, DbgVariableValue>, 16> Defs;
11060b57cec5SDimitry Andric 
11070b57cec5SDimitry Andric   // Collect all defs to be extended (Skipping undefs).
11080b57cec5SDimitry Andric   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
11090b57cec5SDimitry Andric     if (!I.value().isUndef())
11100b57cec5SDimitry Andric       Defs.push_back(std::make_pair(I.start(), I.value()));
11110b57cec5SDimitry Andric 
11120b57cec5SDimitry Andric   // Extend all defs, and possibly add new ones along the way.
11130b57cec5SDimitry Andric   for (unsigned i = 0; i != Defs.size(); ++i) {
11140b57cec5SDimitry Andric     SlotIndex Idx = Defs[i].first;
11155ffd83dbSDimitry Andric     DbgVariableValue DbgValue = Defs[i].second;
1116fe6060f1SDimitry Andric     SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>> LIs;
1117fe6060f1SDimitry Andric     SmallVector<const VNInfo *, 4> VNIs;
1118fe6060f1SDimitry Andric     bool ShouldExtendDef = false;
1119fe6060f1SDimitry Andric     for (unsigned LocNo : DbgValue.loc_nos()) {
1120fe6060f1SDimitry Andric       const MachineOperand &LocMO = locations[LocNo];
1121fe6060f1SDimitry Andric       if (!LocMO.isReg() || !Register::isVirtualRegister(LocMO.getReg())) {
1122fe6060f1SDimitry Andric         ShouldExtendDef |= !LocMO.isReg();
11230b57cec5SDimitry Andric         continue;
11240b57cec5SDimitry Andric       }
1125fe6060f1SDimitry Andric       ShouldExtendDef = true;
11260b57cec5SDimitry Andric       LiveInterval *LI = nullptr;
11270b57cec5SDimitry Andric       const VNInfo *VNI = nullptr;
11280b57cec5SDimitry Andric       if (LIS.hasInterval(LocMO.getReg())) {
11290b57cec5SDimitry Andric         LI = &LIS.getInterval(LocMO.getReg());
11300b57cec5SDimitry Andric         VNI = LI->getVNInfoAt(Idx);
11310b57cec5SDimitry Andric       }
1132fe6060f1SDimitry Andric       if (LI && VNI)
1133fe6060f1SDimitry Andric         LIs[LocNo] = {LI, VNI};
1134fe6060f1SDimitry Andric     }
1135fe6060f1SDimitry Andric     if (ShouldExtendDef) {
1136fe6060f1SDimitry Andric       Optional<std::pair<SlotIndex, SmallVector<unsigned>>> Kills;
1137fe6060f1SDimitry Andric       extendDef(Idx, DbgValue, LIs, Kills, LIS);
1138fe6060f1SDimitry Andric 
1139fe6060f1SDimitry Andric       if (Kills) {
1140fe6060f1SDimitry Andric         SmallVector<std::pair<unsigned, LiveInterval *>, 2> KilledLocIntervals;
1141fe6060f1SDimitry Andric         bool AnySubreg = false;
1142fe6060f1SDimitry Andric         for (unsigned LocNo : Kills->second) {
1143fe6060f1SDimitry Andric           const MachineOperand &LocMO = this->locations[LocNo];
1144fe6060f1SDimitry Andric           if (LocMO.getSubReg()) {
1145fe6060f1SDimitry Andric             AnySubreg = true;
1146fe6060f1SDimitry Andric             break;
1147fe6060f1SDimitry Andric           }
1148fe6060f1SDimitry Andric           LiveInterval *LI = &LIS.getInterval(LocMO.getReg());
1149fe6060f1SDimitry Andric           KilledLocIntervals.push_back({LocNo, LI});
1150fe6060f1SDimitry Andric         }
1151fe6060f1SDimitry Andric 
11520b57cec5SDimitry Andric         // FIXME: Handle sub-registers in addDefsFromCopies. The problem is that
11530b57cec5SDimitry Andric         // if the original location for example is %vreg0:sub_hi, and we find a
1154fe6060f1SDimitry Andric         // full register copy in addDefsFromCopies (at the moment it only
1155fe6060f1SDimitry Andric         // handles full register copies), then we must add the sub1 sub-register
1156fe6060f1SDimitry Andric         // index to the new location. However, that is only possible if the new
1157fe6060f1SDimitry Andric         // virtual register is of the same regclass (or if there is an
1158fe6060f1SDimitry Andric         // equivalent sub-register in that regclass). For now, simply skip
1159fe6060f1SDimitry Andric         // handling copies if a sub-register is involved.
1160fe6060f1SDimitry Andric         if (!AnySubreg)
1161fe6060f1SDimitry Andric           addDefsFromCopies(DbgValue, KilledLocIntervals, Kills->first, Defs,
1162fe6060f1SDimitry Andric                             MRI, LIS);
1163fe6060f1SDimitry Andric       }
11640b57cec5SDimitry Andric     }
11650b57cec5SDimitry Andric 
11660b57cec5SDimitry Andric     // For physregs, we only mark the start slot idx. DwarfDebug will see it
11670b57cec5SDimitry Andric     // as if the DBG_VALUE is valid up until the end of the basic block, or
11680b57cec5SDimitry Andric     // the next def of the physical register. So we do not need to extend the
11690b57cec5SDimitry Andric     // range. It might actually happen that the DBG_VALUE is the last use of
11700b57cec5SDimitry Andric     // the physical register (e.g. if this is an unused input argument to a
11710b57cec5SDimitry Andric     // function).
11720b57cec5SDimitry Andric   }
11730b57cec5SDimitry Andric 
11740b57cec5SDimitry Andric   // The computed intervals may extend beyond the range of the debug
11750b57cec5SDimitry Andric   // location's lexical scope. In this case, splitting of an interval
11760b57cec5SDimitry Andric   // can result in an interval outside of the scope being created,
11770b57cec5SDimitry Andric   // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
1178fe6060f1SDimitry Andric   // this, trim the intervals to the lexical scope in the case of inlined
1179fe6060f1SDimitry Andric   // variables, since heavy inlining may cause production of dramatically big
1180fe6060f1SDimitry Andric   // number of DBG_VALUEs to be generated.
1181fe6060f1SDimitry Andric   if (!dl.getInlinedAt())
1182fe6060f1SDimitry Andric     return;
11830b57cec5SDimitry Andric 
11840b57cec5SDimitry Andric   LexicalScope *Scope = LS.findLexicalScope(dl);
11850b57cec5SDimitry Andric   if (!Scope)
11860b57cec5SDimitry Andric     return;
11870b57cec5SDimitry Andric 
11880b57cec5SDimitry Andric   SlotIndex PrevEnd;
11890b57cec5SDimitry Andric   LocMap::iterator I = locInts.begin();
11900b57cec5SDimitry Andric 
11910b57cec5SDimitry Andric   // Iterate over the lexical scope ranges. Each time round the loop
11920b57cec5SDimitry Andric   // we check the intervals for overlap with the end of the previous
11930b57cec5SDimitry Andric   // range and the start of the next. The first range is handled as
11940b57cec5SDimitry Andric   // a special case where there is no PrevEnd.
11950b57cec5SDimitry Andric   for (const InsnRange &Range : Scope->getRanges()) {
11960b57cec5SDimitry Andric     SlotIndex RStart = LIS.getInstructionIndex(*Range.first);
11970b57cec5SDimitry Andric     SlotIndex REnd = LIS.getInstructionIndex(*Range.second);
11980b57cec5SDimitry Andric 
119913138422SDimitry Andric     // Variable locations at the first instruction of a block should be
120013138422SDimitry Andric     // based on the block's SlotIndex, not the first instruction's index.
120113138422SDimitry Andric     if (Range.first == Range.first->getParent()->begin())
120213138422SDimitry Andric       RStart = LIS.getSlotIndexes()->getIndexBefore(*Range.first);
120313138422SDimitry Andric 
12040b57cec5SDimitry Andric     // At the start of each iteration I has been advanced so that
12050b57cec5SDimitry Andric     // I.stop() >= PrevEnd. Check for overlap.
12060b57cec5SDimitry Andric     if (PrevEnd && I.start() < PrevEnd) {
12070b57cec5SDimitry Andric       SlotIndex IStop = I.stop();
12085ffd83dbSDimitry Andric       DbgVariableValue DbgValue = I.value();
12090b57cec5SDimitry Andric 
12100b57cec5SDimitry Andric       // Stop overlaps previous end - trim the end of the interval to
12110b57cec5SDimitry Andric       // the scope range.
12120b57cec5SDimitry Andric       I.setStopUnchecked(PrevEnd);
12130b57cec5SDimitry Andric       ++I;
12140b57cec5SDimitry Andric 
12150b57cec5SDimitry Andric       // If the interval also overlaps the start of the "next" (i.e.
121613138422SDimitry Andric       // current) range create a new interval for the remainder (which
121713138422SDimitry Andric       // may be further trimmed).
12180b57cec5SDimitry Andric       if (RStart < IStop)
12195ffd83dbSDimitry Andric         I.insert(RStart, IStop, DbgValue);
12200b57cec5SDimitry Andric     }
12210b57cec5SDimitry Andric 
12220b57cec5SDimitry Andric     // Advance I so that I.stop() >= RStart, and check for overlap.
12230b57cec5SDimitry Andric     I.advanceTo(RStart);
12240b57cec5SDimitry Andric     if (!I.valid())
12250b57cec5SDimitry Andric       return;
12260b57cec5SDimitry Andric 
122713138422SDimitry Andric     if (I.start() < RStart) {
122813138422SDimitry Andric       // Interval start overlaps range - trim to the scope range.
122913138422SDimitry Andric       I.setStartUnchecked(RStart);
123013138422SDimitry Andric       // Remember that this interval was trimmed.
123113138422SDimitry Andric       trimmedDefs.insert(RStart);
123213138422SDimitry Andric     }
123313138422SDimitry Andric 
12340b57cec5SDimitry Andric     // The end of a lexical scope range is the last instruction in the
12350b57cec5SDimitry Andric     // range. To convert to an interval we need the index of the
12360b57cec5SDimitry Andric     // instruction after it.
12370b57cec5SDimitry Andric     REnd = REnd.getNextIndex();
12380b57cec5SDimitry Andric 
12390b57cec5SDimitry Andric     // Advance I to first interval outside current range.
12400b57cec5SDimitry Andric     I.advanceTo(REnd);
12410b57cec5SDimitry Andric     if (!I.valid())
12420b57cec5SDimitry Andric       return;
12430b57cec5SDimitry Andric 
12440b57cec5SDimitry Andric     PrevEnd = REnd;
12450b57cec5SDimitry Andric   }
12460b57cec5SDimitry Andric 
12470b57cec5SDimitry Andric   // Check for overlap with end of final range.
12480b57cec5SDimitry Andric   if (PrevEnd && I.start() < PrevEnd)
12490b57cec5SDimitry Andric     I.setStopUnchecked(PrevEnd);
12500b57cec5SDimitry Andric }
12510b57cec5SDimitry Andric 
12520b57cec5SDimitry Andric void LDVImpl::computeIntervals() {
12530b57cec5SDimitry Andric   LexicalScopes LS;
12540b57cec5SDimitry Andric   LS.initialize(*MF);
12550b57cec5SDimitry Andric 
12560b57cec5SDimitry Andric   for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
12570b57cec5SDimitry Andric     userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS);
12580b57cec5SDimitry Andric     userValues[i]->mapVirtRegs(this);
12590b57cec5SDimitry Andric   }
12600b57cec5SDimitry Andric }
12610b57cec5SDimitry Andric 
1262fe6060f1SDimitry Andric bool LDVImpl::runOnMachineFunction(MachineFunction &mf, bool InstrRef) {
12630b57cec5SDimitry Andric   clear();
12640b57cec5SDimitry Andric   MF = &mf;
12650b57cec5SDimitry Andric   LIS = &pass.getAnalysis<LiveIntervals>();
12660b57cec5SDimitry Andric   TRI = mf.getSubtarget().getRegisterInfo();
12670b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
12680b57cec5SDimitry Andric                     << mf.getName() << " **********\n");
12690b57cec5SDimitry Andric 
1270fe6060f1SDimitry Andric   bool Changed = collectDebugValues(mf, InstrRef);
12710b57cec5SDimitry Andric   computeIntervals();
12720b57cec5SDimitry Andric   LLVM_DEBUG(print(dbgs()));
1273fe6060f1SDimitry Andric 
1274fe6060f1SDimitry Andric   // Collect the set of VReg / SlotIndexs where PHIs occur; index the sensitive
1275fe6060f1SDimitry Andric   // VRegs too, for when we're notified of a range split.
1276fe6060f1SDimitry Andric   SlotIndexes *Slots = LIS->getSlotIndexes();
1277fe6060f1SDimitry Andric   for (const auto &PHIIt : MF->DebugPHIPositions) {
1278fe6060f1SDimitry Andric     const MachineFunction::DebugPHIRegallocPos &Position = PHIIt.second;
1279fe6060f1SDimitry Andric     MachineBasicBlock *MBB = Position.MBB;
1280fe6060f1SDimitry Andric     Register Reg = Position.Reg;
1281fe6060f1SDimitry Andric     unsigned SubReg = Position.SubReg;
1282fe6060f1SDimitry Andric     SlotIndex SI = Slots->getMBBStartIdx(MBB);
1283fe6060f1SDimitry Andric     PHIValPos VP = {SI, Reg, SubReg};
1284fe6060f1SDimitry Andric     PHIValToPos.insert(std::make_pair(PHIIt.first, VP));
1285fe6060f1SDimitry Andric     RegToPHIIdx[Reg].push_back(PHIIt.first);
1286fe6060f1SDimitry Andric   }
1287fe6060f1SDimitry Andric 
12880b57cec5SDimitry Andric   ModifiedMF = Changed;
12890b57cec5SDimitry Andric   return Changed;
12900b57cec5SDimitry Andric }
12910b57cec5SDimitry Andric 
1292e8d8bef9SDimitry Andric static void removeDebugInstrs(MachineFunction &mf) {
12930b57cec5SDimitry Andric   for (MachineBasicBlock &MBB : mf) {
1294349cc55cSDimitry Andric     for (MachineInstr &MI : llvm::make_early_inc_range(MBB))
1295349cc55cSDimitry Andric       if (MI.isDebugInstr())
1296349cc55cSDimitry Andric         MBB.erase(&MI);
12970b57cec5SDimitry Andric   }
12980b57cec5SDimitry Andric }
12990b57cec5SDimitry Andric 
13000b57cec5SDimitry Andric bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
13010b57cec5SDimitry Andric   if (!EnableLDV)
13020b57cec5SDimitry Andric     return false;
13030b57cec5SDimitry Andric   if (!mf.getFunction().getSubprogram()) {
1304e8d8bef9SDimitry Andric     removeDebugInstrs(mf);
13050b57cec5SDimitry Andric     return false;
13060b57cec5SDimitry Andric   }
1307fe6060f1SDimitry Andric 
1308fe6060f1SDimitry Andric   // Have we been asked to track variable locations using instruction
1309fe6060f1SDimitry Andric   // referencing?
1310349cc55cSDimitry Andric   bool InstrRef = mf.useDebugInstrRef();
1311fe6060f1SDimitry Andric 
13120b57cec5SDimitry Andric   if (!pImpl)
13130b57cec5SDimitry Andric     pImpl = new LDVImpl(this);
1314fe6060f1SDimitry Andric   return static_cast<LDVImpl *>(pImpl)->runOnMachineFunction(mf, InstrRef);
13150b57cec5SDimitry Andric }
13160b57cec5SDimitry Andric 
13170b57cec5SDimitry Andric void LiveDebugVariables::releaseMemory() {
13180b57cec5SDimitry Andric   if (pImpl)
13190b57cec5SDimitry Andric     static_cast<LDVImpl*>(pImpl)->clear();
13200b57cec5SDimitry Andric }
13210b57cec5SDimitry Andric 
13220b57cec5SDimitry Andric LiveDebugVariables::~LiveDebugVariables() {
13230b57cec5SDimitry Andric   if (pImpl)
13240b57cec5SDimitry Andric     delete static_cast<LDVImpl*>(pImpl);
13250b57cec5SDimitry Andric }
13260b57cec5SDimitry Andric 
13270b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13280b57cec5SDimitry Andric //                           Live Range Splitting
13290b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13300b57cec5SDimitry Andric 
13310b57cec5SDimitry Andric bool
13325ffd83dbSDimitry Andric UserValue::splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs,
13330b57cec5SDimitry Andric                          LiveIntervals& LIS) {
13340b57cec5SDimitry Andric   LLVM_DEBUG({
13350b57cec5SDimitry Andric     dbgs() << "Splitting Loc" << OldLocNo << '\t';
13360b57cec5SDimitry Andric     print(dbgs(), nullptr);
13370b57cec5SDimitry Andric   });
13380b57cec5SDimitry Andric   bool DidChange = false;
13390b57cec5SDimitry Andric   LocMap::iterator LocMapI;
13400b57cec5SDimitry Andric   LocMapI.setMap(locInts);
13410eae32dcSDimitry Andric   for (Register NewReg : NewRegs) {
13420eae32dcSDimitry Andric     LiveInterval *LI = &LIS.getInterval(NewReg);
13430b57cec5SDimitry Andric     if (LI->empty())
13440b57cec5SDimitry Andric       continue;
13450b57cec5SDimitry Andric 
13460b57cec5SDimitry Andric     // Don't allocate the new LocNo until it is needed.
13470b57cec5SDimitry Andric     unsigned NewLocNo = UndefLocNo;
13480b57cec5SDimitry Andric 
13490b57cec5SDimitry Andric     // Iterate over the overlaps between locInts and LI.
13500b57cec5SDimitry Andric     LocMapI.find(LI->beginIndex());
13510b57cec5SDimitry Andric     if (!LocMapI.valid())
13520b57cec5SDimitry Andric       continue;
13530b57cec5SDimitry Andric     LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
13540b57cec5SDimitry Andric     LiveInterval::iterator LIE = LI->end();
13550b57cec5SDimitry Andric     while (LocMapI.valid() && LII != LIE) {
13560b57cec5SDimitry Andric       // At this point, we know that LocMapI.stop() > LII->start.
13570b57cec5SDimitry Andric       LII = LI->advanceTo(LII, LocMapI.start());
13580b57cec5SDimitry Andric       if (LII == LIE)
13590b57cec5SDimitry Andric         break;
13600b57cec5SDimitry Andric 
13610b57cec5SDimitry Andric       // Now LII->end > LocMapI.start(). Do we have an overlap?
1362fe6060f1SDimitry Andric       if (LocMapI.value().containsLocNo(OldLocNo) &&
13635ffd83dbSDimitry Andric           LII->start < LocMapI.stop()) {
13640b57cec5SDimitry Andric         // Overlapping correct location. Allocate NewLocNo now.
13650b57cec5SDimitry Andric         if (NewLocNo == UndefLocNo) {
1366e8d8bef9SDimitry Andric           MachineOperand MO = MachineOperand::CreateReg(LI->reg(), false);
13670b57cec5SDimitry Andric           MO.setSubReg(locations[OldLocNo].getSubReg());
13680b57cec5SDimitry Andric           NewLocNo = getLocationNo(MO);
13690b57cec5SDimitry Andric           DidChange = true;
13700b57cec5SDimitry Andric         }
13710b57cec5SDimitry Andric 
13720b57cec5SDimitry Andric         SlotIndex LStart = LocMapI.start();
13730b57cec5SDimitry Andric         SlotIndex LStop = LocMapI.stop();
13745ffd83dbSDimitry Andric         DbgVariableValue OldDbgValue = LocMapI.value();
13750b57cec5SDimitry Andric 
13760b57cec5SDimitry Andric         // Trim LocMapI down to the LII overlap.
13770b57cec5SDimitry Andric         if (LStart < LII->start)
13780b57cec5SDimitry Andric           LocMapI.setStartUnchecked(LII->start);
13790b57cec5SDimitry Andric         if (LStop > LII->end)
13800b57cec5SDimitry Andric           LocMapI.setStopUnchecked(LII->end);
13810b57cec5SDimitry Andric 
13820b57cec5SDimitry Andric         // Change the value in the overlap. This may trigger coalescing.
1383fe6060f1SDimitry Andric         LocMapI.setValue(OldDbgValue.changeLocNo(OldLocNo, NewLocNo));
13840b57cec5SDimitry Andric 
13855ffd83dbSDimitry Andric         // Re-insert any removed OldDbgValue ranges.
13860b57cec5SDimitry Andric         if (LStart < LocMapI.start()) {
13875ffd83dbSDimitry Andric           LocMapI.insert(LStart, LocMapI.start(), OldDbgValue);
13880b57cec5SDimitry Andric           ++LocMapI;
13890b57cec5SDimitry Andric           assert(LocMapI.valid() && "Unexpected coalescing");
13900b57cec5SDimitry Andric         }
13910b57cec5SDimitry Andric         if (LStop > LocMapI.stop()) {
13920b57cec5SDimitry Andric           ++LocMapI;
13935ffd83dbSDimitry Andric           LocMapI.insert(LII->end, LStop, OldDbgValue);
13940b57cec5SDimitry Andric           --LocMapI;
13950b57cec5SDimitry Andric         }
13960b57cec5SDimitry Andric       }
13970b57cec5SDimitry Andric 
13980b57cec5SDimitry Andric       // Advance to the next overlap.
13990b57cec5SDimitry Andric       if (LII->end < LocMapI.stop()) {
14000b57cec5SDimitry Andric         if (++LII == LIE)
14010b57cec5SDimitry Andric           break;
14020b57cec5SDimitry Andric         LocMapI.advanceTo(LII->start);
14030b57cec5SDimitry Andric       } else {
14040b57cec5SDimitry Andric         ++LocMapI;
14050b57cec5SDimitry Andric         if (!LocMapI.valid())
14060b57cec5SDimitry Andric           break;
14070b57cec5SDimitry Andric         LII = LI->advanceTo(LII, LocMapI.start());
14080b57cec5SDimitry Andric       }
14090b57cec5SDimitry Andric     }
14100b57cec5SDimitry Andric   }
14110b57cec5SDimitry Andric 
1412480093f4SDimitry Andric   // Finally, remove OldLocNo unless it is still used by some interval in the
1413480093f4SDimitry Andric   // locInts map. One case when OldLocNo still is in use is when the register
1414480093f4SDimitry Andric   // has been spilled. In such situations the spilled register is kept as a
1415480093f4SDimitry Andric   // location until rewriteLocations is called (VirtRegMap is mapping the old
1416480093f4SDimitry Andric   // register to the spill slot). So for a while we can have locations that map
1417480093f4SDimitry Andric   // to virtual registers that have been removed from both the MachineFunction
1418480093f4SDimitry Andric   // and from LiveIntervals.
14195ffd83dbSDimitry Andric   //
14205ffd83dbSDimitry Andric   // We may also just be using the location for a value with a different
14215ffd83dbSDimitry Andric   // expression.
1422480093f4SDimitry Andric   removeLocationIfUnused(OldLocNo);
14230b57cec5SDimitry Andric 
14240b57cec5SDimitry Andric   LLVM_DEBUG({
14250b57cec5SDimitry Andric     dbgs() << "Split result: \t";
14260b57cec5SDimitry Andric     print(dbgs(), nullptr);
14270b57cec5SDimitry Andric   });
14280b57cec5SDimitry Andric   return DidChange;
14290b57cec5SDimitry Andric }
14300b57cec5SDimitry Andric 
14310b57cec5SDimitry Andric bool
14325ffd83dbSDimitry Andric UserValue::splitRegister(Register OldReg, ArrayRef<Register> NewRegs,
14330b57cec5SDimitry Andric                          LiveIntervals &LIS) {
14340b57cec5SDimitry Andric   bool DidChange = false;
14350b57cec5SDimitry Andric   // Split locations referring to OldReg. Iterate backwards so splitLocation can
14360b57cec5SDimitry Andric   // safely erase unused locations.
14370b57cec5SDimitry Andric   for (unsigned i = locations.size(); i ; --i) {
14380b57cec5SDimitry Andric     unsigned LocNo = i-1;
14390b57cec5SDimitry Andric     const MachineOperand *Loc = &locations[LocNo];
14400b57cec5SDimitry Andric     if (!Loc->isReg() || Loc->getReg() != OldReg)
14410b57cec5SDimitry Andric       continue;
14420b57cec5SDimitry Andric     DidChange |= splitLocation(LocNo, NewRegs, LIS);
14430b57cec5SDimitry Andric   }
14440b57cec5SDimitry Andric   return DidChange;
14450b57cec5SDimitry Andric }
14460b57cec5SDimitry Andric 
1447fe6060f1SDimitry Andric void LDVImpl::splitPHIRegister(Register OldReg, ArrayRef<Register> NewRegs) {
1448fe6060f1SDimitry Andric   auto RegIt = RegToPHIIdx.find(OldReg);
1449fe6060f1SDimitry Andric   if (RegIt == RegToPHIIdx.end())
1450fe6060f1SDimitry Andric     return;
1451fe6060f1SDimitry Andric 
1452fe6060f1SDimitry Andric   std::vector<std::pair<Register, unsigned>> NewRegIdxes;
1453fe6060f1SDimitry Andric   // Iterate over all the debug instruction numbers affected by this split.
1454fe6060f1SDimitry Andric   for (unsigned InstrID : RegIt->second) {
1455fe6060f1SDimitry Andric     auto PHIIt = PHIValToPos.find(InstrID);
1456fe6060f1SDimitry Andric     assert(PHIIt != PHIValToPos.end());
1457fe6060f1SDimitry Andric     const SlotIndex &Slot = PHIIt->second.SI;
1458fe6060f1SDimitry Andric     assert(OldReg == PHIIt->second.Reg);
1459fe6060f1SDimitry Andric 
1460fe6060f1SDimitry Andric     // Find the new register that covers this position.
1461fe6060f1SDimitry Andric     for (auto NewReg : NewRegs) {
1462fe6060f1SDimitry Andric       const LiveInterval &LI = LIS->getInterval(NewReg);
1463fe6060f1SDimitry Andric       auto LII = LI.find(Slot);
1464fe6060f1SDimitry Andric       if (LII != LI.end() && LII->start <= Slot) {
1465fe6060f1SDimitry Andric         // This new register covers this PHI position, record this for indexing.
1466fe6060f1SDimitry Andric         NewRegIdxes.push_back(std::make_pair(NewReg, InstrID));
1467fe6060f1SDimitry Andric         // Record that this value lives in a different VReg now.
1468fe6060f1SDimitry Andric         PHIIt->second.Reg = NewReg;
1469fe6060f1SDimitry Andric         break;
1470fe6060f1SDimitry Andric       }
1471fe6060f1SDimitry Andric     }
1472fe6060f1SDimitry Andric 
1473fe6060f1SDimitry Andric     // If we do not find a new register covering this PHI, then register
1474fe6060f1SDimitry Andric     // allocation has dropped its location, for example because it's not live.
1475fe6060f1SDimitry Andric     // The old VReg will not be mapped to a physreg, and the instruction
1476fe6060f1SDimitry Andric     // number will have been optimized out.
1477fe6060f1SDimitry Andric   }
1478fe6060f1SDimitry Andric 
1479fe6060f1SDimitry Andric   // Re-create register index using the new register numbers.
1480fe6060f1SDimitry Andric   RegToPHIIdx.erase(RegIt);
1481fe6060f1SDimitry Andric   for (auto &RegAndInstr : NewRegIdxes)
1482fe6060f1SDimitry Andric     RegToPHIIdx[RegAndInstr.first].push_back(RegAndInstr.second);
1483fe6060f1SDimitry Andric }
1484fe6060f1SDimitry Andric 
14855ffd83dbSDimitry Andric void LDVImpl::splitRegister(Register OldReg, ArrayRef<Register> NewRegs) {
1486fe6060f1SDimitry Andric   // Consider whether this split range affects any PHI locations.
1487fe6060f1SDimitry Andric   splitPHIRegister(OldReg, NewRegs);
1488fe6060f1SDimitry Andric 
1489fe6060f1SDimitry Andric   // Check whether any intervals mapped by a DBG_VALUE were split and need
1490fe6060f1SDimitry Andric   // updating.
14910b57cec5SDimitry Andric   bool DidChange = false;
1492480093f4SDimitry Andric   for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
14930b57cec5SDimitry Andric     DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
14940b57cec5SDimitry Andric 
14950b57cec5SDimitry Andric   if (!DidChange)
14960b57cec5SDimitry Andric     return;
14970b57cec5SDimitry Andric 
14980b57cec5SDimitry Andric   // Map all of the new virtual registers.
1499480093f4SDimitry Andric   UserValue *UV = lookupVirtReg(OldReg);
15000eae32dcSDimitry Andric   for (Register NewReg : NewRegs)
15010eae32dcSDimitry Andric     mapVirtReg(NewReg, UV);
15020b57cec5SDimitry Andric }
15030b57cec5SDimitry Andric 
15040b57cec5SDimitry Andric void LiveDebugVariables::
15055ffd83dbSDimitry Andric splitRegister(Register OldReg, ArrayRef<Register> NewRegs, LiveIntervals &LIS) {
15060b57cec5SDimitry Andric   if (pImpl)
15070b57cec5SDimitry Andric     static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
15080b57cec5SDimitry Andric }
15090b57cec5SDimitry Andric 
15100b57cec5SDimitry Andric void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
15110b57cec5SDimitry Andric                                  const TargetInstrInfo &TII,
15120b57cec5SDimitry Andric                                  const TargetRegisterInfo &TRI,
15130b57cec5SDimitry Andric                                  SpillOffsetMap &SpillOffsets) {
15140b57cec5SDimitry Andric   // Build a set of new locations with new numbers so we can coalesce our
15150b57cec5SDimitry Andric   // IntervalMap if two vreg intervals collapse to the same physical location.
15160b57cec5SDimitry Andric   // Use MapVector instead of SetVector because MapVector::insert returns the
15170b57cec5SDimitry Andric   // position of the previously or newly inserted element. The boolean value
15180b57cec5SDimitry Andric   // tracks if the location was produced by a spill.
15190b57cec5SDimitry Andric   // FIXME: This will be problematic if we ever support direct and indirect
15200b57cec5SDimitry Andric   // frame index locations, i.e. expressing both variables in memory and
15210b57cec5SDimitry Andric   // 'int x, *px = &x'. The "spilled" bit must become part of the location.
15220b57cec5SDimitry Andric   MapVector<MachineOperand, std::pair<bool, unsigned>> NewLocations;
15230b57cec5SDimitry Andric   SmallVector<unsigned, 4> LocNoMap(locations.size());
15240b57cec5SDimitry Andric   for (unsigned I = 0, E = locations.size(); I != E; ++I) {
15250b57cec5SDimitry Andric     bool Spilled = false;
15260b57cec5SDimitry Andric     unsigned SpillOffset = 0;
15270b57cec5SDimitry Andric     MachineOperand Loc = locations[I];
15280b57cec5SDimitry Andric     // Only virtual registers are rewritten.
15290b57cec5SDimitry Andric     if (Loc.isReg() && Loc.getReg() &&
15308bcb0991SDimitry Andric         Register::isVirtualRegister(Loc.getReg())) {
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
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
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 
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 
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 
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 
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 
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 
1857fe6060f1SDimitry Andric       // Test whether this location is legal with the given subreg.
1858fe6060f1SDimitry Andric       bool Success =
1859fe6060f1SDimitry Andric           TII->getStackSlotRange(TRC, SubReg, SpillSize, SpillOffset, *MF);
1860fe6060f1SDimitry Andric 
1861fe6060f1SDimitry Andric       if (Success) {
1862fe6060f1SDimitry Andric         auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(),
1863fe6060f1SDimitry Andric                                TII->get(TargetOpcode::DBG_PHI));
1864fe6060f1SDimitry Andric         Builder.addFrameIndex(VRM->getStackSlot(Reg));
1865fe6060f1SDimitry Andric         Builder.addImm(InstNum);
1866fe6060f1SDimitry Andric       }
1867fe6060f1SDimitry Andric     }
1868fe6060f1SDimitry Andric     // If there was no mapping for a value ID, it's optimized out. Create no
1869fe6060f1SDimitry Andric     // DBG_PHI, and any variables using this value will become optimized out.
1870fe6060f1SDimitry Andric   }
1871fe6060f1SDimitry Andric   MF->DebugPHIPositions.clear();
1872fe6060f1SDimitry Andric 
1873e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "********** EMITTING INSTR REFERENCES **********\n");
1874e8d8bef9SDimitry Andric 
18754824e7fdSDimitry Andric   // Re-insert any debug instrs back in the position they were. We must
18764824e7fdSDimitry Andric   // re-insert in the same order to ensure that debug instructions don't swap,
18774824e7fdSDimitry Andric   // which could re-order assignments. Do so in a batch -- once we find the
18784824e7fdSDimitry Andric   // insert position, insert all instructions at the same SlotIdx. They are
18794824e7fdSDimitry Andric   // guaranteed to appear in-sequence in StashedDebugInstrs because we insert
18804824e7fdSDimitry Andric   // them in order.
18814824e7fdSDimitry Andric   for (auto StashIt = StashedDebugInstrs.begin();
18824824e7fdSDimitry Andric        StashIt != StashedDebugInstrs.end(); ++StashIt) {
18834824e7fdSDimitry Andric     SlotIndex Idx = StashIt->Idx;
18844824e7fdSDimitry Andric     MachineBasicBlock *MBB = StashIt->MBB;
18854824e7fdSDimitry Andric     MachineInstr *MI = StashIt->MI;
18864824e7fdSDimitry Andric 
18874824e7fdSDimitry Andric     auto EmitInstsHere = [this, &StashIt, MBB, Idx,
18884824e7fdSDimitry Andric                           MI](MachineBasicBlock::iterator InsertPos) {
18894824e7fdSDimitry Andric       // Insert this debug instruction.
18904824e7fdSDimitry Andric       MBB->insert(InsertPos, MI);
18914824e7fdSDimitry Andric 
18924824e7fdSDimitry Andric       // Look at subsequent stashed debug instructions: if they're at the same
18934824e7fdSDimitry Andric       // index, insert those too.
18944824e7fdSDimitry Andric       auto NextItem = std::next(StashIt);
18954824e7fdSDimitry Andric       while (NextItem != StashedDebugInstrs.end() && NextItem->Idx == Idx) {
18964824e7fdSDimitry Andric         assert(NextItem->MBB == MBB && "Instrs with same slot index should be"
18974824e7fdSDimitry Andric                "in the same block");
18984824e7fdSDimitry Andric         MBB->insert(InsertPos, NextItem->MI);
18994824e7fdSDimitry Andric         StashIt = NextItem;
19004824e7fdSDimitry Andric         NextItem = std::next(StashIt);
19014824e7fdSDimitry Andric       };
19024824e7fdSDimitry Andric     };
1903fe6060f1SDimitry Andric 
1904fe6060f1SDimitry Andric     // Start block index: find the first non-debug instr in the block, and
1905fe6060f1SDimitry Andric     // insert before it.
19064824e7fdSDimitry Andric     if (Idx == Slots->getMBBStartIdx(MBB)) {
1907fe6060f1SDimitry Andric       MachineBasicBlock::iterator InsertPos =
19084824e7fdSDimitry Andric           findInsertLocation(MBB, Idx, *LIS, BBSkipInstsMap);
19094824e7fdSDimitry Andric       EmitInstsHere(InsertPos);
1910fe6060f1SDimitry Andric       continue;
1911fe6060f1SDimitry Andric     }
1912fe6060f1SDimitry Andric 
1913fe6060f1SDimitry Andric     if (MachineInstr *Pos = Slots->getInstructionFromIndex(Idx)) {
1914fe6060f1SDimitry Andric       // Insert at the end of any debug instructions.
1915fe6060f1SDimitry Andric       auto PostDebug = std::next(Pos->getIterator());
19164824e7fdSDimitry Andric       PostDebug = skipDebugInstructionsForward(PostDebug, MBB->instr_end());
19174824e7fdSDimitry Andric       EmitInstsHere(PostDebug);
1918fe6060f1SDimitry Andric     } else {
1919fe6060f1SDimitry Andric       // Insert position disappeared; walk forwards through slots until we
1920fe6060f1SDimitry Andric       // find a new one.
19214824e7fdSDimitry Andric       SlotIndex End = Slots->getMBBEndIdx(MBB);
1922fe6060f1SDimitry Andric       for (; Idx < End; Idx = Slots->getNextNonNullIndex(Idx)) {
1923fe6060f1SDimitry Andric         Pos = Slots->getInstructionFromIndex(Idx);
1924fe6060f1SDimitry Andric         if (Pos) {
19254824e7fdSDimitry Andric           EmitInstsHere(Pos->getIterator());
1926fe6060f1SDimitry Andric           break;
1927fe6060f1SDimitry Andric         }
1928fe6060f1SDimitry Andric       }
1929fe6060f1SDimitry Andric 
1930fe6060f1SDimitry Andric       // We have reached the end of the block and didn't find anywhere to
1931fe6060f1SDimitry Andric       // insert! It's not safe to discard any debug instructions; place them
1932fe6060f1SDimitry Andric       // in front of the first terminator, or in front of end().
1933fe6060f1SDimitry Andric       if (Idx >= End) {
19344824e7fdSDimitry Andric         auto TermIt = MBB->getFirstTerminator();
19354824e7fdSDimitry Andric         EmitInstsHere(TermIt);
1936fe6060f1SDimitry Andric       }
1937e8d8bef9SDimitry Andric     }
1938e8d8bef9SDimitry Andric   }
1939e8d8bef9SDimitry Andric 
19400b57cec5SDimitry Andric   EmitDone = true;
1941fe6060f1SDimitry Andric   BBSkipInstsMap.clear();
19420b57cec5SDimitry Andric }
19430b57cec5SDimitry Andric 
19440b57cec5SDimitry Andric void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
19450b57cec5SDimitry Andric   if (pImpl)
19460b57cec5SDimitry Andric     static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
19470b57cec5SDimitry Andric }
19480b57cec5SDimitry Andric 
19490b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
19500b57cec5SDimitry Andric LLVM_DUMP_METHOD void LiveDebugVariables::dump() const {
19510b57cec5SDimitry Andric   if (pImpl)
19520b57cec5SDimitry Andric     static_cast<LDVImpl*>(pImpl)->print(dbgs());
19530b57cec5SDimitry Andric }
19540b57cec5SDimitry Andric #endif
1955