1//===- LiveDebugVariables.cpp - Tracking debug info variables -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the LiveDebugVariables analysis.
10//
11// Remove all DBG_VALUE instructions referencing virtual registers and replace
12// them with a data structure tracking where live user variables are kept - in a
13// virtual register or in a stack slot.
14//
15// Allow the data structure to be updated during register allocation when values
16// are moved between registers and stack slots. Finally emit new DBG_VALUE
17// instructions after register allocation is complete.
18//
19//===----------------------------------------------------------------------===//
20
21#include "LiveDebugVariables.h"
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/IntervalMap.h"
25#include "llvm/ADT/MapVector.h"
26#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/SmallSet.h"
28#include "llvm/ADT/SmallVector.h"
29#include "llvm/ADT/Statistic.h"
30#include "llvm/ADT/StringRef.h"
31#include "llvm/BinaryFormat/Dwarf.h"
32#include "llvm/CodeGen/LexicalScopes.h"
33#include "llvm/CodeGen/LiveInterval.h"
34#include "llvm/CodeGen/LiveIntervals.h"
35#include "llvm/CodeGen/MachineBasicBlock.h"
36#include "llvm/CodeGen/MachineDominators.h"
37#include "llvm/CodeGen/MachineFunction.h"
38#include "llvm/CodeGen/MachineInstr.h"
39#include "llvm/CodeGen/MachineInstrBuilder.h"
40#include "llvm/CodeGen/MachineOperand.h"
41#include "llvm/CodeGen/MachineRegisterInfo.h"
42#include "llvm/CodeGen/SlotIndexes.h"
43#include "llvm/CodeGen/TargetInstrInfo.h"
44#include "llvm/CodeGen/TargetOpcodes.h"
45#include "llvm/CodeGen/TargetRegisterInfo.h"
46#include "llvm/CodeGen/TargetSubtargetInfo.h"
47#include "llvm/CodeGen/VirtRegMap.h"
48#include "llvm/Config/llvm-config.h"
49#include "llvm/IR/DebugInfoMetadata.h"
50#include "llvm/IR/DebugLoc.h"
51#include "llvm/IR/Function.h"
52#include "llvm/InitializePasses.h"
53#include "llvm/Pass.h"
54#include "llvm/Support/Casting.h"
55#include "llvm/Support/CommandLine.h"
56#include "llvm/Support/Debug.h"
57#include "llvm/Support/raw_ostream.h"
58#include <algorithm>
59#include <cassert>
60#include <iterator>
61#include <map>
62#include <memory>
63#include <optional>
64#include <utility>
65
66using namespace llvm;
67
68#define DEBUG_TYPE "livedebugvars"
69
70static cl::opt<bool>
71EnableLDV("live-debug-variables", cl::init(true),
72          cl::desc("Enable the live debug variables pass"), cl::Hidden);
73
74STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
75STATISTIC(NumInsertedDebugLabels, "Number of DBG_LABELs inserted");
76
77char LiveDebugVariables::ID = 0;
78
79INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE,
80                "Debug Variable Analysis", false, false)
81INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
82INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
83INITIALIZE_PASS_END(LiveDebugVariables, DEBUG_TYPE,
84                "Debug Variable Analysis", false, false)
85
86void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
87  AU.addRequired<MachineDominatorTree>();
88  AU.addRequiredTransitive<LiveIntervals>();
89  AU.setPreservesAll();
90  MachineFunctionPass::getAnalysisUsage(AU);
91}
92
93LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID) {
94  initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
95}
96
97enum : unsigned { UndefLocNo = ~0U };
98
99namespace {
100/// Describes a debug variable value by location number and expression along
101/// with some flags about the original usage of the location.
102class DbgVariableValue {
103public:
104  DbgVariableValue(ArrayRef<unsigned> NewLocs, bool WasIndirect, bool WasList,
105                   const DIExpression &Expr)
106      : WasIndirect(WasIndirect), WasList(WasList), Expression(&Expr) {
107    assert(!(WasIndirect && WasList) &&
108           "DBG_VALUE_LISTs should not be indirect.");
109    SmallVector<unsigned> LocNoVec;
110    for (unsigned LocNo : NewLocs) {
111      auto It = find(LocNoVec, LocNo);
112      if (It == LocNoVec.end())
113        LocNoVec.push_back(LocNo);
114      else {
115        // Loc duplicates an element in LocNos; replace references to Op
116        // with references to the duplicating element.
117        unsigned OpIdx = LocNoVec.size();
118        unsigned DuplicatingIdx = std::distance(LocNoVec.begin(), It);
119        Expression =
120            DIExpression::replaceArg(Expression, OpIdx, DuplicatingIdx);
121      }
122    }
123    // FIXME: Debug values referencing 64+ unique machine locations are rare and
124    // currently unsupported for performance reasons. If we can verify that
125    // performance is acceptable for such debug values, we can increase the
126    // bit-width of LocNoCount to 14 to enable up to 16384 unique machine
127    // locations. We will also need to verify that this does not cause issues
128    // with LiveDebugVariables' use of IntervalMap.
129    if (LocNoVec.size() < 64) {
130      LocNoCount = LocNoVec.size();
131      if (LocNoCount > 0) {
132        LocNos = std::make_unique<unsigned[]>(LocNoCount);
133        std::copy(LocNoVec.begin(), LocNoVec.end(), loc_nos_begin());
134      }
135    } else {
136      LLVM_DEBUG(dbgs() << "Found debug value with 64+ unique machine "
137                           "locations, dropping...\n");
138      LocNoCount = 1;
139      // Turn this into an undef debug value list; right now, the simplest form
140      // of this is an expression with one arg, and an undef debug operand.
141      Expression =
142          DIExpression::get(Expr.getContext(), {dwarf::DW_OP_LLVM_arg, 0});
143      if (auto FragmentInfoOpt = Expr.getFragmentInfo())
144        Expression = *DIExpression::createFragmentExpression(
145            Expression, FragmentInfoOpt->OffsetInBits,
146            FragmentInfoOpt->SizeInBits);
147      LocNos = std::make_unique<unsigned[]>(LocNoCount);
148      LocNos[0] = UndefLocNo;
149    }
150  }
151
152  DbgVariableValue() : LocNoCount(0), WasIndirect(false), WasList(false) {}
153  DbgVariableValue(const DbgVariableValue &Other)
154      : LocNoCount(Other.LocNoCount), WasIndirect(Other.getWasIndirect()),
155        WasList(Other.getWasList()), Expression(Other.getExpression()) {
156    if (Other.getLocNoCount()) {
157      LocNos.reset(new unsigned[Other.getLocNoCount()]);
158      std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin());
159    }
160  }
161
162  DbgVariableValue &operator=(const DbgVariableValue &Other) {
163    if (this == &Other)
164      return *this;
165    if (Other.getLocNoCount()) {
166      LocNos.reset(new unsigned[Other.getLocNoCount()]);
167      std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin());
168    } else {
169      LocNos.release();
170    }
171    LocNoCount = Other.getLocNoCount();
172    WasIndirect = Other.getWasIndirect();
173    WasList = Other.getWasList();
174    Expression = Other.getExpression();
175    return *this;
176  }
177
178  const DIExpression *getExpression() const { return Expression; }
179  uint8_t getLocNoCount() const { return LocNoCount; }
180  bool containsLocNo(unsigned LocNo) const {
181    return is_contained(loc_nos(), LocNo);
182  }
183  bool getWasIndirect() const { return WasIndirect; }
184  bool getWasList() const { return WasList; }
185  bool isUndef() const { return LocNoCount == 0 || containsLocNo(UndefLocNo); }
186
187  DbgVariableValue decrementLocNosAfterPivot(unsigned Pivot) const {
188    SmallVector<unsigned, 4> NewLocNos;
189    for (unsigned LocNo : loc_nos())
190      NewLocNos.push_back(LocNo != UndefLocNo && LocNo > Pivot ? LocNo - 1
191                                                               : LocNo);
192    return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
193  }
194
195  DbgVariableValue remapLocNos(ArrayRef<unsigned> LocNoMap) const {
196    SmallVector<unsigned> NewLocNos;
197    for (unsigned LocNo : loc_nos())
198      // Undef values don't exist in locations (and thus not in LocNoMap
199      // either) so skip over them. See getLocationNo().
200      NewLocNos.push_back(LocNo == UndefLocNo ? UndefLocNo : LocNoMap[LocNo]);
201    return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
202  }
203
204  DbgVariableValue changeLocNo(unsigned OldLocNo, unsigned NewLocNo) const {
205    SmallVector<unsigned> NewLocNos;
206    NewLocNos.assign(loc_nos_begin(), loc_nos_end());
207    auto OldLocIt = find(NewLocNos, OldLocNo);
208    assert(OldLocIt != NewLocNos.end() && "Old location must be present.");
209    *OldLocIt = NewLocNo;
210    return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
211  }
212
213  bool hasLocNoGreaterThan(unsigned LocNo) const {
214    return any_of(loc_nos(),
215                  [LocNo](unsigned ThisLocNo) { return ThisLocNo > LocNo; });
216  }
217
218  void printLocNos(llvm::raw_ostream &OS) const {
219    for (const unsigned &Loc : loc_nos())
220      OS << (&Loc == loc_nos_begin() ? " " : ", ") << Loc;
221  }
222
223  friend inline bool operator==(const DbgVariableValue &LHS,
224                                const DbgVariableValue &RHS) {
225    if (std::tie(LHS.LocNoCount, LHS.WasIndirect, LHS.WasList,
226                 LHS.Expression) !=
227        std::tie(RHS.LocNoCount, RHS.WasIndirect, RHS.WasList, RHS.Expression))
228      return false;
229    return std::equal(LHS.loc_nos_begin(), LHS.loc_nos_end(),
230                      RHS.loc_nos_begin());
231  }
232
233  friend inline bool operator!=(const DbgVariableValue &LHS,
234                                const DbgVariableValue &RHS) {
235    return !(LHS == RHS);
236  }
237
238  unsigned *loc_nos_begin() { return LocNos.get(); }
239  const unsigned *loc_nos_begin() const { return LocNos.get(); }
240  unsigned *loc_nos_end() { return LocNos.get() + LocNoCount; }
241  const unsigned *loc_nos_end() const { return LocNos.get() + LocNoCount; }
242  ArrayRef<unsigned> loc_nos() const {
243    return ArrayRef<unsigned>(LocNos.get(), LocNoCount);
244  }
245
246private:
247  // IntervalMap requires the value object to be very small, to the extent
248  // that we do not have enough room for an std::vector. Using a C-style array
249  // (with a unique_ptr wrapper for convenience) allows us to optimize for this
250  // specific case by packing the array size into only 6 bits (it is highly
251  // unlikely that any debug value will need 64+ locations).
252  std::unique_ptr<unsigned[]> LocNos;
253  uint8_t LocNoCount : 6;
254  bool WasIndirect : 1;
255  bool WasList : 1;
256  const DIExpression *Expression = nullptr;
257};
258} // namespace
259
260/// Map of where a user value is live to that value.
261using LocMap = IntervalMap<SlotIndex, DbgVariableValue, 4>;
262
263/// Map of stack slot offsets for spilled locations.
264/// Non-spilled locations are not added to the map.
265using SpillOffsetMap = DenseMap<unsigned, unsigned>;
266
267/// Cache to save the location where it can be used as the starting
268/// position as input for calling MachineBasicBlock::SkipPHIsLabelsAndDebug.
269/// This is to prevent MachineBasicBlock::SkipPHIsLabelsAndDebug from
270/// repeatedly searching the same set of PHIs/Labels/Debug instructions
271/// if it is called many times for the same block.
272using BlockSkipInstsMap =
273    DenseMap<MachineBasicBlock *, MachineBasicBlock::iterator>;
274
275namespace {
276
277class LDVImpl;
278
279/// A user value is a part of a debug info user variable.
280///
281/// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
282/// holds part of a user variable. The part is identified by a byte offset.
283///
284/// UserValues are grouped into equivalence classes for easier searching. Two
285/// user values are related if they are held by the same virtual register. The
286/// equivalence class is the transitive closure of that relation.
287class UserValue {
288  const DILocalVariable *Variable; ///< The debug info variable we are part of.
289  /// The part of the variable we describe.
290  const std::optional<DIExpression::FragmentInfo> Fragment;
291  DebugLoc dl;            ///< The debug location for the variable. This is
292                          ///< used by dwarf writer to find lexical scope.
293  UserValue *leader;      ///< Equivalence class leader.
294  UserValue *next = nullptr; ///< Next value in equivalence class, or null.
295
296  /// Numbered locations referenced by locmap.
297  SmallVector<MachineOperand, 4> locations;
298
299  /// Map of slot indices where this value is live.
300  LocMap locInts;
301
302  /// Set of interval start indexes that have been trimmed to the
303  /// lexical scope.
304  SmallSet<SlotIndex, 2> trimmedDefs;
305
306  /// Insert a DBG_VALUE into MBB at Idx for DbgValue.
307  void insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
308                        SlotIndex StopIdx, DbgVariableValue DbgValue,
309                        ArrayRef<bool> LocSpills,
310                        ArrayRef<unsigned> SpillOffsets, LiveIntervals &LIS,
311                        const TargetInstrInfo &TII,
312                        const TargetRegisterInfo &TRI,
313                        BlockSkipInstsMap &BBSkipInstsMap);
314
315  /// Replace OldLocNo ranges with NewRegs ranges where NewRegs
316  /// is live. Returns true if any changes were made.
317  bool splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs,
318                     LiveIntervals &LIS);
319
320public:
321  /// Create a new UserValue.
322  UserValue(const DILocalVariable *var,
323            std::optional<DIExpression::FragmentInfo> Fragment, DebugLoc L,
324            LocMap::Allocator &alloc)
325      : Variable(var), Fragment(Fragment), dl(std::move(L)), leader(this),
326        locInts(alloc) {}
327
328  /// Get the leader of this value's equivalence class.
329  UserValue *getLeader() {
330    UserValue *l = leader;
331    while (l != l->leader)
332      l = l->leader;
333    return leader = l;
334  }
335
336  /// Return the next UserValue in the equivalence class.
337  UserValue *getNext() const { return next; }
338
339  /// Merge equivalence classes.
340  static UserValue *merge(UserValue *L1, UserValue *L2) {
341    L2 = L2->getLeader();
342    if (!L1)
343      return L2;
344    L1 = L1->getLeader();
345    if (L1 == L2)
346      return L1;
347    // Splice L2 before L1's members.
348    UserValue *End = L2;
349    while (End->next) {
350      End->leader = L1;
351      End = End->next;
352    }
353    End->leader = L1;
354    End->next = L1->next;
355    L1->next = L2;
356    return L1;
357  }
358
359  /// Return the location number that matches Loc.
360  ///
361  /// For undef values we always return location number UndefLocNo without
362  /// inserting anything in locations. Since locations is a vector and the
363  /// location number is the position in the vector and UndefLocNo is ~0,
364  /// we would need a very big vector to put the value at the right position.
365  unsigned getLocationNo(const MachineOperand &LocMO) {
366    if (LocMO.isReg()) {
367      if (LocMO.getReg() == 0)
368        return UndefLocNo;
369      // For register locations we dont care about use/def and other flags.
370      for (unsigned i = 0, e = locations.size(); i != e; ++i)
371        if (locations[i].isReg() &&
372            locations[i].getReg() == LocMO.getReg() &&
373            locations[i].getSubReg() == LocMO.getSubReg())
374          return i;
375    } else
376      for (unsigned i = 0, e = locations.size(); i != e; ++i)
377        if (LocMO.isIdenticalTo(locations[i]))
378          return i;
379    locations.push_back(LocMO);
380    // We are storing a MachineOperand outside a MachineInstr.
381    locations.back().clearParent();
382    // Don't store def operands.
383    if (locations.back().isReg()) {
384      if (locations.back().isDef())
385        locations.back().setIsDead(false);
386      locations.back().setIsUse();
387    }
388    return locations.size() - 1;
389  }
390
391  /// Remove (recycle) a location number. If \p LocNo still is used by the
392  /// locInts nothing is done.
393  void removeLocationIfUnused(unsigned LocNo) {
394    // Bail out if LocNo still is used.
395    for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
396      const DbgVariableValue &DbgValue = I.value();
397      if (DbgValue.containsLocNo(LocNo))
398        return;
399    }
400    // Remove the entry in the locations vector, and adjust all references to
401    // location numbers above the removed entry.
402    locations.erase(locations.begin() + LocNo);
403    for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
404      const DbgVariableValue &DbgValue = I.value();
405      if (DbgValue.hasLocNoGreaterThan(LocNo))
406        I.setValueUnchecked(DbgValue.decrementLocNosAfterPivot(LocNo));
407    }
408  }
409
410  /// Ensure that all virtual register locations are mapped.
411  void mapVirtRegs(LDVImpl *LDV);
412
413  /// Add a definition point to this user value.
414  void addDef(SlotIndex Idx, ArrayRef<MachineOperand> LocMOs, bool IsIndirect,
415              bool IsList, const DIExpression &Expr) {
416    SmallVector<unsigned> Locs;
417    for (const MachineOperand &Op : LocMOs)
418      Locs.push_back(getLocationNo(Op));
419    DbgVariableValue DbgValue(Locs, IsIndirect, IsList, Expr);
420    // Add a singular (Idx,Idx) -> value mapping.
421    LocMap::iterator I = locInts.find(Idx);
422    if (!I.valid() || I.start() != Idx)
423      I.insert(Idx, Idx.getNextSlot(), std::move(DbgValue));
424    else
425      // A later DBG_VALUE at the same SlotIndex overrides the old location.
426      I.setValue(std::move(DbgValue));
427  }
428
429  /// Extend the current definition as far as possible down.
430  ///
431  /// Stop when meeting an existing def or when leaving the live
432  /// range of VNI. End points where VNI is no longer live are added to Kills.
433  ///
434  /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
435  /// data-flow analysis to propagate them beyond basic block boundaries.
436  ///
437  /// \param Idx Starting point for the definition.
438  /// \param DbgValue value to propagate.
439  /// \param LiveIntervalInfo For each location number key in this map,
440  /// restricts liveness to where the LiveRange has the value equal to the\
441  /// VNInfo.
442  /// \param [out] Kills Append end points of VNI's live range to Kills.
443  /// \param LIS Live intervals analysis.
444  void
445  extendDef(SlotIndex Idx, DbgVariableValue DbgValue,
446            SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>>
447                &LiveIntervalInfo,
448            std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills,
449            LiveIntervals &LIS);
450
451  /// The value in LI may be copies to other registers. Determine if
452  /// any of the copies are available at the kill points, and add defs if
453  /// possible.
454  ///
455  /// \param DbgValue Location number of LI->reg, and DIExpression.
456  /// \param LocIntervals Scan for copies of the value for each location in the
457  /// corresponding LiveInterval->reg.
458  /// \param KilledAt The point where the range of DbgValue could be extended.
459  /// \param [in,out] NewDefs Append (Idx, DbgValue) of inserted defs here.
460  void addDefsFromCopies(
461      DbgVariableValue DbgValue,
462      SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals,
463      SlotIndex KilledAt,
464      SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
465      MachineRegisterInfo &MRI, LiveIntervals &LIS);
466
467  /// Compute the live intervals of all locations after collecting all their
468  /// def points.
469  void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
470                        LiveIntervals &LIS, LexicalScopes &LS);
471
472  /// Replace OldReg ranges with NewRegs ranges where NewRegs is
473  /// live. Returns true if any changes were made.
474  bool splitRegister(Register OldReg, ArrayRef<Register> NewRegs,
475                     LiveIntervals &LIS);
476
477  /// Rewrite virtual register locations according to the provided virtual
478  /// register map. Record the stack slot offsets for the locations that
479  /// were spilled.
480  void rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
481                        const TargetInstrInfo &TII,
482                        const TargetRegisterInfo &TRI,
483                        SpillOffsetMap &SpillOffsets);
484
485  /// Recreate DBG_VALUE instruction from data structures.
486  void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
487                       const TargetInstrInfo &TII,
488                       const TargetRegisterInfo &TRI,
489                       const SpillOffsetMap &SpillOffsets,
490                       BlockSkipInstsMap &BBSkipInstsMap);
491
492  /// Return DebugLoc of this UserValue.
493  const DebugLoc &getDebugLoc() { return dl; }
494
495  void print(raw_ostream &, const TargetRegisterInfo *);
496};
497
498/// A user label is a part of a debug info user label.
499class UserLabel {
500  const DILabel *Label; ///< The debug info label we are part of.
501  DebugLoc dl;          ///< The debug location for the label. This is
502                        ///< used by dwarf writer to find lexical scope.
503  SlotIndex loc;        ///< Slot used by the debug label.
504
505  /// Insert a DBG_LABEL into MBB at Idx.
506  void insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
507                        LiveIntervals &LIS, const TargetInstrInfo &TII,
508                        BlockSkipInstsMap &BBSkipInstsMap);
509
510public:
511  /// Create a new UserLabel.
512  UserLabel(const DILabel *label, DebugLoc L, SlotIndex Idx)
513      : Label(label), dl(std::move(L)), loc(Idx) {}
514
515  /// Does this UserLabel match the parameters?
516  bool matches(const DILabel *L, const DILocation *IA,
517             const SlotIndex Index) const {
518    return Label == L && dl->getInlinedAt() == IA && loc == Index;
519  }
520
521  /// Recreate DBG_LABEL instruction from data structures.
522  void emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
523                      BlockSkipInstsMap &BBSkipInstsMap);
524
525  /// Return DebugLoc of this UserLabel.
526  const DebugLoc &getDebugLoc() { return dl; }
527
528  void print(raw_ostream &, const TargetRegisterInfo *);
529};
530
531/// Implementation of the LiveDebugVariables pass.
532class LDVImpl {
533  LiveDebugVariables &pass;
534  LocMap::Allocator allocator;
535  MachineFunction *MF = nullptr;
536  LiveIntervals *LIS;
537  const TargetRegisterInfo *TRI;
538
539  /// Position and VReg of a PHI instruction during register allocation.
540  struct PHIValPos {
541    SlotIndex SI;    /// Slot where this PHI occurs.
542    Register Reg;    /// VReg this PHI occurs in.
543    unsigned SubReg; /// Qualifiying subregister for Reg.
544  };
545
546  /// Map from debug instruction number to PHI position during allocation.
547  std::map<unsigned, PHIValPos> PHIValToPos;
548  /// Index of, for each VReg, which debug instruction numbers and corresponding
549  /// PHIs are sensitive to splitting. Each VReg may have multiple PHI defs,
550  /// at different positions.
551  DenseMap<Register, std::vector<unsigned>> RegToPHIIdx;
552
553  /// Record for any debug instructions unlinked from their blocks during
554  /// regalloc. Stores the instr and it's location, so that they can be
555  /// re-inserted after regalloc is over.
556  struct InstrPos {
557    MachineInstr *MI;       ///< Debug instruction, unlinked from it's block.
558    SlotIndex Idx;          ///< Slot position where MI should be re-inserted.
559    MachineBasicBlock *MBB; ///< Block that MI was in.
560  };
561
562  /// Collection of stored debug instructions, preserved until after regalloc.
563  SmallVector<InstrPos, 32> StashedDebugInstrs;
564
565  /// Whether emitDebugValues is called.
566  bool EmitDone = false;
567
568  /// Whether the machine function is modified during the pass.
569  bool ModifiedMF = false;
570
571  /// All allocated UserValue instances.
572  SmallVector<std::unique_ptr<UserValue>, 8> userValues;
573
574  /// All allocated UserLabel instances.
575  SmallVector<std::unique_ptr<UserLabel>, 2> userLabels;
576
577  /// Map virtual register to eq class leader.
578  using VRMap = DenseMap<unsigned, UserValue *>;
579  VRMap virtRegToEqClass;
580
581  /// Map to find existing UserValue instances.
582  using UVMap = DenseMap<DebugVariable, UserValue *>;
583  UVMap userVarMap;
584
585  /// Find or create a UserValue.
586  UserValue *getUserValue(const DILocalVariable *Var,
587                          std::optional<DIExpression::FragmentInfo> Fragment,
588                          const DebugLoc &DL);
589
590  /// Find the EC leader for VirtReg or null.
591  UserValue *lookupVirtReg(Register VirtReg);
592
593  /// Add DBG_VALUE instruction to our maps.
594  ///
595  /// \param MI DBG_VALUE instruction
596  /// \param Idx Last valid SLotIndex before instruction.
597  ///
598  /// \returns True if the DBG_VALUE instruction should be deleted.
599  bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
600
601  /// Track variable location debug instructions while using the instruction
602  /// referencing implementation. Such debug instructions do not need to be
603  /// updated during regalloc because they identify instructions rather than
604  /// register locations. However, they needs to be removed from the
605  /// MachineFunction during regalloc, then re-inserted later, to avoid
606  /// disrupting the allocator.
607  ///
608  /// \param MI Any DBG_VALUE / DBG_INSTR_REF / DBG_PHI instruction
609  /// \param Idx Last valid SlotIndex before instruction
610  ///
611  /// \returns Iterator to continue processing from after unlinking.
612  MachineBasicBlock::iterator handleDebugInstr(MachineInstr &MI, SlotIndex Idx);
613
614  /// Add DBG_LABEL instruction to UserLabel.
615  ///
616  /// \param MI DBG_LABEL instruction
617  /// \param Idx Last valid SlotIndex before instruction.
618  ///
619  /// \returns True if the DBG_LABEL instruction should be deleted.
620  bool handleDebugLabel(MachineInstr &MI, SlotIndex Idx);
621
622  /// Collect and erase all DBG_VALUE instructions, adding a UserValue def
623  /// for each instruction.
624  ///
625  /// \param mf MachineFunction to be scanned.
626  /// \param InstrRef Whether to operate in instruction referencing mode. If
627  ///        true, most of LiveDebugVariables doesn't run.
628  ///
629  /// \returns True if any debug values were found.
630  bool collectDebugValues(MachineFunction &mf, bool InstrRef);
631
632  /// Compute the live intervals of all user values after collecting all
633  /// their def points.
634  void computeIntervals();
635
636public:
637  LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
638
639  bool runOnMachineFunction(MachineFunction &mf, bool InstrRef);
640
641  /// Release all memory.
642  void clear() {
643    MF = nullptr;
644    PHIValToPos.clear();
645    RegToPHIIdx.clear();
646    StashedDebugInstrs.clear();
647    userValues.clear();
648    userLabels.clear();
649    virtRegToEqClass.clear();
650    userVarMap.clear();
651    // Make sure we call emitDebugValues if the machine function was modified.
652    assert((!ModifiedMF || EmitDone) &&
653           "Dbg values are not emitted in LDV");
654    EmitDone = false;
655    ModifiedMF = false;
656  }
657
658  /// Map virtual register to an equivalence class.
659  void mapVirtReg(Register VirtReg, UserValue *EC);
660
661  /// Replace any PHI referring to OldReg with its corresponding NewReg, if
662  /// present.
663  void splitPHIRegister(Register OldReg, ArrayRef<Register> NewRegs);
664
665  /// Replace all references to OldReg with NewRegs.
666  void splitRegister(Register OldReg, ArrayRef<Register> NewRegs);
667
668  /// Recreate DBG_VALUE instruction from data structures.
669  void emitDebugValues(VirtRegMap *VRM);
670
671  void print(raw_ostream&);
672};
673
674} // end anonymous namespace
675
676#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
677static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
678                          const LLVMContext &Ctx) {
679  if (!DL)
680    return;
681
682  auto *Scope = cast<DIScope>(DL.getScope());
683  // Omit the directory, because it's likely to be long and uninteresting.
684  CommentOS << Scope->getFilename();
685  CommentOS << ':' << DL.getLine();
686  if (DL.getCol() != 0)
687    CommentOS << ':' << DL.getCol();
688
689  DebugLoc InlinedAtDL = DL.getInlinedAt();
690  if (!InlinedAtDL)
691    return;
692
693  CommentOS << " @[ ";
694  printDebugLoc(InlinedAtDL, CommentOS, Ctx);
695  CommentOS << " ]";
696}
697
698static void printExtendedName(raw_ostream &OS, const DINode *Node,
699                              const DILocation *DL) {
700  const LLVMContext &Ctx = Node->getContext();
701  StringRef Res;
702  unsigned Line = 0;
703  if (const auto *V = dyn_cast<const DILocalVariable>(Node)) {
704    Res = V->getName();
705    Line = V->getLine();
706  } else if (const auto *L = dyn_cast<const DILabel>(Node)) {
707    Res = L->getName();
708    Line = L->getLine();
709  }
710
711  if (!Res.empty())
712    OS << Res << "," << Line;
713  auto *InlinedAt = DL ? DL->getInlinedAt() : nullptr;
714  if (InlinedAt) {
715    if (DebugLoc InlinedAtDL = InlinedAt) {
716      OS << " @[";
717      printDebugLoc(InlinedAtDL, OS, Ctx);
718      OS << "]";
719    }
720  }
721}
722
723void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
724  OS << "!\"";
725  printExtendedName(OS, Variable, dl);
726
727  OS << "\"\t";
728  for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
729    OS << " [" << I.start() << ';' << I.stop() << "):";
730    if (I.value().isUndef())
731      OS << " undef";
732    else {
733      I.value().printLocNos(OS);
734      if (I.value().getWasIndirect())
735        OS << " ind";
736      else if (I.value().getWasList())
737        OS << " list";
738    }
739  }
740  for (unsigned i = 0, e = locations.size(); i != e; ++i) {
741    OS << " Loc" << i << '=';
742    locations[i].print(OS, TRI);
743  }
744  OS << '\n';
745}
746
747void UserLabel::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
748  OS << "!\"";
749  printExtendedName(OS, Label, dl);
750
751  OS << "\"\t";
752  OS << loc;
753  OS << '\n';
754}
755
756void LDVImpl::print(raw_ostream &OS) {
757  OS << "********** DEBUG VARIABLES **********\n";
758  for (auto &userValue : userValues)
759    userValue->print(OS, TRI);
760  OS << "********** DEBUG LABELS **********\n";
761  for (auto &userLabel : userLabels)
762    userLabel->print(OS, TRI);
763}
764#endif
765
766void UserValue::mapVirtRegs(LDVImpl *LDV) {
767  for (unsigned i = 0, e = locations.size(); i != e; ++i)
768    if (locations[i].isReg() && locations[i].getReg().isVirtual())
769      LDV->mapVirtReg(locations[i].getReg(), this);
770}
771
772UserValue *
773LDVImpl::getUserValue(const DILocalVariable *Var,
774                      std::optional<DIExpression::FragmentInfo> Fragment,
775                      const DebugLoc &DL) {
776  // FIXME: Handle partially overlapping fragments. See
777  // https://reviews.llvm.org/D70121#1849741.
778  DebugVariable ID(Var, Fragment, DL->getInlinedAt());
779  UserValue *&UV = userVarMap[ID];
780  if (!UV) {
781    userValues.push_back(
782        std::make_unique<UserValue>(Var, Fragment, DL, allocator));
783    UV = userValues.back().get();
784  }
785  return UV;
786}
787
788void LDVImpl::mapVirtReg(Register VirtReg, UserValue *EC) {
789  assert(VirtReg.isVirtual() && "Only map VirtRegs");
790  UserValue *&Leader = virtRegToEqClass[VirtReg];
791  Leader = UserValue::merge(Leader, EC);
792}
793
794UserValue *LDVImpl::lookupVirtReg(Register VirtReg) {
795  if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
796    return UV->getLeader();
797  return nullptr;
798}
799
800bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
801  // DBG_VALUE loc, offset, variable, expr
802  // DBG_VALUE_LIST variable, expr, locs...
803  if (!MI.isDebugValue()) {
804    LLVM_DEBUG(dbgs() << "Can't handle non-DBG_VALUE*: " << MI);
805    return false;
806  }
807  if (!MI.getDebugVariableOp().isMetadata()) {
808    LLVM_DEBUG(dbgs() << "Can't handle DBG_VALUE* with invalid variable: "
809                      << MI);
810    return false;
811  }
812  if (MI.isNonListDebugValue() &&
813      (MI.getNumOperands() != 4 ||
814       !(MI.getDebugOffset().isImm() || MI.getDebugOffset().isReg()))) {
815    LLVM_DEBUG(dbgs() << "Can't handle malformed DBG_VALUE: " << MI);
816    return false;
817  }
818
819  // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual
820  // register that hasn't been defined yet. If we do not remove those here, then
821  // the re-insertion of the DBG_VALUE instruction after register allocation
822  // will be incorrect.
823  bool Discard = false;
824  for (const MachineOperand &Op : MI.debug_operands()) {
825    if (Op.isReg() && Op.getReg().isVirtual()) {
826      const Register Reg = Op.getReg();
827      if (!LIS->hasInterval(Reg)) {
828        // The DBG_VALUE is described by a virtual register that does not have a
829        // live interval. Discard the DBG_VALUE.
830        Discard = true;
831        LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx
832                          << " " << MI);
833      } else {
834        // The DBG_VALUE is only valid if either Reg is live out from Idx, or
835        // Reg is defined dead at Idx (where Idx is the slot index for the
836        // instruction preceding the DBG_VALUE).
837        const LiveInterval &LI = LIS->getInterval(Reg);
838        LiveQueryResult LRQ = LI.Query(Idx);
839        if (!LRQ.valueOutOrDead()) {
840          // We have found a DBG_VALUE with the value in a virtual register that
841          // is not live. Discard the DBG_VALUE.
842          Discard = true;
843          LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx
844                            << " " << MI);
845        }
846      }
847    }
848  }
849
850  // Get or create the UserValue for (variable,offset) here.
851  bool IsIndirect = MI.isDebugOffsetImm();
852  if (IsIndirect)
853    assert(MI.getDebugOffset().getImm() == 0 &&
854           "DBG_VALUE with nonzero offset");
855  bool IsList = MI.isDebugValueList();
856  const DILocalVariable *Var = MI.getDebugVariable();
857  const DIExpression *Expr = MI.getDebugExpression();
858  UserValue *UV = getUserValue(Var, Expr->getFragmentInfo(), MI.getDebugLoc());
859  if (!Discard)
860    UV->addDef(Idx,
861               ArrayRef<MachineOperand>(MI.debug_operands().begin(),
862                                        MI.debug_operands().end()),
863               IsIndirect, IsList, *Expr);
864  else {
865    MachineOperand MO = MachineOperand::CreateReg(0U, false);
866    MO.setIsDebug();
867    // We should still pass a list the same size as MI.debug_operands() even if
868    // all MOs are undef, so that DbgVariableValue can correctly adjust the
869    // expression while removing the duplicated undefs.
870    SmallVector<MachineOperand, 4> UndefMOs(MI.getNumDebugOperands(), MO);
871    UV->addDef(Idx, UndefMOs, false, IsList, *Expr);
872  }
873  return true;
874}
875
876MachineBasicBlock::iterator LDVImpl::handleDebugInstr(MachineInstr &MI,
877                                                      SlotIndex Idx) {
878  assert(MI.isDebugValueLike() || MI.isDebugPHI());
879
880  // In instruction referencing mode, there should be no DBG_VALUE instructions
881  // that refer to virtual registers. They might still refer to constants.
882  if (MI.isDebugValueLike())
883    assert(none_of(MI.debug_operands(),
884                   [](const MachineOperand &MO) {
885                     return MO.isReg() && MO.getReg().isVirtual();
886                   }) &&
887           "MIs should not refer to Virtual Registers in InstrRef mode.");
888
889  // Unlink the instruction, store it in the debug instructions collection.
890  auto NextInst = std::next(MI.getIterator());
891  auto *MBB = MI.getParent();
892  MI.removeFromParent();
893  StashedDebugInstrs.push_back({&MI, Idx, MBB});
894  return NextInst;
895}
896
897bool LDVImpl::handleDebugLabel(MachineInstr &MI, SlotIndex Idx) {
898  // DBG_LABEL label
899  if (MI.getNumOperands() != 1 || !MI.getOperand(0).isMetadata()) {
900    LLVM_DEBUG(dbgs() << "Can't handle " << MI);
901    return false;
902  }
903
904  // Get or create the UserLabel for label here.
905  const DILabel *Label = MI.getDebugLabel();
906  const DebugLoc &DL = MI.getDebugLoc();
907  bool Found = false;
908  for (auto const &L : userLabels) {
909    if (L->matches(Label, DL->getInlinedAt(), Idx)) {
910      Found = true;
911      break;
912    }
913  }
914  if (!Found)
915    userLabels.push_back(std::make_unique<UserLabel>(Label, DL, Idx));
916
917  return true;
918}
919
920bool LDVImpl::collectDebugValues(MachineFunction &mf, bool InstrRef) {
921  bool Changed = false;
922  for (MachineBasicBlock &MBB : mf) {
923    for (MachineBasicBlock::iterator MBBI = MBB.begin(), MBBE = MBB.end();
924         MBBI != MBBE;) {
925      // Use the first debug instruction in the sequence to get a SlotIndex
926      // for following consecutive debug instructions.
927      if (!MBBI->isDebugOrPseudoInstr()) {
928        ++MBBI;
929        continue;
930      }
931      // Debug instructions has no slot index. Use the previous
932      // non-debug instruction's SlotIndex as its SlotIndex.
933      SlotIndex Idx =
934          MBBI == MBB.begin()
935              ? LIS->getMBBStartIdx(&MBB)
936              : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
937      // Handle consecutive debug instructions with the same slot index.
938      do {
939        // In instruction referencing mode, pass each instr to handleDebugInstr
940        // to be unlinked. Ignore DBG_VALUE_LISTs -- they refer to vregs, and
941        // need to go through the normal live interval splitting process.
942        if (InstrRef && (MBBI->isNonListDebugValue() || MBBI->isDebugPHI() ||
943                         MBBI->isDebugRef())) {
944          MBBI = handleDebugInstr(*MBBI, Idx);
945          Changed = true;
946        // In normal debug mode, use the dedicated DBG_VALUE / DBG_LABEL handler
947        // to track things through register allocation, and erase the instr.
948        } else if ((MBBI->isDebugValue() && handleDebugValue(*MBBI, Idx)) ||
949                   (MBBI->isDebugLabel() && handleDebugLabel(*MBBI, Idx))) {
950          MBBI = MBB.erase(MBBI);
951          Changed = true;
952        } else
953          ++MBBI;
954      } while (MBBI != MBBE && MBBI->isDebugOrPseudoInstr());
955    }
956  }
957  return Changed;
958}
959
960void UserValue::extendDef(
961    SlotIndex Idx, DbgVariableValue DbgValue,
962    SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>>
963        &LiveIntervalInfo,
964    std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills,
965    LiveIntervals &LIS) {
966  SlotIndex Start = Idx;
967  MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
968  SlotIndex Stop = LIS.getMBBEndIdx(MBB);
969  LocMap::iterator I = locInts.find(Start);
970
971  // Limit to the intersection of the VNIs' live ranges.
972  for (auto &LII : LiveIntervalInfo) {
973    LiveRange *LR = LII.second.first;
974    assert(LR && LII.second.second && "Missing range info for Idx.");
975    LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
976    assert(Segment && Segment->valno == LII.second.second &&
977           "Invalid VNInfo for Idx given?");
978    if (Segment->end < Stop) {
979      Stop = Segment->end;
980      Kills = {Stop, {LII.first}};
981    } else if (Segment->end == Stop && Kills) {
982      // If multiple locations end at the same place, track all of them in
983      // Kills.
984      Kills->second.push_back(LII.first);
985    }
986  }
987
988  // There could already be a short def at Start.
989  if (I.valid() && I.start() <= Start) {
990    // Stop when meeting a different location or an already extended interval.
991    Start = Start.getNextSlot();
992    if (I.value() != DbgValue || I.stop() != Start) {
993      // Clear `Kills`, as we have a new def available.
994      Kills = std::nullopt;
995      return;
996    }
997    // This is a one-slot placeholder. Just skip it.
998    ++I;
999  }
1000
1001  // Limited by the next def.
1002  if (I.valid() && I.start() < Stop) {
1003    Stop = I.start();
1004    // Clear `Kills`, as we have a new def available.
1005    Kills = std::nullopt;
1006  }
1007
1008  if (Start < Stop) {
1009    DbgVariableValue ExtDbgValue(DbgValue);
1010    I.insert(Start, Stop, std::move(ExtDbgValue));
1011  }
1012}
1013
1014void UserValue::addDefsFromCopies(
1015    DbgVariableValue DbgValue,
1016    SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals,
1017    SlotIndex KilledAt,
1018    SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
1019    MachineRegisterInfo &MRI, LiveIntervals &LIS) {
1020  // Don't track copies from physregs, there are too many uses.
1021  if (any_of(LocIntervals,
1022             [](auto LocI) { return !LocI.second->reg().isVirtual(); }))
1023    return;
1024
1025  // Collect all the (vreg, valno) pairs that are copies of LI.
1026  SmallDenseMap<unsigned,
1027                SmallVector<std::pair<LiveInterval *, const VNInfo *>, 4>>
1028      CopyValues;
1029  for (auto &LocInterval : LocIntervals) {
1030    unsigned LocNo = LocInterval.first;
1031    LiveInterval *LI = LocInterval.second;
1032    for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg())) {
1033      MachineInstr *MI = MO.getParent();
1034      // Copies of the full value.
1035      if (MO.getSubReg() || !MI->isCopy())
1036        continue;
1037      Register DstReg = MI->getOperand(0).getReg();
1038
1039      // Don't follow copies to physregs. These are usually setting up call
1040      // arguments, and the argument registers are always call clobbered. We are
1041      // better off in the source register which could be a callee-saved
1042      // register, or it could be spilled.
1043      if (!DstReg.isVirtual())
1044        continue;
1045
1046      // Is the value extended to reach this copy? If not, another def may be
1047      // blocking it, or we are looking at a wrong value of LI.
1048      SlotIndex Idx = LIS.getInstructionIndex(*MI);
1049      LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
1050      if (!I.valid() || I.value() != DbgValue)
1051        continue;
1052
1053      if (!LIS.hasInterval(DstReg))
1054        continue;
1055      LiveInterval *DstLI = &LIS.getInterval(DstReg);
1056      const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
1057      assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
1058      CopyValues[LocNo].push_back(std::make_pair(DstLI, DstVNI));
1059    }
1060  }
1061
1062  if (CopyValues.empty())
1063    return;
1064
1065#if !defined(NDEBUG)
1066  for (auto &LocInterval : LocIntervals)
1067    LLVM_DEBUG(dbgs() << "Got " << CopyValues[LocInterval.first].size()
1068                      << " copies of " << *LocInterval.second << '\n');
1069#endif
1070
1071  // Try to add defs of the copied values for the kill point. Check that there
1072  // isn't already a def at Idx.
1073  LocMap::iterator I = locInts.find(KilledAt);
1074  if (I.valid() && I.start() <= KilledAt)
1075    return;
1076  DbgVariableValue NewValue(DbgValue);
1077  for (auto &LocInterval : LocIntervals) {
1078    unsigned LocNo = LocInterval.first;
1079    bool FoundCopy = false;
1080    for (auto &LIAndVNI : CopyValues[LocNo]) {
1081      LiveInterval *DstLI = LIAndVNI.first;
1082      const VNInfo *DstVNI = LIAndVNI.second;
1083      if (DstLI->getVNInfoAt(KilledAt) != DstVNI)
1084        continue;
1085      LLVM_DEBUG(dbgs() << "Kill at " << KilledAt << " covered by valno #"
1086                        << DstVNI->id << " in " << *DstLI << '\n');
1087      MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
1088      assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
1089      unsigned NewLocNo = getLocationNo(CopyMI->getOperand(0));
1090      NewValue = NewValue.changeLocNo(LocNo, NewLocNo);
1091      FoundCopy = true;
1092      break;
1093    }
1094    // If there are any killed locations we can't find a copy for, we can't
1095    // extend the variable value.
1096    if (!FoundCopy)
1097      return;
1098  }
1099  I.insert(KilledAt, KilledAt.getNextSlot(), NewValue);
1100  NewDefs.push_back(std::make_pair(KilledAt, NewValue));
1101}
1102
1103void UserValue::computeIntervals(MachineRegisterInfo &MRI,
1104                                 const TargetRegisterInfo &TRI,
1105                                 LiveIntervals &LIS, LexicalScopes &LS) {
1106  SmallVector<std::pair<SlotIndex, DbgVariableValue>, 16> Defs;
1107
1108  // Collect all defs to be extended (Skipping undefs).
1109  for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
1110    if (!I.value().isUndef())
1111      Defs.push_back(std::make_pair(I.start(), I.value()));
1112
1113  // Extend all defs, and possibly add new ones along the way.
1114  for (unsigned i = 0; i != Defs.size(); ++i) {
1115    SlotIndex Idx = Defs[i].first;
1116    DbgVariableValue DbgValue = Defs[i].second;
1117    SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>> LIs;
1118    SmallVector<const VNInfo *, 4> VNIs;
1119    bool ShouldExtendDef = false;
1120    for (unsigned LocNo : DbgValue.loc_nos()) {
1121      const MachineOperand &LocMO = locations[LocNo];
1122      if (!LocMO.isReg() || !LocMO.getReg().isVirtual()) {
1123        ShouldExtendDef |= !LocMO.isReg();
1124        continue;
1125      }
1126      ShouldExtendDef = true;
1127      LiveInterval *LI = nullptr;
1128      const VNInfo *VNI = nullptr;
1129      if (LIS.hasInterval(LocMO.getReg())) {
1130        LI = &LIS.getInterval(LocMO.getReg());
1131        VNI = LI->getVNInfoAt(Idx);
1132      }
1133      if (LI && VNI)
1134        LIs[LocNo] = {LI, VNI};
1135    }
1136    if (ShouldExtendDef) {
1137      std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> Kills;
1138      extendDef(Idx, DbgValue, LIs, Kills, LIS);
1139
1140      if (Kills) {
1141        SmallVector<std::pair<unsigned, LiveInterval *>, 2> KilledLocIntervals;
1142        bool AnySubreg = false;
1143        for (unsigned LocNo : Kills->second) {
1144          const MachineOperand &LocMO = this->locations[LocNo];
1145          if (LocMO.getSubReg()) {
1146            AnySubreg = true;
1147            break;
1148          }
1149          LiveInterval *LI = &LIS.getInterval(LocMO.getReg());
1150          KilledLocIntervals.push_back({LocNo, LI});
1151        }
1152
1153        // FIXME: Handle sub-registers in addDefsFromCopies. The problem is that
1154        // if the original location for example is %vreg0:sub_hi, and we find a
1155        // full register copy in addDefsFromCopies (at the moment it only
1156        // handles full register copies), then we must add the sub1 sub-register
1157        // index to the new location. However, that is only possible if the new
1158        // virtual register is of the same regclass (or if there is an
1159        // equivalent sub-register in that regclass). For now, simply skip
1160        // handling copies if a sub-register is involved.
1161        if (!AnySubreg)
1162          addDefsFromCopies(DbgValue, KilledLocIntervals, Kills->first, Defs,
1163                            MRI, LIS);
1164      }
1165    }
1166
1167    // For physregs, we only mark the start slot idx. DwarfDebug will see it
1168    // as if the DBG_VALUE is valid up until the end of the basic block, or
1169    // the next def of the physical register. So we do not need to extend the
1170    // range. It might actually happen that the DBG_VALUE is the last use of
1171    // the physical register (e.g. if this is an unused input argument to a
1172    // function).
1173  }
1174
1175  // The computed intervals may extend beyond the range of the debug
1176  // location's lexical scope. In this case, splitting of an interval
1177  // can result in an interval outside of the scope being created,
1178  // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
1179  // this, trim the intervals to the lexical scope in the case of inlined
1180  // variables, since heavy inlining may cause production of dramatically big
1181  // number of DBG_VALUEs to be generated.
1182  if (!dl.getInlinedAt())
1183    return;
1184
1185  LexicalScope *Scope = LS.findLexicalScope(dl);
1186  if (!Scope)
1187    return;
1188
1189  SlotIndex PrevEnd;
1190  LocMap::iterator I = locInts.begin();
1191
1192  // Iterate over the lexical scope ranges. Each time round the loop
1193  // we check the intervals for overlap with the end of the previous
1194  // range and the start of the next. The first range is handled as
1195  // a special case where there is no PrevEnd.
1196  for (const InsnRange &Range : Scope->getRanges()) {
1197    SlotIndex RStart = LIS.getInstructionIndex(*Range.first);
1198    SlotIndex REnd = LIS.getInstructionIndex(*Range.second);
1199
1200    // Variable locations at the first instruction of a block should be
1201    // based on the block's SlotIndex, not the first instruction's index.
1202    if (Range.first == Range.first->getParent()->begin())
1203      RStart = LIS.getSlotIndexes()->getIndexBefore(*Range.first);
1204
1205    // At the start of each iteration I has been advanced so that
1206    // I.stop() >= PrevEnd. Check for overlap.
1207    if (PrevEnd && I.start() < PrevEnd) {
1208      SlotIndex IStop = I.stop();
1209      DbgVariableValue DbgValue = I.value();
1210
1211      // Stop overlaps previous end - trim the end of the interval to
1212      // the scope range.
1213      I.setStopUnchecked(PrevEnd);
1214      ++I;
1215
1216      // If the interval also overlaps the start of the "next" (i.e.
1217      // current) range create a new interval for the remainder (which
1218      // may be further trimmed).
1219      if (RStart < IStop)
1220        I.insert(RStart, IStop, DbgValue);
1221    }
1222
1223    // Advance I so that I.stop() >= RStart, and check for overlap.
1224    I.advanceTo(RStart);
1225    if (!I.valid())
1226      return;
1227
1228    if (I.start() < RStart) {
1229      // Interval start overlaps range - trim to the scope range.
1230      I.setStartUnchecked(RStart);
1231      // Remember that this interval was trimmed.
1232      trimmedDefs.insert(RStart);
1233    }
1234
1235    // The end of a lexical scope range is the last instruction in the
1236    // range. To convert to an interval we need the index of the
1237    // instruction after it.
1238    REnd = REnd.getNextIndex();
1239
1240    // Advance I to first interval outside current range.
1241    I.advanceTo(REnd);
1242    if (!I.valid())
1243      return;
1244
1245    PrevEnd = REnd;
1246  }
1247
1248  // Check for overlap with end of final range.
1249  if (PrevEnd && I.start() < PrevEnd)
1250    I.setStopUnchecked(PrevEnd);
1251}
1252
1253void LDVImpl::computeIntervals() {
1254  LexicalScopes LS;
1255  LS.initialize(*MF);
1256
1257  for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
1258    userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS);
1259    userValues[i]->mapVirtRegs(this);
1260  }
1261}
1262
1263bool LDVImpl::runOnMachineFunction(MachineFunction &mf, bool InstrRef) {
1264  clear();
1265  MF = &mf;
1266  LIS = &pass.getAnalysis<LiveIntervals>();
1267  TRI = mf.getSubtarget().getRegisterInfo();
1268  LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
1269                    << mf.getName() << " **********\n");
1270
1271  bool Changed = collectDebugValues(mf, InstrRef);
1272  computeIntervals();
1273  LLVM_DEBUG(print(dbgs()));
1274
1275  // Collect the set of VReg / SlotIndexs where PHIs occur; index the sensitive
1276  // VRegs too, for when we're notified of a range split.
1277  SlotIndexes *Slots = LIS->getSlotIndexes();
1278  for (const auto &PHIIt : MF->DebugPHIPositions) {
1279    const MachineFunction::DebugPHIRegallocPos &Position = PHIIt.second;
1280    MachineBasicBlock *MBB = Position.MBB;
1281    Register Reg = Position.Reg;
1282    unsigned SubReg = Position.SubReg;
1283    SlotIndex SI = Slots->getMBBStartIdx(MBB);
1284    PHIValPos VP = {SI, Reg, SubReg};
1285    PHIValToPos.insert(std::make_pair(PHIIt.first, VP));
1286    RegToPHIIdx[Reg].push_back(PHIIt.first);
1287  }
1288
1289  ModifiedMF = Changed;
1290  return Changed;
1291}
1292
1293static void removeDebugInstrs(MachineFunction &mf) {
1294  for (MachineBasicBlock &MBB : mf) {
1295    for (MachineInstr &MI : llvm::make_early_inc_range(MBB))
1296      if (MI.isDebugInstr())
1297        MBB.erase(&MI);
1298  }
1299}
1300
1301bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
1302  if (!EnableLDV)
1303    return false;
1304  if (!mf.getFunction().getSubprogram()) {
1305    removeDebugInstrs(mf);
1306    return false;
1307  }
1308
1309  // Have we been asked to track variable locations using instruction
1310  // referencing?
1311  bool InstrRef = mf.useDebugInstrRef();
1312
1313  if (!pImpl)
1314    pImpl = new LDVImpl(this);
1315  return static_cast<LDVImpl *>(pImpl)->runOnMachineFunction(mf, InstrRef);
1316}
1317
1318void LiveDebugVariables::releaseMemory() {
1319  if (pImpl)
1320    static_cast<LDVImpl*>(pImpl)->clear();
1321}
1322
1323LiveDebugVariables::~LiveDebugVariables() {
1324  if (pImpl)
1325    delete static_cast<LDVImpl*>(pImpl);
1326}
1327
1328//===----------------------------------------------------------------------===//
1329//                           Live Range Splitting
1330//===----------------------------------------------------------------------===//
1331
1332bool
1333UserValue::splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs,
1334                         LiveIntervals& LIS) {
1335  LLVM_DEBUG({
1336    dbgs() << "Splitting Loc" << OldLocNo << '\t';
1337    print(dbgs(), nullptr);
1338  });
1339  bool DidChange = false;
1340  LocMap::iterator LocMapI;
1341  LocMapI.setMap(locInts);
1342  for (Register NewReg : NewRegs) {
1343    LiveInterval *LI = &LIS.getInterval(NewReg);
1344    if (LI->empty())
1345      continue;
1346
1347    // Don't allocate the new LocNo until it is needed.
1348    unsigned NewLocNo = UndefLocNo;
1349
1350    // Iterate over the overlaps between locInts and LI.
1351    LocMapI.find(LI->beginIndex());
1352    if (!LocMapI.valid())
1353      continue;
1354    LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
1355    LiveInterval::iterator LIE = LI->end();
1356    while (LocMapI.valid() && LII != LIE) {
1357      // At this point, we know that LocMapI.stop() > LII->start.
1358      LII = LI->advanceTo(LII, LocMapI.start());
1359      if (LII == LIE)
1360        break;
1361
1362      // Now LII->end > LocMapI.start(). Do we have an overlap?
1363      if (LocMapI.value().containsLocNo(OldLocNo) &&
1364          LII->start < LocMapI.stop()) {
1365        // Overlapping correct location. Allocate NewLocNo now.
1366        if (NewLocNo == UndefLocNo) {
1367          MachineOperand MO = MachineOperand::CreateReg(LI->reg(), false);
1368          MO.setSubReg(locations[OldLocNo].getSubReg());
1369          NewLocNo = getLocationNo(MO);
1370          DidChange = true;
1371        }
1372
1373        SlotIndex LStart = LocMapI.start();
1374        SlotIndex LStop = LocMapI.stop();
1375        DbgVariableValue OldDbgValue = LocMapI.value();
1376
1377        // Trim LocMapI down to the LII overlap.
1378        if (LStart < LII->start)
1379          LocMapI.setStartUnchecked(LII->start);
1380        if (LStop > LII->end)
1381          LocMapI.setStopUnchecked(LII->end);
1382
1383        // Change the value in the overlap. This may trigger coalescing.
1384        LocMapI.setValue(OldDbgValue.changeLocNo(OldLocNo, NewLocNo));
1385
1386        // Re-insert any removed OldDbgValue ranges.
1387        if (LStart < LocMapI.start()) {
1388          LocMapI.insert(LStart, LocMapI.start(), OldDbgValue);
1389          ++LocMapI;
1390          assert(LocMapI.valid() && "Unexpected coalescing");
1391        }
1392        if (LStop > LocMapI.stop()) {
1393          ++LocMapI;
1394          LocMapI.insert(LII->end, LStop, OldDbgValue);
1395          --LocMapI;
1396        }
1397      }
1398
1399      // Advance to the next overlap.
1400      if (LII->end < LocMapI.stop()) {
1401        if (++LII == LIE)
1402          break;
1403        LocMapI.advanceTo(LII->start);
1404      } else {
1405        ++LocMapI;
1406        if (!LocMapI.valid())
1407          break;
1408        LII = LI->advanceTo(LII, LocMapI.start());
1409      }
1410    }
1411  }
1412
1413  // Finally, remove OldLocNo unless it is still used by some interval in the
1414  // locInts map. One case when OldLocNo still is in use is when the register
1415  // has been spilled. In such situations the spilled register is kept as a
1416  // location until rewriteLocations is called (VirtRegMap is mapping the old
1417  // register to the spill slot). So for a while we can have locations that map
1418  // to virtual registers that have been removed from both the MachineFunction
1419  // and from LiveIntervals.
1420  //
1421  // We may also just be using the location for a value with a different
1422  // expression.
1423  removeLocationIfUnused(OldLocNo);
1424
1425  LLVM_DEBUG({
1426    dbgs() << "Split result: \t";
1427    print(dbgs(), nullptr);
1428  });
1429  return DidChange;
1430}
1431
1432bool
1433UserValue::splitRegister(Register OldReg, ArrayRef<Register> NewRegs,
1434                         LiveIntervals &LIS) {
1435  bool DidChange = false;
1436  // Split locations referring to OldReg. Iterate backwards so splitLocation can
1437  // safely erase unused locations.
1438  for (unsigned i = locations.size(); i ; --i) {
1439    unsigned LocNo = i-1;
1440    const MachineOperand *Loc = &locations[LocNo];
1441    if (!Loc->isReg() || Loc->getReg() != OldReg)
1442      continue;
1443    DidChange |= splitLocation(LocNo, NewRegs, LIS);
1444  }
1445  return DidChange;
1446}
1447
1448void LDVImpl::splitPHIRegister(Register OldReg, ArrayRef<Register> NewRegs) {
1449  auto RegIt = RegToPHIIdx.find(OldReg);
1450  if (RegIt == RegToPHIIdx.end())
1451    return;
1452
1453  std::vector<std::pair<Register, unsigned>> NewRegIdxes;
1454  // Iterate over all the debug instruction numbers affected by this split.
1455  for (unsigned InstrID : RegIt->second) {
1456    auto PHIIt = PHIValToPos.find(InstrID);
1457    assert(PHIIt != PHIValToPos.end());
1458    const SlotIndex &Slot = PHIIt->second.SI;
1459    assert(OldReg == PHIIt->second.Reg);
1460
1461    // Find the new register that covers this position.
1462    for (auto NewReg : NewRegs) {
1463      const LiveInterval &LI = LIS->getInterval(NewReg);
1464      auto LII = LI.find(Slot);
1465      if (LII != LI.end() && LII->start <= Slot) {
1466        // This new register covers this PHI position, record this for indexing.
1467        NewRegIdxes.push_back(std::make_pair(NewReg, InstrID));
1468        // Record that this value lives in a different VReg now.
1469        PHIIt->second.Reg = NewReg;
1470        break;
1471      }
1472    }
1473
1474    // If we do not find a new register covering this PHI, then register
1475    // allocation has dropped its location, for example because it's not live.
1476    // The old VReg will not be mapped to a physreg, and the instruction
1477    // number will have been optimized out.
1478  }
1479
1480  // Re-create register index using the new register numbers.
1481  RegToPHIIdx.erase(RegIt);
1482  for (auto &RegAndInstr : NewRegIdxes)
1483    RegToPHIIdx[RegAndInstr.first].push_back(RegAndInstr.second);
1484}
1485
1486void LDVImpl::splitRegister(Register OldReg, ArrayRef<Register> NewRegs) {
1487  // Consider whether this split range affects any PHI locations.
1488  splitPHIRegister(OldReg, NewRegs);
1489
1490  // Check whether any intervals mapped by a DBG_VALUE were split and need
1491  // updating.
1492  bool DidChange = false;
1493  for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
1494    DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
1495
1496  if (!DidChange)
1497    return;
1498
1499  // Map all of the new virtual registers.
1500  UserValue *UV = lookupVirtReg(OldReg);
1501  for (Register NewReg : NewRegs)
1502    mapVirtReg(NewReg, UV);
1503}
1504
1505void LiveDebugVariables::
1506splitRegister(Register OldReg, ArrayRef<Register> NewRegs, LiveIntervals &LIS) {
1507  if (pImpl)
1508    static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
1509}
1510
1511void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
1512                                 const TargetInstrInfo &TII,
1513                                 const TargetRegisterInfo &TRI,
1514                                 SpillOffsetMap &SpillOffsets) {
1515  // Build a set of new locations with new numbers so we can coalesce our
1516  // IntervalMap if two vreg intervals collapse to the same physical location.
1517  // Use MapVector instead of SetVector because MapVector::insert returns the
1518  // position of the previously or newly inserted element. The boolean value
1519  // tracks if the location was produced by a spill.
1520  // FIXME: This will be problematic if we ever support direct and indirect
1521  // frame index locations, i.e. expressing both variables in memory and
1522  // 'int x, *px = &x'. The "spilled" bit must become part of the location.
1523  MapVector<MachineOperand, std::pair<bool, unsigned>> NewLocations;
1524  SmallVector<unsigned, 4> LocNoMap(locations.size());
1525  for (unsigned I = 0, E = locations.size(); I != E; ++I) {
1526    bool Spilled = false;
1527    unsigned SpillOffset = 0;
1528    MachineOperand Loc = locations[I];
1529    // Only virtual registers are rewritten.
1530    if (Loc.isReg() && Loc.getReg() && Loc.getReg().isVirtual()) {
1531      Register VirtReg = Loc.getReg();
1532      if (VRM.isAssignedReg(VirtReg) &&
1533          Register::isPhysicalRegister(VRM.getPhys(VirtReg))) {
1534        // This can create a %noreg operand in rare cases when the sub-register
1535        // index is no longer available. That means the user value is in a
1536        // non-existent sub-register, and %noreg is exactly what we want.
1537        Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
1538      } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
1539        // Retrieve the stack slot offset.
1540        unsigned SpillSize;
1541        const MachineRegisterInfo &MRI = MF.getRegInfo();
1542        const TargetRegisterClass *TRC = MRI.getRegClass(VirtReg);
1543        bool Success = TII.getStackSlotRange(TRC, Loc.getSubReg(), SpillSize,
1544                                             SpillOffset, MF);
1545
1546        // FIXME: Invalidate the location if the offset couldn't be calculated.
1547        (void)Success;
1548
1549        Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
1550        Spilled = true;
1551      } else {
1552        Loc.setReg(0);
1553        Loc.setSubReg(0);
1554      }
1555    }
1556
1557    // Insert this location if it doesn't already exist and record a mapping
1558    // from the old number to the new number.
1559    auto InsertResult = NewLocations.insert({Loc, {Spilled, SpillOffset}});
1560    unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first);
1561    LocNoMap[I] = NewLocNo;
1562  }
1563
1564  // Rewrite the locations and record the stack slot offsets for spills.
1565  locations.clear();
1566  SpillOffsets.clear();
1567  for (auto &Pair : NewLocations) {
1568    bool Spilled;
1569    unsigned SpillOffset;
1570    std::tie(Spilled, SpillOffset) = Pair.second;
1571    locations.push_back(Pair.first);
1572    if (Spilled) {
1573      unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair);
1574      SpillOffsets[NewLocNo] = SpillOffset;
1575    }
1576  }
1577
1578  // Update the interval map, but only coalesce left, since intervals to the
1579  // right use the old location numbers. This should merge two contiguous
1580  // DBG_VALUE intervals with different vregs that were allocated to the same
1581  // physical register.
1582  for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
1583    I.setValueUnchecked(I.value().remapLocNos(LocNoMap));
1584    I.setStart(I.start());
1585  }
1586}
1587
1588/// Find an iterator for inserting a DBG_VALUE instruction.
1589static MachineBasicBlock::iterator
1590findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx, LiveIntervals &LIS,
1591                   BlockSkipInstsMap &BBSkipInstsMap) {
1592  SlotIndex Start = LIS.getMBBStartIdx(MBB);
1593  Idx = Idx.getBaseIndex();
1594
1595  // Try to find an insert location by going backwards from Idx.
1596  MachineInstr *MI;
1597  while (!(MI = LIS.getInstructionFromIndex(Idx))) {
1598    // We've reached the beginning of MBB.
1599    if (Idx == Start) {
1600      // Retrieve the last PHI/Label/Debug location found when calling
1601      // SkipPHIsLabelsAndDebug last time. Start searching from there.
1602      //
1603      // Note the iterator kept in BBSkipInstsMap is one step back based
1604      // on the iterator returned by SkipPHIsLabelsAndDebug last time.
1605      // One exception is when SkipPHIsLabelsAndDebug returns MBB->begin(),
1606      // BBSkipInstsMap won't save it. This is to consider the case that
1607      // new instructions may be inserted at the beginning of MBB after
1608      // last call of SkipPHIsLabelsAndDebug. If we save MBB->begin() in
1609      // BBSkipInstsMap, after new non-phi/non-label/non-debug instructions
1610      // are inserted at the beginning of the MBB, the iterator in
1611      // BBSkipInstsMap won't point to the beginning of the MBB anymore.
1612      // Therefore The next search in SkipPHIsLabelsAndDebug will skip those
1613      // newly added instructions and that is unwanted.
1614      MachineBasicBlock::iterator BeginIt;
1615      auto MapIt = BBSkipInstsMap.find(MBB);
1616      if (MapIt == BBSkipInstsMap.end())
1617        BeginIt = MBB->begin();
1618      else
1619        BeginIt = std::next(MapIt->second);
1620      auto I = MBB->SkipPHIsLabelsAndDebug(BeginIt);
1621      if (I != BeginIt)
1622        BBSkipInstsMap[MBB] = std::prev(I);
1623      return I;
1624    }
1625    Idx = Idx.getPrevIndex();
1626  }
1627
1628  // Don't insert anything after the first terminator, though.
1629  return MI->isTerminator() ? MBB->getFirstTerminator() :
1630                              std::next(MachineBasicBlock::iterator(MI));
1631}
1632
1633/// Find an iterator for inserting the next DBG_VALUE instruction
1634/// (or end if no more insert locations found).
1635static MachineBasicBlock::iterator
1636findNextInsertLocation(MachineBasicBlock *MBB, MachineBasicBlock::iterator I,
1637                       SlotIndex StopIdx, ArrayRef<MachineOperand> LocMOs,
1638                       LiveIntervals &LIS, const TargetRegisterInfo &TRI) {
1639  SmallVector<Register, 4> Regs;
1640  for (const MachineOperand &LocMO : LocMOs)
1641    if (LocMO.isReg())
1642      Regs.push_back(LocMO.getReg());
1643  if (Regs.empty())
1644    return MBB->instr_end();
1645
1646  // Find the next instruction in the MBB that define the register Reg.
1647  while (I != MBB->end() && !I->isTerminator()) {
1648    if (!LIS.isNotInMIMap(*I) &&
1649        SlotIndex::isEarlierEqualInstr(StopIdx, LIS.getInstructionIndex(*I)))
1650      break;
1651    if (any_of(Regs, [&I, &TRI](Register &Reg) {
1652          return I->definesRegister(Reg, &TRI);
1653        }))
1654      // The insert location is directly after the instruction/bundle.
1655      return std::next(I);
1656    ++I;
1657  }
1658  return MBB->end();
1659}
1660
1661void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
1662                                 SlotIndex StopIdx, DbgVariableValue DbgValue,
1663                                 ArrayRef<bool> LocSpills,
1664                                 ArrayRef<unsigned> SpillOffsets,
1665                                 LiveIntervals &LIS, const TargetInstrInfo &TII,
1666                                 const TargetRegisterInfo &TRI,
1667                                 BlockSkipInstsMap &BBSkipInstsMap) {
1668  SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB);
1669  // Only search within the current MBB.
1670  StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx;
1671  MachineBasicBlock::iterator I =
1672      findInsertLocation(MBB, StartIdx, LIS, BBSkipInstsMap);
1673  // Undef values don't exist in locations so create new "noreg" register MOs
1674  // for them. See getLocationNo().
1675  SmallVector<MachineOperand, 8> MOs;
1676  if (DbgValue.isUndef()) {
1677    MOs.assign(DbgValue.loc_nos().size(),
1678               MachineOperand::CreateReg(
1679                   /* Reg */ 0, /* isDef */ false, /* isImp */ false,
1680                   /* isKill */ false, /* isDead */ false,
1681                   /* isUndef */ false, /* isEarlyClobber */ false,
1682                   /* SubReg */ 0, /* isDebug */ true));
1683  } else {
1684    for (unsigned LocNo : DbgValue.loc_nos())
1685      MOs.push_back(locations[LocNo]);
1686  }
1687
1688  ++NumInsertedDebugValues;
1689
1690  assert(cast<DILocalVariable>(Variable)
1691             ->isValidLocationForIntrinsic(getDebugLoc()) &&
1692         "Expected inlined-at fields to agree");
1693
1694  // If the location was spilled, the new DBG_VALUE will be indirect. If the
1695  // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
1696  // that the original virtual register was a pointer. Also, add the stack slot
1697  // offset for the spilled register to the expression.
1698  const DIExpression *Expr = DbgValue.getExpression();
1699  bool IsIndirect = DbgValue.getWasIndirect();
1700  bool IsList = DbgValue.getWasList();
1701  for (unsigned I = 0, E = LocSpills.size(); I != E; ++I) {
1702    if (LocSpills[I]) {
1703      if (!IsList) {
1704        uint8_t DIExprFlags = DIExpression::ApplyOffset;
1705        if (IsIndirect)
1706          DIExprFlags |= DIExpression::DerefAfter;
1707        Expr = DIExpression::prepend(Expr, DIExprFlags, SpillOffsets[I]);
1708        IsIndirect = true;
1709      } else {
1710        SmallVector<uint64_t, 4> Ops;
1711        DIExpression::appendOffset(Ops, SpillOffsets[I]);
1712        Ops.push_back(dwarf::DW_OP_deref);
1713        Expr = DIExpression::appendOpsToArg(Expr, Ops, I);
1714      }
1715    }
1716
1717    assert((!LocSpills[I] || MOs[I].isFI()) &&
1718           "a spilled location must be a frame index");
1719  }
1720
1721  unsigned DbgValueOpcode =
1722      IsList ? TargetOpcode::DBG_VALUE_LIST : TargetOpcode::DBG_VALUE;
1723  do {
1724    BuildMI(*MBB, I, getDebugLoc(), TII.get(DbgValueOpcode), IsIndirect, MOs,
1725            Variable, Expr);
1726
1727    // Continue and insert DBG_VALUES after every redefinition of a register
1728    // associated with the debug value within the range
1729    I = findNextInsertLocation(MBB, I, StopIdx, MOs, LIS, TRI);
1730  } while (I != MBB->end());
1731}
1732
1733void UserLabel::insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
1734                                 LiveIntervals &LIS, const TargetInstrInfo &TII,
1735                                 BlockSkipInstsMap &BBSkipInstsMap) {
1736  MachineBasicBlock::iterator I =
1737      findInsertLocation(MBB, Idx, LIS, BBSkipInstsMap);
1738  ++NumInsertedDebugLabels;
1739  BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_LABEL))
1740      .addMetadata(Label);
1741}
1742
1743void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
1744                                const TargetInstrInfo &TII,
1745                                const TargetRegisterInfo &TRI,
1746                                const SpillOffsetMap &SpillOffsets,
1747                                BlockSkipInstsMap &BBSkipInstsMap) {
1748  MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
1749
1750  for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
1751    SlotIndex Start = I.start();
1752    SlotIndex Stop = I.stop();
1753    DbgVariableValue DbgValue = I.value();
1754
1755    SmallVector<bool> SpilledLocs;
1756    SmallVector<unsigned> LocSpillOffsets;
1757    for (unsigned LocNo : DbgValue.loc_nos()) {
1758      auto SpillIt =
1759          !DbgValue.isUndef() ? SpillOffsets.find(LocNo) : SpillOffsets.end();
1760      bool Spilled = SpillIt != SpillOffsets.end();
1761      SpilledLocs.push_back(Spilled);
1762      LocSpillOffsets.push_back(Spilled ? SpillIt->second : 0);
1763    }
1764
1765    // If the interval start was trimmed to the lexical scope insert the
1766    // DBG_VALUE at the previous index (otherwise it appears after the
1767    // first instruction in the range).
1768    if (trimmedDefs.count(Start))
1769      Start = Start.getPrevIndex();
1770
1771    LLVM_DEBUG(auto &dbg = dbgs(); dbg << "\t[" << Start << ';' << Stop << "):";
1772               DbgValue.printLocNos(dbg));
1773    MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
1774    SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
1775
1776    LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1777    insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs, LocSpillOffsets,
1778                     LIS, TII, TRI, BBSkipInstsMap);
1779    // This interval may span multiple basic blocks.
1780    // Insert a DBG_VALUE into each one.
1781    while (Stop > MBBEnd) {
1782      // Move to the next block.
1783      Start = MBBEnd;
1784      if (++MBB == MFEnd)
1785        break;
1786      MBBEnd = LIS.getMBBEndIdx(&*MBB);
1787      LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1788      insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs,
1789                       LocSpillOffsets, LIS, TII, TRI, BBSkipInstsMap);
1790    }
1791    LLVM_DEBUG(dbgs() << '\n');
1792    if (MBB == MFEnd)
1793      break;
1794
1795    ++I;
1796  }
1797}
1798
1799void UserLabel::emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
1800                               BlockSkipInstsMap &BBSkipInstsMap) {
1801  LLVM_DEBUG(dbgs() << "\t" << loc);
1802  MachineFunction::iterator MBB = LIS.getMBBFromIndex(loc)->getIterator();
1803
1804  LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB));
1805  insertDebugLabel(&*MBB, loc, LIS, TII, BBSkipInstsMap);
1806
1807  LLVM_DEBUG(dbgs() << '\n');
1808}
1809
1810void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
1811  LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
1812  if (!MF)
1813    return;
1814
1815  BlockSkipInstsMap BBSkipInstsMap;
1816  const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1817  SpillOffsetMap SpillOffsets;
1818  for (auto &userValue : userValues) {
1819    LLVM_DEBUG(userValue->print(dbgs(), TRI));
1820    userValue->rewriteLocations(*VRM, *MF, *TII, *TRI, SpillOffsets);
1821    userValue->emitDebugValues(VRM, *LIS, *TII, *TRI, SpillOffsets,
1822                               BBSkipInstsMap);
1823  }
1824  LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG LABELS **********\n");
1825  for (auto &userLabel : userLabels) {
1826    LLVM_DEBUG(userLabel->print(dbgs(), TRI));
1827    userLabel->emitDebugLabel(*LIS, *TII, BBSkipInstsMap);
1828  }
1829
1830  LLVM_DEBUG(dbgs() << "********** EMITTING DEBUG PHIS **********\n");
1831
1832  auto Slots = LIS->getSlotIndexes();
1833  for (auto &It : PHIValToPos) {
1834    // For each ex-PHI, identify its physreg location or stack slot, and emit
1835    // a DBG_PHI for it.
1836    unsigned InstNum = It.first;
1837    auto Slot = It.second.SI;
1838    Register Reg = It.second.Reg;
1839    unsigned SubReg = It.second.SubReg;
1840
1841    MachineBasicBlock *OrigMBB = Slots->getMBBFromIndex(Slot);
1842    if (VRM->isAssignedReg(Reg) &&
1843        Register::isPhysicalRegister(VRM->getPhys(Reg))) {
1844      unsigned PhysReg = VRM->getPhys(Reg);
1845      if (SubReg != 0)
1846        PhysReg = TRI->getSubReg(PhysReg, SubReg);
1847
1848      auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(),
1849                             TII->get(TargetOpcode::DBG_PHI));
1850      Builder.addReg(PhysReg);
1851      Builder.addImm(InstNum);
1852    } else if (VRM->getStackSlot(Reg) != VirtRegMap::NO_STACK_SLOT) {
1853      const MachineRegisterInfo &MRI = MF->getRegInfo();
1854      const TargetRegisterClass *TRC = MRI.getRegClass(Reg);
1855      unsigned SpillSize, SpillOffset;
1856
1857      unsigned regSizeInBits = TRI->getRegSizeInBits(*TRC);
1858      if (SubReg)
1859        regSizeInBits = TRI->getSubRegIdxSize(SubReg);
1860
1861      // Test whether this location is legal with the given subreg. If the
1862      // subregister has a nonzero offset, drop this location, it's too complex
1863      // to describe. (TODO: future work).
1864      bool Success =
1865          TII->getStackSlotRange(TRC, SubReg, SpillSize, SpillOffset, *MF);
1866
1867      if (Success && SpillOffset == 0) {
1868        auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(),
1869                               TII->get(TargetOpcode::DBG_PHI));
1870        Builder.addFrameIndex(VRM->getStackSlot(Reg));
1871        Builder.addImm(InstNum);
1872        // Record how large the original value is. The stack slot might be
1873        // merged and altered during optimisation, but we will want to know how
1874        // large the value is, at this DBG_PHI.
1875        Builder.addImm(regSizeInBits);
1876      }
1877
1878      LLVM_DEBUG(
1879      if (SpillOffset != 0) {
1880        dbgs() << "DBG_PHI for Vreg " << Reg << " subreg " << SubReg <<
1881                  " has nonzero offset\n";
1882      }
1883      );
1884    }
1885    // If there was no mapping for a value ID, it's optimized out. Create no
1886    // DBG_PHI, and any variables using this value will become optimized out.
1887  }
1888  MF->DebugPHIPositions.clear();
1889
1890  LLVM_DEBUG(dbgs() << "********** EMITTING INSTR REFERENCES **********\n");
1891
1892  // Re-insert any debug instrs back in the position they were. We must
1893  // re-insert in the same order to ensure that debug instructions don't swap,
1894  // which could re-order assignments. Do so in a batch -- once we find the
1895  // insert position, insert all instructions at the same SlotIdx. They are
1896  // guaranteed to appear in-sequence in StashedDebugInstrs because we insert
1897  // them in order.
1898  for (auto *StashIt = StashedDebugInstrs.begin();
1899       StashIt != StashedDebugInstrs.end(); ++StashIt) {
1900    SlotIndex Idx = StashIt->Idx;
1901    MachineBasicBlock *MBB = StashIt->MBB;
1902    MachineInstr *MI = StashIt->MI;
1903
1904    auto EmitInstsHere = [this, &StashIt, MBB, Idx,
1905                          MI](MachineBasicBlock::iterator InsertPos) {
1906      // Insert this debug instruction.
1907      MBB->insert(InsertPos, MI);
1908
1909      // Look at subsequent stashed debug instructions: if they're at the same
1910      // index, insert those too.
1911      auto NextItem = std::next(StashIt);
1912      while (NextItem != StashedDebugInstrs.end() && NextItem->Idx == Idx) {
1913        assert(NextItem->MBB == MBB && "Instrs with same slot index should be"
1914               "in the same block");
1915        MBB->insert(InsertPos, NextItem->MI);
1916        StashIt = NextItem;
1917        NextItem = std::next(StashIt);
1918      };
1919    };
1920
1921    // Start block index: find the first non-debug instr in the block, and
1922    // insert before it.
1923    if (Idx == Slots->getMBBStartIdx(MBB)) {
1924      MachineBasicBlock::iterator InsertPos =
1925          findInsertLocation(MBB, Idx, *LIS, BBSkipInstsMap);
1926      EmitInstsHere(InsertPos);
1927      continue;
1928    }
1929
1930    if (MachineInstr *Pos = Slots->getInstructionFromIndex(Idx)) {
1931      // Insert at the end of any debug instructions.
1932      auto PostDebug = std::next(Pos->getIterator());
1933      PostDebug = skipDebugInstructionsForward(PostDebug, MBB->instr_end());
1934      EmitInstsHere(PostDebug);
1935    } else {
1936      // Insert position disappeared; walk forwards through slots until we
1937      // find a new one.
1938      SlotIndex End = Slots->getMBBEndIdx(MBB);
1939      for (; Idx < End; Idx = Slots->getNextNonNullIndex(Idx)) {
1940        Pos = Slots->getInstructionFromIndex(Idx);
1941        if (Pos) {
1942          EmitInstsHere(Pos->getIterator());
1943          break;
1944        }
1945      }
1946
1947      // We have reached the end of the block and didn't find anywhere to
1948      // insert! It's not safe to discard any debug instructions; place them
1949      // in front of the first terminator, or in front of end().
1950      if (Idx >= End) {
1951        auto TermIt = MBB->getFirstTerminator();
1952        EmitInstsHere(TermIt);
1953      }
1954    }
1955  }
1956
1957  EmitDone = true;
1958  BBSkipInstsMap.clear();
1959}
1960
1961void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
1962  if (pImpl)
1963    static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
1964}
1965
1966#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1967LLVM_DUMP_METHOD void LiveDebugVariables::dump() const {
1968  if (pImpl)
1969    static_cast<LDVImpl*>(pImpl)->print(dbgs());
1970}
1971#endif
1972