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