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