xref: /llvm-project/llvm/lib/CodeGen/LiveDebugVariables.cpp (revision 35e0ab647bfcb904057ce97f3c449e7e4845f672)
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/CodeGen/LexicalScopes.h"
32 #include "llvm/CodeGen/LiveInterval.h"
33 #include "llvm/CodeGen/LiveIntervals.h"
34 #include "llvm/CodeGen/MachineBasicBlock.h"
35 #include "llvm/CodeGen/MachineDominators.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineInstr.h"
38 #include "llvm/CodeGen/MachineInstrBuilder.h"
39 #include "llvm/CodeGen/MachineOperand.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/SlotIndexes.h"
42 #include "llvm/CodeGen/TargetInstrInfo.h"
43 #include "llvm/CodeGen/TargetOpcodes.h"
44 #include "llvm/CodeGen/TargetRegisterInfo.h"
45 #include "llvm/CodeGen/TargetSubtargetInfo.h"
46 #include "llvm/CodeGen/VirtRegMap.h"
47 #include "llvm/Config/llvm-config.h"
48 #include "llvm/IR/DebugInfoMetadata.h"
49 #include "llvm/IR/DebugLoc.h"
50 #include "llvm/IR/Function.h"
51 #include "llvm/IR/Metadata.h"
52 #include "llvm/InitializePasses.h"
53 #include "llvm/MC/MCRegisterInfo.h"
54 #include "llvm/Pass.h"
55 #include "llvm/Support/Casting.h"
56 #include "llvm/Support/CommandLine.h"
57 #include "llvm/Support/Compiler.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include <algorithm>
61 #include <cassert>
62 #include <iterator>
63 #include <memory>
64 #include <utility>
65 
66 using namespace llvm;
67 
68 #define DEBUG_TYPE "livedebugvars"
69 
70 static cl::opt<bool>
71 EnableLDV("live-debug-variables", cl::init(true),
72           cl::desc("Enable the live debug variables pass"), cl::Hidden);
73 
74 STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
75 STATISTIC(NumInsertedDebugLabels, "Number of DBG_LABELs inserted");
76 
77 char LiveDebugVariables::ID = 0;
78 
79 INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE,
80                 "Debug Variable Analysis", false, false)
81 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
82 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
83 INITIALIZE_PASS_END(LiveDebugVariables, DEBUG_TYPE,
84                 "Debug Variable Analysis", false, false)
85 
86 void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
87   AU.addRequired<MachineDominatorTree>();
88   AU.addRequiredTransitive<LiveIntervals>();
89   AU.setPreservesAll();
90   MachineFunctionPass::getAnalysisUsage(AU);
91 }
92 
93 LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID) {
94   initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
95 }
96 
97 enum : unsigned { UndefLocNo = ~0U };
98 
99 /// Describes a debug variable value by location number and expression along
100 /// with some flags about the original usage of the location.
101 class DbgVariableValue {
102 public:
103   DbgVariableValue(unsigned LocNo, bool WasIndirect,
104                    const DIExpression &Expression)
105       : LocNo(LocNo), WasIndirect(WasIndirect), Expression(&Expression) {
106     assert(getLocNo() == LocNo && "location truncation");
107   }
108 
109   DbgVariableValue() : LocNo(0), WasIndirect(0) {}
110 
111   const DIExpression *getExpression() const { return Expression; }
112   unsigned getLocNo() const {
113     // Fix up the undef location number, which gets truncated.
114     return LocNo == INT_MAX ? UndefLocNo : LocNo;
115   }
116   bool getWasIndirect() const { return WasIndirect; }
117   bool isUndef() const { return getLocNo() == UndefLocNo; }
118 
119   DbgVariableValue changeLocNo(unsigned NewLocNo) const {
120     return DbgVariableValue(NewLocNo, WasIndirect, *Expression);
121   }
122 
123   friend inline bool operator==(const DbgVariableValue &LHS,
124                                 const DbgVariableValue &RHS) {
125     return LHS.LocNo == RHS.LocNo && LHS.WasIndirect == RHS.WasIndirect &&
126            LHS.Expression == RHS.Expression;
127   }
128 
129   friend inline bool operator!=(const DbgVariableValue &LHS,
130                                 const DbgVariableValue &RHS) {
131     return !(LHS == RHS);
132   }
133 
134 private:
135   unsigned LocNo : 31;
136   unsigned WasIndirect : 1;
137   const DIExpression *Expression = nullptr;
138 };
139 
140 /// Map of where a user value is live to that value.
141 using LocMap = IntervalMap<SlotIndex, DbgVariableValue, 4>;
142 
143 /// Map of stack slot offsets for spilled locations.
144 /// Non-spilled locations are not added to the map.
145 using SpillOffsetMap = DenseMap<unsigned, unsigned>;
146 
147 namespace {
148 
149 class LDVImpl;
150 
151 /// A user value is a part of a debug info user variable.
152 ///
153 /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
154 /// holds part of a user variable. The part is identified by a byte offset.
155 ///
156 /// UserValues are grouped into equivalence classes for easier searching. Two
157 /// user values are related if they refer to the same variable, or if they are
158 /// held by the same virtual register. The equivalence class is the transitive
159 /// closure of that relation.
160 class UserValue {
161   const DILocalVariable *Variable; ///< The debug info variable we are part of.
162   /// The part of the variable we describe.
163   const Optional<DIExpression::FragmentInfo> Fragment;
164   DebugLoc dl;            ///< The debug location for the variable. This is
165                           ///< used by dwarf writer to find lexical scope.
166   UserValue *leader;      ///< Equivalence class leader.
167   UserValue *next = nullptr; ///< Next value in equivalence class, or null.
168 
169   /// Numbered locations referenced by locmap.
170   SmallVector<MachineOperand, 4> locations;
171 
172   /// Map of slot indices where this value is live.
173   LocMap locInts;
174 
175   /// Set of interval start indexes that have been trimmed to the
176   /// lexical scope.
177   SmallSet<SlotIndex, 2> trimmedDefs;
178 
179   /// Insert a DBG_VALUE into MBB at Idx for DbgValue.
180   void insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
181                         SlotIndex StopIdx, DbgVariableValue DbgValue,
182                         bool Spilled, unsigned SpillOffset, LiveIntervals &LIS,
183                         const TargetInstrInfo &TII,
184                         const TargetRegisterInfo &TRI);
185 
186   /// Replace OldLocNo ranges with NewRegs ranges where NewRegs
187   /// is live. Returns true if any changes were made.
188   bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
189                      LiveIntervals &LIS);
190 
191 public:
192   /// Create a new UserValue.
193   UserValue(const DILocalVariable *var,
194             Optional<DIExpression::FragmentInfo> Fragment, DebugLoc L,
195             LocMap::Allocator &alloc)
196       : Variable(var), Fragment(Fragment), dl(std::move(L)), leader(this),
197         locInts(alloc) {}
198 
199   /// Get the leader of this value's equivalence class.
200   UserValue *getLeader() {
201     UserValue *l = leader;
202     while (l != l->leader)
203       l = l->leader;
204     return leader = l;
205   }
206 
207   /// Return the next UserValue in the equivalence class.
208   UserValue *getNext() const { return next; }
209 
210   /// Does this UserValue match the parameters?
211   bool matches(const DILocalVariable *Var,
212              Optional<DIExpression::FragmentInfo> OtherFragment,
213              const DILocation *IA) const {
214     // FIXME: Handle partially overlapping fragments.
215     // A DBG_VALUE with a fragment which overlaps a previous DBG_VALUE fragment
216     // for the same variable terminates the interval opened by the first.
217     // getUserValue() uses matches() to filter DBG_VALUEs into interval maps to
218     // represent these intervals.
219     // Given two _partially_ overlapping fragments matches() will always return
220     // false. The DBG_VALUEs will be filtered into separate interval maps and
221     // therefore we do not faithfully represent the original intervals.
222     // See D70121#1849741 for a more detailed explanation and further
223     // discussion.
224     return Var == Variable && OtherFragment == Fragment &&
225            dl->getInlinedAt() == IA;
226   }
227 
228   /// Merge equivalence classes.
229   static UserValue *merge(UserValue *L1, UserValue *L2) {
230     L2 = L2->getLeader();
231     if (!L1)
232       return L2;
233     L1 = L1->getLeader();
234     if (L1 == L2)
235       return L1;
236     // Splice L2 before L1's members.
237     UserValue *End = L2;
238     while (End->next) {
239       End->leader = L1;
240       End = End->next;
241     }
242     End->leader = L1;
243     End->next = L1->next;
244     L1->next = L2;
245     return L1;
246   }
247 
248   /// Return the location number that matches Loc.
249   ///
250   /// For undef values we always return location number UndefLocNo without
251   /// inserting anything in locations. Since locations is a vector and the
252   /// location number is the position in the vector and UndefLocNo is ~0,
253   /// we would need a very big vector to put the value at the right position.
254   unsigned getLocationNo(const MachineOperand &LocMO) {
255     if (LocMO.isReg()) {
256       if (LocMO.getReg() == 0)
257         return UndefLocNo;
258       // For register locations we dont care about use/def and other flags.
259       for (unsigned i = 0, e = locations.size(); i != e; ++i)
260         if (locations[i].isReg() &&
261             locations[i].getReg() == LocMO.getReg() &&
262             locations[i].getSubReg() == LocMO.getSubReg())
263           return i;
264     } else
265       for (unsigned i = 0, e = locations.size(); i != e; ++i)
266         if (LocMO.isIdenticalTo(locations[i]))
267           return i;
268     locations.push_back(LocMO);
269     // We are storing a MachineOperand outside a MachineInstr.
270     locations.back().clearParent();
271     // Don't store def operands.
272     if (locations.back().isReg()) {
273       if (locations.back().isDef())
274         locations.back().setIsDead(false);
275       locations.back().setIsUse();
276     }
277     return locations.size() - 1;
278   }
279 
280   /// Remove (recycle) a location number. If \p LocNo still is used by the
281   /// locInts nothing is done.
282   void removeLocationIfUnused(unsigned LocNo) {
283     // Bail out if LocNo still is used.
284     for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
285       DbgVariableValue DbgValue = I.value();
286       if (DbgValue.getLocNo() == LocNo)
287         return;
288     }
289     // Remove the entry in the locations vector, and adjust all references to
290     // location numbers above the removed entry.
291     locations.erase(locations.begin() + LocNo);
292     for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
293       DbgVariableValue DbgValue = I.value();
294       if (!DbgValue.isUndef() && DbgValue.getLocNo() > LocNo)
295         I.setValueUnchecked(DbgValue.changeLocNo(DbgValue.getLocNo() - 1));
296     }
297   }
298 
299   /// Ensure that all virtual register locations are mapped.
300   void mapVirtRegs(LDVImpl *LDV);
301 
302   /// Add a definition point to this user value.
303   void addDef(SlotIndex Idx, const MachineOperand &LocMO, bool IsIndirect,
304               const DIExpression &Expr) {
305     DbgVariableValue DbgValue(getLocationNo(LocMO), IsIndirect, Expr);
306     // Add a singular (Idx,Idx) -> value mapping.
307     LocMap::iterator I = locInts.find(Idx);
308     if (!I.valid() || I.start() != Idx)
309       I.insert(Idx, Idx.getNextSlot(), DbgValue);
310     else
311       // A later DBG_VALUE at the same SlotIndex overrides the old location.
312       I.setValue(DbgValue);
313   }
314 
315   /// Extend the current definition as far as possible down.
316   ///
317   /// Stop when meeting an existing def or when leaving the live
318   /// range of VNI. End points where VNI is no longer live are added to Kills.
319   ///
320   /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
321   /// data-flow analysis to propagate them beyond basic block boundaries.
322   ///
323   /// \param Idx Starting point for the definition.
324   /// \param DbgValue value to propagate.
325   /// \param LR Restrict liveness to where LR has the value VNI. May be null.
326   /// \param VNI When LR is not null, this is the value to restrict to.
327   /// \param [out] Kills Append end points of VNI's live range to Kills.
328   /// \param LIS Live intervals analysis.
329   void extendDef(SlotIndex Idx, DbgVariableValue DbgValue, LiveRange *LR,
330                  const VNInfo *VNI, SmallVectorImpl<SlotIndex> *Kills,
331                  LiveIntervals &LIS);
332 
333   /// The value in LI may be copies to other registers. Determine if
334   /// any of the copies are available at the kill points, and add defs if
335   /// possible.
336   ///
337   /// \param LI Scan for copies of the value in LI->reg.
338   /// \param DbgValue Location number of LI->reg, and DIExpression.
339   /// \param Kills Points where the range of DbgValue could be extended.
340   /// \param [in,out] NewDefs Append (Idx, DbgValue) of inserted defs here.
341   void addDefsFromCopies(
342       LiveInterval *LI, DbgVariableValue DbgValue,
343       const SmallVectorImpl<SlotIndex> &Kills,
344       SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
345       MachineRegisterInfo &MRI, LiveIntervals &LIS);
346 
347   /// Compute the live intervals of all locations after collecting all their
348   /// def points.
349   void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
350                         LiveIntervals &LIS, LexicalScopes &LS);
351 
352   /// Replace OldReg ranges with NewRegs ranges where NewRegs is
353   /// live. Returns true if any changes were made.
354   bool splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
355                      LiveIntervals &LIS);
356 
357   /// Rewrite virtual register locations according to the provided virtual
358   /// register map. Record the stack slot offsets for the locations that
359   /// were spilled.
360   void rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
361                         const TargetInstrInfo &TII,
362                         const TargetRegisterInfo &TRI,
363                         SpillOffsetMap &SpillOffsets);
364 
365   /// Recreate DBG_VALUE instruction from data structures.
366   void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
367                        const TargetInstrInfo &TII,
368                        const TargetRegisterInfo &TRI,
369                        const SpillOffsetMap &SpillOffsets);
370 
371   /// Return DebugLoc of this UserValue.
372   DebugLoc getDebugLoc() { return dl;}
373 
374   void print(raw_ostream &, const TargetRegisterInfo *);
375 };
376 
377 /// A user label is a part of a debug info user label.
378 class UserLabel {
379   const DILabel *Label; ///< The debug info label we are part of.
380   DebugLoc dl;          ///< The debug location for the label. This is
381                         ///< used by dwarf writer to find lexical scope.
382   SlotIndex loc;        ///< Slot used by the debug label.
383 
384   /// Insert a DBG_LABEL into MBB at Idx.
385   void insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
386                         LiveIntervals &LIS, const TargetInstrInfo &TII);
387 
388 public:
389   /// Create a new UserLabel.
390   UserLabel(const DILabel *label, DebugLoc L, SlotIndex Idx)
391       : Label(label), dl(std::move(L)), loc(Idx) {}
392 
393   /// Does this UserLabel match the parameters?
394   bool matches(const DILabel *L, const DILocation *IA,
395              const SlotIndex Index) const {
396     return Label == L && dl->getInlinedAt() == IA && loc == Index;
397   }
398 
399   /// Recreate DBG_LABEL instruction from data structures.
400   void emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII);
401 
402   /// Return DebugLoc of this UserLabel.
403   DebugLoc getDebugLoc() { return dl; }
404 
405   void print(raw_ostream &, const TargetRegisterInfo *);
406 };
407 
408 /// Implementation of the LiveDebugVariables pass.
409 class LDVImpl {
410   LiveDebugVariables &pass;
411   LocMap::Allocator allocator;
412   MachineFunction *MF = nullptr;
413   LiveIntervals *LIS;
414   const TargetRegisterInfo *TRI;
415 
416   /// Whether emitDebugValues is called.
417   bool EmitDone = false;
418 
419   /// Whether the machine function is modified during the pass.
420   bool ModifiedMF = false;
421 
422   /// All allocated UserValue instances.
423   SmallVector<std::unique_ptr<UserValue>, 8> userValues;
424 
425   /// All allocated UserLabel instances.
426   SmallVector<std::unique_ptr<UserLabel>, 2> userLabels;
427 
428   /// Map virtual register to eq class leader.
429   using VRMap = DenseMap<unsigned, UserValue *>;
430   VRMap virtRegToEqClass;
431 
432   /// Map user variable to eq class leader.
433   using UVMap = DenseMap<const DILocalVariable *, UserValue *>;
434   UVMap userVarMap;
435 
436   /// Find or create a UserValue.
437   UserValue *getUserValue(const DILocalVariable *Var,
438                           Optional<DIExpression::FragmentInfo> Fragment,
439                           const DebugLoc &DL);
440 
441   /// Find the EC leader for VirtReg or null.
442   UserValue *lookupVirtReg(unsigned VirtReg);
443 
444   /// Add DBG_VALUE instruction to our maps.
445   ///
446   /// \param MI DBG_VALUE instruction
447   /// \param Idx Last valid SLotIndex before instruction.
448   ///
449   /// \returns True if the DBG_VALUE instruction should be deleted.
450   bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
451 
452   /// Add DBG_LABEL instruction to UserLabel.
453   ///
454   /// \param MI DBG_LABEL instruction
455   /// \param Idx Last valid SlotIndex before instruction.
456   ///
457   /// \returns True if the DBG_LABEL instruction should be deleted.
458   bool handleDebugLabel(MachineInstr &MI, SlotIndex Idx);
459 
460   /// Collect and erase all DBG_VALUE instructions, adding a UserValue def
461   /// for each instruction.
462   ///
463   /// \param mf MachineFunction to be scanned.
464   ///
465   /// \returns True if any debug values were found.
466   bool collectDebugValues(MachineFunction &mf);
467 
468   /// Compute the live intervals of all user values after collecting all
469   /// their def points.
470   void computeIntervals();
471 
472 public:
473   LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
474 
475   bool runOnMachineFunction(MachineFunction &mf);
476 
477   /// Release all memory.
478   void clear() {
479     MF = nullptr;
480     userValues.clear();
481     userLabels.clear();
482     virtRegToEqClass.clear();
483     userVarMap.clear();
484     // Make sure we call emitDebugValues if the machine function was modified.
485     assert((!ModifiedMF || EmitDone) &&
486            "Dbg values are not emitted in LDV");
487     EmitDone = false;
488     ModifiedMF = false;
489   }
490 
491   /// Map virtual register to an equivalence class.
492   void mapVirtReg(unsigned VirtReg, UserValue *EC);
493 
494   /// Replace all references to OldReg with NewRegs.
495   void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs);
496 
497   /// Recreate DBG_VALUE instruction from data structures.
498   void emitDebugValues(VirtRegMap *VRM);
499 
500   void print(raw_ostream&);
501 };
502 
503 } // end anonymous namespace
504 
505 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
506 static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
507                           const LLVMContext &Ctx) {
508   if (!DL)
509     return;
510 
511   auto *Scope = cast<DIScope>(DL.getScope());
512   // Omit the directory, because it's likely to be long and uninteresting.
513   CommentOS << Scope->getFilename();
514   CommentOS << ':' << DL.getLine();
515   if (DL.getCol() != 0)
516     CommentOS << ':' << DL.getCol();
517 
518   DebugLoc InlinedAtDL = DL.getInlinedAt();
519   if (!InlinedAtDL)
520     return;
521 
522   CommentOS << " @[ ";
523   printDebugLoc(InlinedAtDL, CommentOS, Ctx);
524   CommentOS << " ]";
525 }
526 
527 static void printExtendedName(raw_ostream &OS, const DINode *Node,
528                               const DILocation *DL) {
529   const LLVMContext &Ctx = Node->getContext();
530   StringRef Res;
531   unsigned Line = 0;
532   if (const auto *V = dyn_cast<const DILocalVariable>(Node)) {
533     Res = V->getName();
534     Line = V->getLine();
535   } else if (const auto *L = dyn_cast<const DILabel>(Node)) {
536     Res = L->getName();
537     Line = L->getLine();
538   }
539 
540   if (!Res.empty())
541     OS << Res << "," << Line;
542   auto *InlinedAt = DL ? DL->getInlinedAt() : nullptr;
543   if (InlinedAt) {
544     if (DebugLoc InlinedAtDL = InlinedAt) {
545       OS << " @[";
546       printDebugLoc(InlinedAtDL, OS, Ctx);
547       OS << "]";
548     }
549   }
550 }
551 
552 void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
553   OS << "!\"";
554   printExtendedName(OS, Variable, dl);
555 
556   OS << "\"\t";
557   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
558     OS << " [" << I.start() << ';' << I.stop() << "):";
559     if (I.value().isUndef())
560       OS << "undef";
561     else {
562       OS << I.value().getLocNo();
563       if (I.value().getWasIndirect())
564         OS << " ind";
565     }
566   }
567   for (unsigned i = 0, e = locations.size(); i != e; ++i) {
568     OS << " Loc" << i << '=';
569     locations[i].print(OS, TRI);
570   }
571   OS << '\n';
572 }
573 
574 void UserLabel::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
575   OS << "!\"";
576   printExtendedName(OS, Label, dl);
577 
578   OS << "\"\t";
579   OS << loc;
580   OS << '\n';
581 }
582 
583 void LDVImpl::print(raw_ostream &OS) {
584   OS << "********** DEBUG VARIABLES **********\n";
585   for (auto &userValue : userValues)
586     userValue->print(OS, TRI);
587   OS << "********** DEBUG LABELS **********\n";
588   for (auto &userLabel : userLabels)
589     userLabel->print(OS, TRI);
590 }
591 #endif
592 
593 void UserValue::mapVirtRegs(LDVImpl *LDV) {
594   for (unsigned i = 0, e = locations.size(); i != e; ++i)
595     if (locations[i].isReg() &&
596         Register::isVirtualRegister(locations[i].getReg()))
597       LDV->mapVirtReg(locations[i].getReg(), this);
598 }
599 
600 UserValue *LDVImpl::getUserValue(const DILocalVariable *Var,
601                                  Optional<DIExpression::FragmentInfo> Fragment,
602                                  const DebugLoc &DL) {
603   UserValue *&Leader = userVarMap[Var];
604   if (Leader) {
605     UserValue *UV = Leader->getLeader();
606     Leader = UV;
607     for (; UV; UV = UV->getNext())
608       if (UV->matches(Var, Fragment, DL->getInlinedAt()))
609         return UV;
610   }
611 
612   userValues.push_back(
613       std::make_unique<UserValue>(Var, Fragment, DL, allocator));
614   UserValue *UV = userValues.back().get();
615   Leader = UserValue::merge(Leader, UV);
616   return UV;
617 }
618 
619 void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
620   assert(Register::isVirtualRegister(VirtReg) && "Only map VirtRegs");
621   UserValue *&Leader = virtRegToEqClass[VirtReg];
622   Leader = UserValue::merge(Leader, EC);
623 }
624 
625 UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
626   if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
627     return UV->getLeader();
628   return nullptr;
629 }
630 
631 bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
632   // DBG_VALUE loc, offset, variable
633   if (MI.getNumOperands() != 4 ||
634       !(MI.getOperand(1).isReg() || MI.getOperand(1).isImm()) ||
635       !MI.getOperand(2).isMetadata()) {
636     LLVM_DEBUG(dbgs() << "Can't handle " << MI);
637     return false;
638   }
639 
640   // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual
641   // register that hasn't been defined yet. If we do not remove those here, then
642   // the re-insertion of the DBG_VALUE instruction after register allocation
643   // will be incorrect.
644   // TODO: If earlier passes are corrected to generate sane debug information
645   // (and if the machine verifier is improved to catch this), then these checks
646   // could be removed or replaced by asserts.
647   bool Discard = false;
648   if (MI.getOperand(0).isReg() &&
649       Register::isVirtualRegister(MI.getOperand(0).getReg())) {
650     const Register Reg = MI.getOperand(0).getReg();
651     if (!LIS->hasInterval(Reg)) {
652       // The DBG_VALUE is described by a virtual register that does not have a
653       // live interval. Discard the DBG_VALUE.
654       Discard = true;
655       LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx
656                         << " " << MI);
657     } else {
658       // The DBG_VALUE is only valid if either Reg is live out from Idx, or Reg
659       // is defined dead at Idx (where Idx is the slot index for the instruction
660       // preceding the DBG_VALUE).
661       const LiveInterval &LI = LIS->getInterval(Reg);
662       LiveQueryResult LRQ = LI.Query(Idx);
663       if (!LRQ.valueOutOrDead()) {
664         // We have found a DBG_VALUE with the value in a virtual register that
665         // is not live. Discard the DBG_VALUE.
666         Discard = true;
667         LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx
668                           << " " << MI);
669       }
670     }
671   }
672 
673   // Get or create the UserValue for (variable,offset) here.
674   bool IsIndirect = MI.getOperand(1).isImm();
675   if (IsIndirect)
676     assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
677   const DILocalVariable *Var = MI.getDebugVariable();
678   const DIExpression *Expr = MI.getDebugExpression();
679   UserValue *UV = getUserValue(Var, Expr->getFragmentInfo(), MI.getDebugLoc());
680   if (!Discard)
681     UV->addDef(Idx, MI.getOperand(0), IsIndirect, *Expr);
682   else {
683     MachineOperand MO = MachineOperand::CreateReg(0U, false);
684     MO.setIsDebug();
685     UV->addDef(Idx, MO, false, *Expr);
686   }
687   return true;
688 }
689 
690 bool LDVImpl::handleDebugLabel(MachineInstr &MI, SlotIndex Idx) {
691   // DBG_LABEL label
692   if (MI.getNumOperands() != 1 || !MI.getOperand(0).isMetadata()) {
693     LLVM_DEBUG(dbgs() << "Can't handle " << MI);
694     return false;
695   }
696 
697   // Get or create the UserLabel for label here.
698   const DILabel *Label = MI.getDebugLabel();
699   const DebugLoc &DL = MI.getDebugLoc();
700   bool Found = false;
701   for (auto const &L : userLabels) {
702     if (L->matches(Label, DL->getInlinedAt(), Idx)) {
703       Found = true;
704       break;
705     }
706   }
707   if (!Found)
708     userLabels.push_back(std::make_unique<UserLabel>(Label, DL, Idx));
709 
710   return true;
711 }
712 
713 bool LDVImpl::collectDebugValues(MachineFunction &mf) {
714   bool Changed = false;
715   for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
716        ++MFI) {
717     MachineBasicBlock *MBB = &*MFI;
718     for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
719          MBBI != MBBE;) {
720       // Use the first debug instruction in the sequence to get a SlotIndex
721       // for following consecutive debug instructions.
722       if (!MBBI->isDebugInstr()) {
723         ++MBBI;
724         continue;
725       }
726       // Debug instructions has no slot index. Use the previous
727       // non-debug instruction's SlotIndex as its SlotIndex.
728       SlotIndex Idx =
729           MBBI == MBB->begin()
730               ? LIS->getMBBStartIdx(MBB)
731               : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
732       // Handle consecutive debug instructions with the same slot index.
733       do {
734         // Only handle DBG_VALUE in handleDebugValue(). Skip all other
735         // kinds of debug instructions.
736         if ((MBBI->isDebugValue() && handleDebugValue(*MBBI, Idx)) ||
737             (MBBI->isDebugLabel() && handleDebugLabel(*MBBI, Idx))) {
738           MBBI = MBB->erase(MBBI);
739           Changed = true;
740         } else
741           ++MBBI;
742       } while (MBBI != MBBE && MBBI->isDebugInstr());
743     }
744   }
745   return Changed;
746 }
747 
748 void UserValue::extendDef(SlotIndex Idx, DbgVariableValue DbgValue, LiveRange *LR,
749                           const VNInfo *VNI, SmallVectorImpl<SlotIndex> *Kills,
750                           LiveIntervals &LIS) {
751   SlotIndex Start = Idx;
752   MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
753   SlotIndex Stop = LIS.getMBBEndIdx(MBB);
754   LocMap::iterator I = locInts.find(Start);
755 
756   // Limit to VNI's live range.
757   bool ToEnd = true;
758   if (LR && VNI) {
759     LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
760     if (!Segment || Segment->valno != VNI) {
761       if (Kills)
762         Kills->push_back(Start);
763       return;
764     }
765     if (Segment->end < Stop) {
766       Stop = Segment->end;
767       ToEnd = false;
768     }
769   }
770 
771   // There could already be a short def at Start.
772   if (I.valid() && I.start() <= Start) {
773     // Stop when meeting a different location or an already extended interval.
774     Start = Start.getNextSlot();
775     if (I.value() != DbgValue || I.stop() != Start)
776       return;
777     // This is a one-slot placeholder. Just skip it.
778     ++I;
779   }
780 
781   // Limited by the next def.
782   if (I.valid() && I.start() < Stop)
783     Stop = I.start();
784   // Limited by VNI's live range.
785   else if (!ToEnd && Kills)
786     Kills->push_back(Stop);
787 
788   if (Start < Stop)
789     I.insert(Start, Stop, DbgValue);
790 }
791 
792 void UserValue::addDefsFromCopies(
793     LiveInterval *LI, DbgVariableValue DbgValue,
794     const SmallVectorImpl<SlotIndex> &Kills,
795     SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
796     MachineRegisterInfo &MRI, LiveIntervals &LIS) {
797   if (Kills.empty())
798     return;
799   // Don't track copies from physregs, there are too many uses.
800   if (!Register::isVirtualRegister(LI->reg))
801     return;
802 
803   // Collect all the (vreg, valno) pairs that are copies of LI.
804   SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
805   for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) {
806     MachineInstr *MI = MO.getParent();
807     // Copies of the full value.
808     if (MO.getSubReg() || !MI->isCopy())
809       continue;
810     Register DstReg = MI->getOperand(0).getReg();
811 
812     // Don't follow copies to physregs. These are usually setting up call
813     // arguments, and the argument registers are always call clobbered. We are
814     // better off in the source register which could be a callee-saved register,
815     // or it could be spilled.
816     if (!Register::isVirtualRegister(DstReg))
817       continue;
818 
819     // Is the value extended to reach this copy? If not, another def may be
820     // blocking it, or we are looking at a wrong value of LI.
821     SlotIndex Idx = LIS.getInstructionIndex(*MI);
822     LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
823     if (!I.valid() || I.value() != DbgValue)
824       continue;
825 
826     if (!LIS.hasInterval(DstReg))
827       continue;
828     LiveInterval *DstLI = &LIS.getInterval(DstReg);
829     const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
830     assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
831     CopyValues.push_back(std::make_pair(DstLI, DstVNI));
832   }
833 
834   if (CopyValues.empty())
835     return;
836 
837   LLVM_DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI
838                     << '\n');
839 
840   // Try to add defs of the copied values for each kill point.
841   for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
842     SlotIndex Idx = Kills[i];
843     for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
844       LiveInterval *DstLI = CopyValues[j].first;
845       const VNInfo *DstVNI = CopyValues[j].second;
846       if (DstLI->getVNInfoAt(Idx) != DstVNI)
847         continue;
848       // Check that there isn't already a def at Idx
849       LocMap::iterator I = locInts.find(Idx);
850       if (I.valid() && I.start() <= Idx)
851         continue;
852       LLVM_DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
853                         << DstVNI->id << " in " << *DstLI << '\n');
854       MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
855       assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
856       unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
857       DbgVariableValue NewValue = DbgValue.changeLocNo(LocNo);
858       I.insert(Idx, Idx.getNextSlot(), NewValue);
859       NewDefs.push_back(std::make_pair(Idx, NewValue));
860       break;
861     }
862   }
863 }
864 
865 void UserValue::computeIntervals(MachineRegisterInfo &MRI,
866                                  const TargetRegisterInfo &TRI,
867                                  LiveIntervals &LIS, LexicalScopes &LS) {
868   SmallVector<std::pair<SlotIndex, DbgVariableValue>, 16> Defs;
869 
870   // Collect all defs to be extended (Skipping undefs).
871   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
872     if (!I.value().isUndef())
873       Defs.push_back(std::make_pair(I.start(), I.value()));
874 
875   // Extend all defs, and possibly add new ones along the way.
876   for (unsigned i = 0; i != Defs.size(); ++i) {
877     SlotIndex Idx = Defs[i].first;
878     DbgVariableValue DbgValue = Defs[i].second;
879     const MachineOperand &LocMO = locations[DbgValue.getLocNo()];
880 
881     if (!LocMO.isReg()) {
882       extendDef(Idx, DbgValue, nullptr, nullptr, nullptr, LIS);
883       continue;
884     }
885 
886     // Register locations are constrained to where the register value is live.
887     if (Register::isVirtualRegister(LocMO.getReg())) {
888       LiveInterval *LI = nullptr;
889       const VNInfo *VNI = nullptr;
890       if (LIS.hasInterval(LocMO.getReg())) {
891         LI = &LIS.getInterval(LocMO.getReg());
892         VNI = LI->getVNInfoAt(Idx);
893       }
894       SmallVector<SlotIndex, 16> Kills;
895       extendDef(Idx, DbgValue, LI, VNI, &Kills, LIS);
896       // FIXME: Handle sub-registers in addDefsFromCopies. The problem is that
897       // if the original location for example is %vreg0:sub_hi, and we find a
898       // full register copy in addDefsFromCopies (at the moment it only handles
899       // full register copies), then we must add the sub1 sub-register index to
900       // the new location. However, that is only possible if the new virtual
901       // register is of the same regclass (or if there is an equivalent
902       // sub-register in that regclass). For now, simply skip handling copies if
903       // a sub-register is involved.
904       if (LI && !LocMO.getSubReg())
905         addDefsFromCopies(LI, DbgValue, Kills, Defs, MRI, LIS);
906       continue;
907     }
908 
909     // For physregs, we only mark the start slot idx. DwarfDebug will see it
910     // as if the DBG_VALUE is valid up until the end of the basic block, or
911     // the next def of the physical register. So we do not need to extend the
912     // range. It might actually happen that the DBG_VALUE is the last use of
913     // the physical register (e.g. if this is an unused input argument to a
914     // function).
915   }
916 
917   // The computed intervals may extend beyond the range of the debug
918   // location's lexical scope. In this case, splitting of an interval
919   // can result in an interval outside of the scope being created,
920   // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
921   // this, trim the intervals to the lexical scope.
922 
923   LexicalScope *Scope = LS.findLexicalScope(dl);
924   if (!Scope)
925     return;
926 
927   SlotIndex PrevEnd;
928   LocMap::iterator I = locInts.begin();
929 
930   // Iterate over the lexical scope ranges. Each time round the loop
931   // we check the intervals for overlap with the end of the previous
932   // range and the start of the next. The first range is handled as
933   // a special case where there is no PrevEnd.
934   for (const InsnRange &Range : Scope->getRanges()) {
935     SlotIndex RStart = LIS.getInstructionIndex(*Range.first);
936     SlotIndex REnd = LIS.getInstructionIndex(*Range.second);
937 
938     // Variable locations at the first instruction of a block should be
939     // based on the block's SlotIndex, not the first instruction's index.
940     if (Range.first == Range.first->getParent()->begin())
941       RStart = LIS.getSlotIndexes()->getIndexBefore(*Range.first);
942 
943     // At the start of each iteration I has been advanced so that
944     // I.stop() >= PrevEnd. Check for overlap.
945     if (PrevEnd && I.start() < PrevEnd) {
946       SlotIndex IStop = I.stop();
947       DbgVariableValue DbgValue = I.value();
948 
949       // Stop overlaps previous end - trim the end of the interval to
950       // the scope range.
951       I.setStopUnchecked(PrevEnd);
952       ++I;
953 
954       // If the interval also overlaps the start of the "next" (i.e.
955       // current) range create a new interval for the remainder (which
956       // may be further trimmed).
957       if (RStart < IStop)
958         I.insert(RStart, IStop, DbgValue);
959     }
960 
961     // Advance I so that I.stop() >= RStart, and check for overlap.
962     I.advanceTo(RStart);
963     if (!I.valid())
964       return;
965 
966     if (I.start() < RStart) {
967       // Interval start overlaps range - trim to the scope range.
968       I.setStartUnchecked(RStart);
969       // Remember that this interval was trimmed.
970       trimmedDefs.insert(RStart);
971     }
972 
973     // The end of a lexical scope range is the last instruction in the
974     // range. To convert to an interval we need the index of the
975     // instruction after it.
976     REnd = REnd.getNextIndex();
977 
978     // Advance I to first interval outside current range.
979     I.advanceTo(REnd);
980     if (!I.valid())
981       return;
982 
983     PrevEnd = REnd;
984   }
985 
986   // Check for overlap with end of final range.
987   if (PrevEnd && I.start() < PrevEnd)
988     I.setStopUnchecked(PrevEnd);
989 }
990 
991 void LDVImpl::computeIntervals() {
992   LexicalScopes LS;
993   LS.initialize(*MF);
994 
995   for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
996     userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS);
997     userValues[i]->mapVirtRegs(this);
998   }
999 }
1000 
1001 bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
1002   clear();
1003   MF = &mf;
1004   LIS = &pass.getAnalysis<LiveIntervals>();
1005   TRI = mf.getSubtarget().getRegisterInfo();
1006   LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
1007                     << mf.getName() << " **********\n");
1008 
1009   bool Changed = collectDebugValues(mf);
1010   computeIntervals();
1011   LLVM_DEBUG(print(dbgs()));
1012   ModifiedMF = Changed;
1013   return Changed;
1014 }
1015 
1016 static void removeDebugValues(MachineFunction &mf) {
1017   for (MachineBasicBlock &MBB : mf) {
1018     for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) {
1019       if (!MBBI->isDebugValue()) {
1020         ++MBBI;
1021         continue;
1022       }
1023       MBBI = MBB.erase(MBBI);
1024     }
1025   }
1026 }
1027 
1028 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
1029   if (!EnableLDV)
1030     return false;
1031   if (!mf.getFunction().getSubprogram()) {
1032     removeDebugValues(mf);
1033     return false;
1034   }
1035   if (!pImpl)
1036     pImpl = new LDVImpl(this);
1037   return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
1038 }
1039 
1040 void LiveDebugVariables::releaseMemory() {
1041   if (pImpl)
1042     static_cast<LDVImpl*>(pImpl)->clear();
1043 }
1044 
1045 LiveDebugVariables::~LiveDebugVariables() {
1046   if (pImpl)
1047     delete static_cast<LDVImpl*>(pImpl);
1048 }
1049 
1050 //===----------------------------------------------------------------------===//
1051 //                           Live Range Splitting
1052 //===----------------------------------------------------------------------===//
1053 
1054 bool
1055 UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
1056                          LiveIntervals& LIS) {
1057   LLVM_DEBUG({
1058     dbgs() << "Splitting Loc" << OldLocNo << '\t';
1059     print(dbgs(), nullptr);
1060   });
1061   bool DidChange = false;
1062   LocMap::iterator LocMapI;
1063   LocMapI.setMap(locInts);
1064   for (unsigned i = 0; i != NewRegs.size(); ++i) {
1065     LiveInterval *LI = &LIS.getInterval(NewRegs[i]);
1066     if (LI->empty())
1067       continue;
1068 
1069     // Don't allocate the new LocNo until it is needed.
1070     unsigned NewLocNo = UndefLocNo;
1071 
1072     // Iterate over the overlaps between locInts and LI.
1073     LocMapI.find(LI->beginIndex());
1074     if (!LocMapI.valid())
1075       continue;
1076     LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
1077     LiveInterval::iterator LIE = LI->end();
1078     while (LocMapI.valid() && LII != LIE) {
1079       // At this point, we know that LocMapI.stop() > LII->start.
1080       LII = LI->advanceTo(LII, LocMapI.start());
1081       if (LII == LIE)
1082         break;
1083 
1084       // Now LII->end > LocMapI.start(). Do we have an overlap?
1085       if (LocMapI.value().getLocNo() == OldLocNo &&
1086           LII->start < LocMapI.stop()) {
1087         // Overlapping correct location. Allocate NewLocNo now.
1088         if (NewLocNo == UndefLocNo) {
1089           MachineOperand MO = MachineOperand::CreateReg(LI->reg, false);
1090           MO.setSubReg(locations[OldLocNo].getSubReg());
1091           NewLocNo = getLocationNo(MO);
1092           DidChange = true;
1093         }
1094 
1095         SlotIndex LStart = LocMapI.start();
1096         SlotIndex LStop = LocMapI.stop();
1097         DbgVariableValue OldDbgValue = LocMapI.value();
1098 
1099         // Trim LocMapI down to the LII overlap.
1100         if (LStart < LII->start)
1101           LocMapI.setStartUnchecked(LII->start);
1102         if (LStop > LII->end)
1103           LocMapI.setStopUnchecked(LII->end);
1104 
1105         // Change the value in the overlap. This may trigger coalescing.
1106         LocMapI.setValue(OldDbgValue.changeLocNo(NewLocNo));
1107 
1108         // Re-insert any removed OldDbgValue ranges.
1109         if (LStart < LocMapI.start()) {
1110           LocMapI.insert(LStart, LocMapI.start(), OldDbgValue);
1111           ++LocMapI;
1112           assert(LocMapI.valid() && "Unexpected coalescing");
1113         }
1114         if (LStop > LocMapI.stop()) {
1115           ++LocMapI;
1116           LocMapI.insert(LII->end, LStop, OldDbgValue);
1117           --LocMapI;
1118         }
1119       }
1120 
1121       // Advance to the next overlap.
1122       if (LII->end < LocMapI.stop()) {
1123         if (++LII == LIE)
1124           break;
1125         LocMapI.advanceTo(LII->start);
1126       } else {
1127         ++LocMapI;
1128         if (!LocMapI.valid())
1129           break;
1130         LII = LI->advanceTo(LII, LocMapI.start());
1131       }
1132     }
1133   }
1134 
1135   // Finally, remove OldLocNo unless it is still used by some interval in the
1136   // locInts map. One case when OldLocNo still is in use is when the register
1137   // has been spilled. In such situations the spilled register is kept as a
1138   // location until rewriteLocations is called (VirtRegMap is mapping the old
1139   // register to the spill slot). So for a while we can have locations that map
1140   // to virtual registers that have been removed from both the MachineFunction
1141   // and from LiveIntervals.
1142   //
1143   // We may also just be using the location for a value with a different
1144   // expression.
1145   removeLocationIfUnused(OldLocNo);
1146 
1147   LLVM_DEBUG({
1148     dbgs() << "Split result: \t";
1149     print(dbgs(), nullptr);
1150   });
1151   return DidChange;
1152 }
1153 
1154 bool
1155 UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
1156                          LiveIntervals &LIS) {
1157   bool DidChange = false;
1158   // Split locations referring to OldReg. Iterate backwards so splitLocation can
1159   // safely erase unused locations.
1160   for (unsigned i = locations.size(); i ; --i) {
1161     unsigned LocNo = i-1;
1162     const MachineOperand *Loc = &locations[LocNo];
1163     if (!Loc->isReg() || Loc->getReg() != OldReg)
1164       continue;
1165     DidChange |= splitLocation(LocNo, NewRegs, LIS);
1166   }
1167   return DidChange;
1168 }
1169 
1170 void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) {
1171   bool DidChange = false;
1172   for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
1173     DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
1174 
1175   if (!DidChange)
1176     return;
1177 
1178   // Map all of the new virtual registers.
1179   UserValue *UV = lookupVirtReg(OldReg);
1180   for (unsigned i = 0; i != NewRegs.size(); ++i)
1181     mapVirtReg(NewRegs[i], UV);
1182 }
1183 
1184 void LiveDebugVariables::
1185 splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) {
1186   if (pImpl)
1187     static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
1188 }
1189 
1190 void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
1191                                  const TargetInstrInfo &TII,
1192                                  const TargetRegisterInfo &TRI,
1193                                  SpillOffsetMap &SpillOffsets) {
1194   // Build a set of new locations with new numbers so we can coalesce our
1195   // IntervalMap if two vreg intervals collapse to the same physical location.
1196   // Use MapVector instead of SetVector because MapVector::insert returns the
1197   // position of the previously or newly inserted element. The boolean value
1198   // tracks if the location was produced by a spill.
1199   // FIXME: This will be problematic if we ever support direct and indirect
1200   // frame index locations, i.e. expressing both variables in memory and
1201   // 'int x, *px = &x'. The "spilled" bit must become part of the location.
1202   MapVector<MachineOperand, std::pair<bool, unsigned>> NewLocations;
1203   SmallVector<unsigned, 4> LocNoMap(locations.size());
1204   for (unsigned I = 0, E = locations.size(); I != E; ++I) {
1205     bool Spilled = false;
1206     unsigned SpillOffset = 0;
1207     MachineOperand Loc = locations[I];
1208     // Only virtual registers are rewritten.
1209     if (Loc.isReg() && Loc.getReg() &&
1210         Register::isVirtualRegister(Loc.getReg())) {
1211       Register VirtReg = Loc.getReg();
1212       if (VRM.isAssignedReg(VirtReg) &&
1213           Register::isPhysicalRegister(VRM.getPhys(VirtReg))) {
1214         // This can create a %noreg operand in rare cases when the sub-register
1215         // index is no longer available. That means the user value is in a
1216         // non-existent sub-register, and %noreg is exactly what we want.
1217         Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
1218       } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
1219         // Retrieve the stack slot offset.
1220         unsigned SpillSize;
1221         const MachineRegisterInfo &MRI = MF.getRegInfo();
1222         const TargetRegisterClass *TRC = MRI.getRegClass(VirtReg);
1223         bool Success = TII.getStackSlotRange(TRC, Loc.getSubReg(), SpillSize,
1224                                              SpillOffset, MF);
1225 
1226         // FIXME: Invalidate the location if the offset couldn't be calculated.
1227         (void)Success;
1228 
1229         Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
1230         Spilled = true;
1231       } else {
1232         Loc.setReg(0);
1233         Loc.setSubReg(0);
1234       }
1235     }
1236 
1237     // Insert this location if it doesn't already exist and record a mapping
1238     // from the old number to the new number.
1239     auto InsertResult = NewLocations.insert({Loc, {Spilled, SpillOffset}});
1240     unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first);
1241     LocNoMap[I] = NewLocNo;
1242   }
1243 
1244   // Rewrite the locations and record the stack slot offsets for spills.
1245   locations.clear();
1246   SpillOffsets.clear();
1247   for (auto &Pair : NewLocations) {
1248     bool Spilled;
1249     unsigned SpillOffset;
1250     std::tie(Spilled, SpillOffset) = Pair.second;
1251     locations.push_back(Pair.first);
1252     if (Spilled) {
1253       unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair);
1254       SpillOffsets[NewLocNo] = SpillOffset;
1255     }
1256   }
1257 
1258   // Update the interval map, but only coalesce left, since intervals to the
1259   // right use the old location numbers. This should merge two contiguous
1260   // DBG_VALUE intervals with different vregs that were allocated to the same
1261   // physical register.
1262   for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
1263     DbgVariableValue DbgValue = I.value();
1264     // Undef values don't exist in locations (and thus not in LocNoMap either)
1265     // so skip over them. See getLocationNo().
1266     if (DbgValue.isUndef())
1267       continue;
1268     unsigned NewLocNo = LocNoMap[DbgValue.getLocNo()];
1269     I.setValueUnchecked(DbgValue.changeLocNo(NewLocNo));
1270     I.setStart(I.start());
1271   }
1272 }
1273 
1274 /// Find an iterator for inserting a DBG_VALUE instruction.
1275 static MachineBasicBlock::iterator
1276 findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
1277                    LiveIntervals &LIS) {
1278   SlotIndex Start = LIS.getMBBStartIdx(MBB);
1279   Idx = Idx.getBaseIndex();
1280 
1281   // Try to find an insert location by going backwards from Idx.
1282   MachineInstr *MI;
1283   while (!(MI = LIS.getInstructionFromIndex(Idx))) {
1284     // We've reached the beginning of MBB.
1285     if (Idx == Start) {
1286       MachineBasicBlock::iterator I = MBB->SkipPHIsLabelsAndDebug(MBB->begin());
1287       return I;
1288     }
1289     Idx = Idx.getPrevIndex();
1290   }
1291 
1292   // Don't insert anything after the first terminator, though.
1293   return MI->isTerminator() ? MBB->getFirstTerminator() :
1294                               std::next(MachineBasicBlock::iterator(MI));
1295 }
1296 
1297 /// Find an iterator for inserting the next DBG_VALUE instruction
1298 /// (or end if no more insert locations found).
1299 static MachineBasicBlock::iterator
1300 findNextInsertLocation(MachineBasicBlock *MBB,
1301                        MachineBasicBlock::iterator I,
1302                        SlotIndex StopIdx, MachineOperand &LocMO,
1303                        LiveIntervals &LIS,
1304                        const TargetRegisterInfo &TRI) {
1305   if (!LocMO.isReg())
1306     return MBB->instr_end();
1307   Register Reg = LocMO.getReg();
1308 
1309   // Find the next instruction in the MBB that define the register Reg.
1310   while (I != MBB->end() && !I->isTerminator()) {
1311     if (!LIS.isNotInMIMap(*I) &&
1312         SlotIndex::isEarlierEqualInstr(StopIdx, LIS.getInstructionIndex(*I)))
1313       break;
1314     if (I->definesRegister(Reg, &TRI))
1315       // The insert location is directly after the instruction/bundle.
1316       return std::next(I);
1317     ++I;
1318   }
1319   return MBB->end();
1320 }
1321 
1322 void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
1323                                  SlotIndex StopIdx, DbgVariableValue DbgValue,
1324                                  bool Spilled, unsigned SpillOffset,
1325                                  LiveIntervals &LIS, const TargetInstrInfo &TII,
1326                                  const TargetRegisterInfo &TRI) {
1327   SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB);
1328   // Only search within the current MBB.
1329   StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx;
1330   MachineBasicBlock::iterator I = findInsertLocation(MBB, StartIdx, LIS);
1331   // Undef values don't exist in locations so create new "noreg" register MOs
1332   // for them. See getLocationNo().
1333   MachineOperand MO =
1334       !DbgValue.isUndef()
1335           ? locations[DbgValue.getLocNo()]
1336           : MachineOperand::CreateReg(
1337                 /* Reg */ 0, /* isDef */ false, /* isImp */ false,
1338                 /* isKill */ false, /* isDead */ false,
1339                 /* isUndef */ false, /* isEarlyClobber */ false,
1340                 /* SubReg */ 0, /* isDebug */ true);
1341 
1342   ++NumInsertedDebugValues;
1343 
1344   assert(cast<DILocalVariable>(Variable)
1345              ->isValidLocationForIntrinsic(getDebugLoc()) &&
1346          "Expected inlined-at fields to agree");
1347 
1348   // If the location was spilled, the new DBG_VALUE will be indirect. If the
1349   // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
1350   // that the original virtual register was a pointer. Also, add the stack slot
1351   // offset for the spilled register to the expression.
1352   const DIExpression *Expr = DbgValue.getExpression();
1353   uint8_t DIExprFlags = DIExpression::ApplyOffset;
1354   bool IsIndirect = DbgValue.getWasIndirect();
1355   if (Spilled) {
1356     if (IsIndirect)
1357       DIExprFlags |= DIExpression::DerefAfter;
1358     Expr =
1359         DIExpression::prepend(Expr, DIExprFlags, SpillOffset);
1360     IsIndirect = true;
1361   }
1362 
1363   assert((!Spilled || MO.isFI()) && "a spilled location must be a frame index");
1364 
1365   do {
1366     BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE),
1367             IsIndirect, MO, Variable, Expr);
1368 
1369     // Continue and insert DBG_VALUES after every redefinition of register
1370     // associated with the debug value within the range
1371     I = findNextInsertLocation(MBB, I, StopIdx, MO, LIS, TRI);
1372   } while (I != MBB->end());
1373 }
1374 
1375 void UserLabel::insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
1376                                  LiveIntervals &LIS,
1377                                  const TargetInstrInfo &TII) {
1378   MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS);
1379   ++NumInsertedDebugLabels;
1380   BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_LABEL))
1381       .addMetadata(Label);
1382 }
1383 
1384 void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
1385                                 const TargetInstrInfo &TII,
1386                                 const TargetRegisterInfo &TRI,
1387                                 const SpillOffsetMap &SpillOffsets) {
1388   MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
1389 
1390   for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
1391     SlotIndex Start = I.start();
1392     SlotIndex Stop = I.stop();
1393     DbgVariableValue DbgValue = I.value();
1394     auto SpillIt = !DbgValue.isUndef() ? SpillOffsets.find(DbgValue.getLocNo())
1395                                        : SpillOffsets.end();
1396     bool Spilled = SpillIt != SpillOffsets.end();
1397     unsigned SpillOffset = Spilled ? SpillIt->second : 0;
1398 
1399     // If the interval start was trimmed to the lexical scope insert the
1400     // DBG_VALUE at the previous index (otherwise it appears after the
1401     // first instruction in the range).
1402     if (trimmedDefs.count(Start))
1403       Start = Start.getPrevIndex();
1404 
1405     LLVM_DEBUG(dbgs() << "\t[" << Start << ';' << Stop
1406                       << "):" << DbgValue.getLocNo());
1407     MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
1408     SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
1409 
1410     LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1411     insertDebugValue(&*MBB, Start, Stop, DbgValue, Spilled, SpillOffset, LIS,
1412                      TII, TRI);
1413     // This interval may span multiple basic blocks.
1414     // Insert a DBG_VALUE into each one.
1415     while (Stop > MBBEnd) {
1416       // Move to the next block.
1417       Start = MBBEnd;
1418       if (++MBB == MFEnd)
1419         break;
1420       MBBEnd = LIS.getMBBEndIdx(&*MBB);
1421       LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1422       insertDebugValue(&*MBB, Start, Stop, DbgValue, Spilled, SpillOffset, LIS,
1423                        TII, TRI);
1424     }
1425     LLVM_DEBUG(dbgs() << '\n');
1426     if (MBB == MFEnd)
1427       break;
1428 
1429     ++I;
1430   }
1431 }
1432 
1433 void UserLabel::emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII) {
1434   LLVM_DEBUG(dbgs() << "\t" << loc);
1435   MachineFunction::iterator MBB = LIS.getMBBFromIndex(loc)->getIterator();
1436 
1437   LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB));
1438   insertDebugLabel(&*MBB, loc, LIS, TII);
1439 
1440   LLVM_DEBUG(dbgs() << '\n');
1441 }
1442 
1443 void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
1444   LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
1445   if (!MF)
1446     return;
1447   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1448   SpillOffsetMap SpillOffsets;
1449   for (auto &userValue : userValues) {
1450     LLVM_DEBUG(userValue->print(dbgs(), TRI));
1451     userValue->rewriteLocations(*VRM, *MF, *TII, *TRI, SpillOffsets);
1452     userValue->emitDebugValues(VRM, *LIS, *TII, *TRI, SpillOffsets);
1453   }
1454   LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG LABELS **********\n");
1455   for (auto &userLabel : userLabels) {
1456     LLVM_DEBUG(userLabel->print(dbgs(), TRI));
1457     userLabel->emitDebugLabel(*LIS, *TII);
1458   }
1459   EmitDone = true;
1460 }
1461 
1462 void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
1463   if (pImpl)
1464     static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
1465 }
1466 
1467 bool LiveDebugVariables::doInitialization(Module &M) {
1468   return Pass::doInitialization(M);
1469 }
1470 
1471 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1472 LLVM_DUMP_METHOD void LiveDebugVariables::dump() const {
1473   if (pImpl)
1474     static_cast<LDVImpl*>(pImpl)->print(dbgs());
1475 }
1476 #endif
1477