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