1 //===- LiveDebugVariables.cpp - Tracking debug info variables -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the LiveDebugVariables analysis.
11 //
12 // Remove all DBG_VALUE instructions referencing virtual registers and replace
13 // them with a data structure tracking where live user variables are kept - in a
14 // virtual register or in a stack slot.
15 //
16 // Allow the data structure to be updated during register allocation when values
17 // are moved between registers and stack slots. Finally emit new DBG_VALUE
18 // instructions after register allocation is complete.
19 //
20 //===----------------------------------------------------------------------===//
21 
22 #include "LiveDebugVariables.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/IntervalMap.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/LiveIntervalAnalysis.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/VirtRegMap.h"
43 #include "llvm/IR/DebugInfoMetadata.h"
44 #include "llvm/IR/DebugLoc.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/Metadata.h"
47 #include "llvm/MC/MCRegisterInfo.h"
48 #include "llvm/Pass.h"
49 #include "llvm/Support/Casting.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetInstrInfo.h"
55 #include "llvm/Target/TargetOpcodes.h"
56 #include "llvm/Target/TargetRegisterInfo.h"
57 #include "llvm/Target/TargetSubtargetInfo.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 
74 char LiveDebugVariables::ID = 0;
75 
76 INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE,
77                 "Debug Variable Analysis", false, false)
78 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
79 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
80 INITIALIZE_PASS_END(LiveDebugVariables, DEBUG_TYPE,
81                 "Debug Variable Analysis", false, false)
82 
83 void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
84   AU.addRequired<MachineDominatorTree>();
85   AU.addRequiredTransitive<LiveIntervals>();
86   AU.setPreservesAll();
87   MachineFunctionPass::getAnalysisUsage(AU);
88 }
89 
90 LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID) {
91   initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
92 }
93 
94 /// LocMap - Map of where a user value is live, and its location.
95 using LocMap = IntervalMap<SlotIndex, unsigned, 4>;
96 
97 namespace {
98 
99 class LDVImpl;
100 
101 /// UserValue - A user value is a part of a debug info user variable.
102 ///
103 /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
104 /// holds part of a user variable. The part is identified by a byte offset.
105 ///
106 /// UserValues are grouped into equivalence classes for easier searching. Two
107 /// user values are related if they refer to the same variable, or if they are
108 /// held by the same virtual register. The equivalence class is the transitive
109 /// closure of that relation.
110 class UserValue {
111   const MDNode *Variable;   ///< The debug info variable we are part of.
112   const MDNode *Expression; ///< Any complex address expression.
113   bool IsIndirect;        ///< true if this is a register-indirect+offset value.
114   DebugLoc dl;            ///< The debug location for the variable. This is
115                           ///< used by dwarf writer to find lexical scope.
116   UserValue *leader;      ///< Equivalence class leader.
117   UserValue *next = nullptr; ///< Next value in equivalence class, or null.
118 
119   /// Numbered locations referenced by locmap.
120   SmallVector<MachineOperand, 4> locations;
121 
122   /// Map of slot indices where this value is live.
123   LocMap locInts;
124 
125   /// Set of interval start indexes that have been trimmed to the
126   /// lexical scope.
127   SmallSet<SlotIndex, 2> trimmedDefs;
128 
129   /// coalesceLocation - After LocNo was changed, check if it has become
130   /// identical to another location, and coalesce them. This may cause LocNo or
131   /// a later location to be erased, but no earlier location will be erased.
132   void coalesceLocation(unsigned LocNo);
133 
134   /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo.
135   void insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, unsigned LocNo,
136                         LiveIntervals &LIS, const TargetInstrInfo &TII);
137 
138   /// splitLocation - Replace OldLocNo ranges with NewRegs ranges where NewRegs
139   /// is live. Returns true if any changes were made.
140   bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
141                      LiveIntervals &LIS);
142 
143 public:
144   /// UserValue - Create a new UserValue.
145   UserValue(const MDNode *var, const MDNode *expr, bool i, DebugLoc L,
146             LocMap::Allocator &alloc)
147       : Variable(var), Expression(expr), IsIndirect(i), dl(std::move(L)),
148         leader(this), locInts(alloc) {}
149 
150   /// getLeader - Get the leader of this value's equivalence class.
151   UserValue *getLeader() {
152     UserValue *l = leader;
153     while (l != l->leader)
154       l = l->leader;
155     return leader = l;
156   }
157 
158   /// getNext - Return the next UserValue in the equivalence class.
159   UserValue *getNext() const { return next; }
160 
161   /// match - Does this UserValue match the parameters?
162   bool match(const MDNode *Var, const MDNode *Expr, const DILocation *IA,
163              bool indirect) const {
164     return Var == Variable && Expr == Expression && dl->getInlinedAt() == IA &&
165            indirect == IsIndirect;
166   }
167 
168   enum : unsigned { UndefLocNo = ~0U };
169 
170   /// merge - Merge equivalence classes.
171   static UserValue *merge(UserValue *L1, UserValue *L2) {
172     L2 = L2->getLeader();
173     if (!L1)
174       return L2;
175     L1 = L1->getLeader();
176     if (L1 == L2)
177       return L1;
178     // Splice L2 before L1's members.
179     UserValue *End = L2;
180     while (End->next) {
181       End->leader = L1;
182       End = End->next;
183     }
184     End->leader = L1;
185     End->next = L1->next;
186     L1->next = L2;
187     return L1;
188   }
189 
190   /// getLocationNo - Return the location number that matches Loc.
191   unsigned getLocationNo(const MachineOperand &LocMO) {
192     if (LocMO.isReg()) {
193       if (LocMO.getReg() == 0)
194         return UndefLocNo;
195       // For register locations we dont care about use/def and other flags.
196       for (unsigned i = 0, e = locations.size(); i != e; ++i)
197         if (locations[i].isReg() &&
198             locations[i].getReg() == LocMO.getReg() &&
199             locations[i].getSubReg() == LocMO.getSubReg())
200           return i;
201     } else
202       for (unsigned i = 0, e = locations.size(); i != e; ++i)
203         if (LocMO.isIdenticalTo(locations[i]))
204           return i;
205     locations.push_back(LocMO);
206     // We are storing a MachineOperand outside a MachineInstr.
207     locations.back().clearParent();
208     // Don't store def operands.
209     if (locations.back().isReg())
210       locations.back().setIsUse();
211     return locations.size() - 1;
212   }
213 
214   /// mapVirtRegs - Ensure that all virtual register locations are mapped.
215   void mapVirtRegs(LDVImpl *LDV);
216 
217   /// addDef - Add a definition point to this value.
218   void addDef(SlotIndex Idx, const MachineOperand &LocMO) {
219     // Add a singular (Idx,Idx) -> Loc mapping.
220     LocMap::iterator I = locInts.find(Idx);
221     if (!I.valid() || I.start() != Idx)
222       I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO));
223     else
224       // A later DBG_VALUE at the same SlotIndex overrides the old location.
225       I.setValue(getLocationNo(LocMO));
226   }
227 
228   /// extendDef - Extend the current definition as far as possible down.
229   /// Stop when meeting an existing def or when leaving the live
230   /// range of VNI.
231   /// End points where VNI is no longer live are added to Kills.
232   /// @param Idx   Starting point for the definition.
233   /// @param LocNo Location number to propagate.
234   /// @param LR    Restrict liveness to where LR has the value VNI. May be null.
235   /// @param VNI   When LR is not null, this is the value to restrict to.
236   /// @param Kills Append end points of VNI's live range to Kills.
237   /// @param LIS   Live intervals analysis.
238   void extendDef(SlotIndex Idx, unsigned LocNo,
239                  LiveRange *LR, const VNInfo *VNI,
240                  SmallVectorImpl<SlotIndex> *Kills,
241                  LiveIntervals &LIS);
242 
243   /// addDefsFromCopies - The value in LI/LocNo may be copies to other
244   /// registers. Determine if any of the copies are available at the kill
245   /// points, and add defs if possible.
246   /// @param LI      Scan for copies of the value in LI->reg.
247   /// @param LocNo   Location number of LI->reg.
248   /// @param Kills   Points where the range of LocNo could be extended.
249   /// @param NewDefs Append (Idx, LocNo) of inserted defs here.
250   void addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
251                        const SmallVectorImpl<SlotIndex> &Kills,
252                        SmallVectorImpl<std::pair<SlotIndex, unsigned>> &NewDefs,
253                        MachineRegisterInfo &MRI,
254                        LiveIntervals &LIS);
255 
256   /// computeIntervals - Compute the live intervals of all locations after
257   /// collecting all their def points.
258   void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
259                         LiveIntervals &LIS, LexicalScopes &LS);
260 
261   /// splitRegister - Replace OldReg ranges with NewRegs ranges where NewRegs is
262   /// live. Returns true if any changes were made.
263   bool splitRegister(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
264                      LiveIntervals &LIS);
265 
266   /// rewriteLocations - Rewrite virtual register locations according to the
267   /// provided virtual register map.
268   void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI);
269 
270   /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
271   void emitDebugValues(VirtRegMap *VRM,
272                        LiveIntervals &LIS, const TargetInstrInfo &TRI);
273 
274   /// getDebugLoc - Return DebugLoc of this UserValue.
275   DebugLoc getDebugLoc() { return dl;}
276 
277   void print(raw_ostream &, const TargetRegisterInfo *);
278 };
279 
280 /// LDVImpl - Implementation of the LiveDebugVariables pass.
281 class LDVImpl {
282   LiveDebugVariables &pass;
283   LocMap::Allocator allocator;
284   MachineFunction *MF = nullptr;
285   LiveIntervals *LIS;
286   const TargetRegisterInfo *TRI;
287 
288   /// Whether emitDebugValues is called.
289   bool EmitDone = false;
290 
291   /// Whether the machine function is modified during the pass.
292   bool ModifiedMF = false;
293 
294   /// userValues - All allocated UserValue instances.
295   SmallVector<std::unique_ptr<UserValue>, 8> userValues;
296 
297   /// Map virtual register to eq class leader.
298   using VRMap = DenseMap<unsigned, UserValue *>;
299   VRMap virtRegToEqClass;
300 
301   /// Map user variable to eq class leader.
302   using UVMap = DenseMap<const MDNode *, UserValue *>;
303   UVMap userVarMap;
304 
305   /// getUserValue - Find or create a UserValue.
306   UserValue *getUserValue(const MDNode *Var, const MDNode *Expr,
307                           bool IsIndirect, const DebugLoc &DL);
308 
309   /// lookupVirtReg - Find the EC leader for VirtReg or null.
310   UserValue *lookupVirtReg(unsigned VirtReg);
311 
312   /// handleDebugValue - Add DBG_VALUE instruction to our maps.
313   /// @param MI  DBG_VALUE instruction
314   /// @param Idx Last valid SLotIndex before instruction.
315   /// @return    True if the DBG_VALUE instruction should be deleted.
316   bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
317 
318   /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
319   /// a UserValue def for each instruction.
320   /// @param mf MachineFunction to be scanned.
321   /// @return True if any debug values were found.
322   bool collectDebugValues(MachineFunction &mf);
323 
324   /// computeIntervals - Compute the live intervals of all user values after
325   /// collecting all their def points.
326   void computeIntervals();
327 
328 public:
329   LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
330 
331   bool runOnMachineFunction(MachineFunction &mf);
332 
333   /// clear - Release all memory.
334   void clear() {
335     MF = nullptr;
336     userValues.clear();
337     virtRegToEqClass.clear();
338     userVarMap.clear();
339     // Make sure we call emitDebugValues if the machine function was modified.
340     assert((!ModifiedMF || EmitDone) &&
341            "Dbg values are not emitted in LDV");
342     EmitDone = false;
343     ModifiedMF = false;
344   }
345 
346   /// mapVirtReg - Map virtual register to an equivalence class.
347   void mapVirtReg(unsigned VirtReg, UserValue *EC);
348 
349   /// splitRegister -  Replace all references to OldReg with NewRegs.
350   void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs);
351 
352   /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
353   void emitDebugValues(VirtRegMap *VRM);
354 
355   void print(raw_ostream&);
356 };
357 
358 } // end anonymous namespace
359 
360 #ifndef NDEBUG
361 static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
362                           const LLVMContext &Ctx) {
363   if (!DL)
364     return;
365 
366   auto *Scope = cast<DIScope>(DL.getScope());
367   // Omit the directory, because it's likely to be long and uninteresting.
368   CommentOS << Scope->getFilename();
369   CommentOS << ':' << DL.getLine();
370   if (DL.getCol() != 0)
371     CommentOS << ':' << DL.getCol();
372 
373   DebugLoc InlinedAtDL = DL.getInlinedAt();
374   if (!InlinedAtDL)
375     return;
376 
377   CommentOS << " @[ ";
378   printDebugLoc(InlinedAtDL, CommentOS, Ctx);
379   CommentOS << " ]";
380 }
381 
382 static void printExtendedName(raw_ostream &OS, const DILocalVariable *V,
383                               const DILocation *DL) {
384   const LLVMContext &Ctx = V->getContext();
385   StringRef Res = V->getName();
386   if (!Res.empty())
387     OS << Res << "," << V->getLine();
388   if (auto *InlinedAt = DL->getInlinedAt()) {
389     if (DebugLoc InlinedAtDL = InlinedAt) {
390       OS << " @[";
391       printDebugLoc(InlinedAtDL, OS, Ctx);
392       OS << "]";
393     }
394   }
395 }
396 
397 void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
398   auto *DV = cast<DILocalVariable>(Variable);
399   OS << "!\"";
400   printExtendedName(OS, DV, dl);
401 
402   OS << "\"\t";
403   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
404     OS << " [" << I.start() << ';' << I.stop() << "):";
405     if (I.value() == UndefLocNo)
406       OS << "undef";
407     else
408       OS << I.value();
409   }
410   for (unsigned i = 0, e = locations.size(); i != e; ++i) {
411     OS << " Loc" << i << '=';
412     locations[i].print(OS, TRI);
413   }
414   OS << '\n';
415 }
416 
417 void LDVImpl::print(raw_ostream &OS) {
418   OS << "********** DEBUG VARIABLES **********\n";
419   for (unsigned i = 0, e = userValues.size(); i != e; ++i)
420     userValues[i]->print(OS, TRI);
421 }
422 #endif
423 
424 void UserValue::coalesceLocation(unsigned LocNo) {
425   unsigned KeepLoc = 0;
426   for (unsigned e = locations.size(); KeepLoc != e; ++KeepLoc) {
427     if (KeepLoc == LocNo)
428       continue;
429     if (locations[KeepLoc].isIdenticalTo(locations[LocNo]))
430       break;
431   }
432   // No matches.
433   if (KeepLoc == locations.size())
434     return;
435 
436   // Keep the smaller location, erase the larger one.
437   unsigned EraseLoc = LocNo;
438   if (KeepLoc > EraseLoc)
439     std::swap(KeepLoc, EraseLoc);
440   locations.erase(locations.begin() + EraseLoc);
441 
442   // Rewrite values.
443   for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
444     unsigned v = I.value();
445     if (v == EraseLoc)
446       I.setValue(KeepLoc);      // Coalesce when possible.
447     else if (v > EraseLoc)
448       I.setValueUnchecked(v-1); // Avoid coalescing with untransformed values.
449   }
450 }
451 
452 void UserValue::mapVirtRegs(LDVImpl *LDV) {
453   for (unsigned i = 0, e = locations.size(); i != e; ++i)
454     if (locations[i].isReg() &&
455         TargetRegisterInfo::isVirtualRegister(locations[i].getReg()))
456       LDV->mapVirtReg(locations[i].getReg(), this);
457 }
458 
459 UserValue *LDVImpl::getUserValue(const MDNode *Var, const MDNode *Expr,
460                                  bool IsIndirect, const DebugLoc &DL) {
461   UserValue *&Leader = userVarMap[Var];
462   if (Leader) {
463     UserValue *UV = Leader->getLeader();
464     Leader = UV;
465     for (; UV; UV = UV->getNext())
466       if (UV->match(Var, Expr, DL->getInlinedAt(), IsIndirect))
467         return UV;
468   }
469 
470   userValues.push_back(
471       llvm::make_unique<UserValue>(Var, Expr, IsIndirect, DL, allocator));
472   UserValue *UV = userValues.back().get();
473   Leader = UserValue::merge(Leader, UV);
474   return UV;
475 }
476 
477 void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
478   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
479   UserValue *&Leader = virtRegToEqClass[VirtReg];
480   Leader = UserValue::merge(Leader, EC);
481 }
482 
483 UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
484   if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
485     return UV->getLeader();
486   return nullptr;
487 }
488 
489 bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
490   // DBG_VALUE loc, offset, variable
491   if (MI.getNumOperands() != 4 ||
492       !(MI.getOperand(1).isReg() || MI.getOperand(1).isImm()) ||
493       !MI.getOperand(2).isMetadata()) {
494     DEBUG(dbgs() << "Can't handle " << MI);
495     return false;
496   }
497 
498   // Get or create the UserValue for (variable,offset).
499   bool IsIndirect = MI.isIndirectDebugValue();
500   if (IsIndirect)
501     assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
502   const MDNode *Var = MI.getDebugVariable();
503   const MDNode *Expr = MI.getDebugExpression();
504   //here.
505   UserValue *UV = getUserValue(Var, Expr, IsIndirect, MI.getDebugLoc());
506   UV->addDef(Idx, MI.getOperand(0));
507   return true;
508 }
509 
510 bool LDVImpl::collectDebugValues(MachineFunction &mf) {
511   bool Changed = false;
512   for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
513        ++MFI) {
514     MachineBasicBlock *MBB = &*MFI;
515     for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
516          MBBI != MBBE;) {
517       if (!MBBI->isDebugValue()) {
518         ++MBBI;
519         continue;
520       }
521       // DBG_VALUE has no slot index, use the previous instruction instead.
522       SlotIndex Idx =
523           MBBI == MBB->begin()
524               ? LIS->getMBBStartIdx(MBB)
525               : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
526       // Handle consecutive DBG_VALUE instructions with the same slot index.
527       do {
528         if (handleDebugValue(*MBBI, Idx)) {
529           MBBI = MBB->erase(MBBI);
530           Changed = true;
531         } else
532           ++MBBI;
533       } while (MBBI != MBBE && MBBI->isDebugValue());
534     }
535   }
536   return Changed;
537 }
538 
539 /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
540 /// data-flow analysis to propagate them beyond basic block boundaries.
541 void UserValue::extendDef(SlotIndex Idx, unsigned LocNo, LiveRange *LR,
542                           const VNInfo *VNI, SmallVectorImpl<SlotIndex> *Kills,
543                           LiveIntervals &LIS) {
544   SlotIndex Start = Idx;
545   MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
546   SlotIndex Stop = LIS.getMBBEndIdx(MBB);
547   LocMap::iterator I = locInts.find(Start);
548 
549   // Limit to VNI's live range.
550   bool ToEnd = true;
551   if (LR && VNI) {
552     LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
553     if (!Segment || Segment->valno != VNI) {
554       if (Kills)
555         Kills->push_back(Start);
556       return;
557     }
558     if (Segment->end < Stop) {
559       Stop = Segment->end;
560       ToEnd = false;
561     }
562   }
563 
564   // There could already be a short def at Start.
565   if (I.valid() && I.start() <= Start) {
566     // Stop when meeting a different location or an already extended interval.
567     Start = Start.getNextSlot();
568     if (I.value() != LocNo || I.stop() != Start)
569       return;
570     // This is a one-slot placeholder. Just skip it.
571     ++I;
572   }
573 
574   // Limited by the next def.
575   if (I.valid() && I.start() < Stop) {
576     Stop = I.start();
577     ToEnd = false;
578   }
579   // Limited by VNI's live range.
580   else if (!ToEnd && Kills)
581     Kills->push_back(Stop);
582 
583   if (Start < Stop)
584     I.insert(Start, Stop, LocNo);
585 }
586 
587 void
588 UserValue::addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
589                        const SmallVectorImpl<SlotIndex> &Kills,
590                        SmallVectorImpl<std::pair<SlotIndex, unsigned>> &NewDefs,
591                        MachineRegisterInfo &MRI, LiveIntervals &LIS) {
592   if (Kills.empty())
593     return;
594   // Don't track copies from physregs, there are too many uses.
595   if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
596     return;
597 
598   // Collect all the (vreg, valno) pairs that are copies of LI.
599   SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
600   for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) {
601     MachineInstr *MI = MO.getParent();
602     // Copies of the full value.
603     if (MO.getSubReg() || !MI->isCopy())
604       continue;
605     unsigned DstReg = MI->getOperand(0).getReg();
606 
607     // Don't follow copies to physregs. These are usually setting up call
608     // arguments, and the argument registers are always call clobbered. We are
609     // better off in the source register which could be a callee-saved register,
610     // or it could be spilled.
611     if (!TargetRegisterInfo::isVirtualRegister(DstReg))
612       continue;
613 
614     // Is LocNo extended to reach this copy? If not, another def may be blocking
615     // it, or we are looking at a wrong value of LI.
616     SlotIndex Idx = LIS.getInstructionIndex(*MI);
617     LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
618     if (!I.valid() || I.value() != LocNo)
619       continue;
620 
621     if (!LIS.hasInterval(DstReg))
622       continue;
623     LiveInterval *DstLI = &LIS.getInterval(DstReg);
624     const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
625     assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
626     CopyValues.push_back(std::make_pair(DstLI, DstVNI));
627   }
628 
629   if (CopyValues.empty())
630     return;
631 
632   DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI << '\n');
633 
634   // Try to add defs of the copied values for each kill point.
635   for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
636     SlotIndex Idx = Kills[i];
637     for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
638       LiveInterval *DstLI = CopyValues[j].first;
639       const VNInfo *DstVNI = CopyValues[j].second;
640       if (DstLI->getVNInfoAt(Idx) != DstVNI)
641         continue;
642       // Check that there isn't already a def at Idx
643       LocMap::iterator I = locInts.find(Idx);
644       if (I.valid() && I.start() <= Idx)
645         continue;
646       DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
647                    << DstVNI->id << " in " << *DstLI << '\n');
648       MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
649       assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
650       unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
651       I.insert(Idx, Idx.getNextSlot(), LocNo);
652       NewDefs.push_back(std::make_pair(Idx, LocNo));
653       break;
654     }
655   }
656 }
657 
658 void UserValue::computeIntervals(MachineRegisterInfo &MRI,
659                                  const TargetRegisterInfo &TRI,
660                                  LiveIntervals &LIS, LexicalScopes &LS) {
661   SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs;
662 
663   // Collect all defs to be extended (Skipping undefs).
664   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
665     if (I.value() != UndefLocNo)
666       Defs.push_back(std::make_pair(I.start(), I.value()));
667 
668   // Extend all defs, and possibly add new ones along the way.
669   for (unsigned i = 0; i != Defs.size(); ++i) {
670     SlotIndex Idx = Defs[i].first;
671     unsigned LocNo = Defs[i].second;
672     const MachineOperand &Loc = locations[LocNo];
673 
674     if (!Loc.isReg()) {
675       extendDef(Idx, LocNo, nullptr, nullptr, nullptr, LIS);
676       continue;
677     }
678 
679     // Register locations are constrained to where the register value is live.
680     if (TargetRegisterInfo::isVirtualRegister(Loc.getReg())) {
681       LiveInterval *LI = nullptr;
682       const VNInfo *VNI = nullptr;
683       if (LIS.hasInterval(Loc.getReg())) {
684         LI = &LIS.getInterval(Loc.getReg());
685         VNI = LI->getVNInfoAt(Idx);
686       }
687       SmallVector<SlotIndex, 16> Kills;
688       extendDef(Idx, LocNo, LI, VNI, &Kills, LIS);
689       if (LI)
690         addDefsFromCopies(LI, LocNo, Kills, Defs, MRI, LIS);
691       continue;
692     }
693 
694     // For physregs, use the live range of the first regunit as a guide.
695     unsigned Unit = *MCRegUnitIterator(Loc.getReg(), &TRI);
696     LiveRange *LR = &LIS.getRegUnit(Unit);
697     const VNInfo *VNI = LR->getVNInfoAt(Idx);
698     // Don't track copies from physregs, it is too expensive.
699     extendDef(Idx, LocNo, LR, VNI, nullptr, LIS);
700   }
701 
702   // Erase all the undefs.
703   for (LocMap::iterator I = locInts.begin(); I.valid();)
704     if (I.value() == UndefLocNo)
705       I.erase();
706     else
707       ++I;
708 
709   // The computed intervals may extend beyond the range of the debug
710   // location's lexical scope. In this case, splitting of an interval
711   // can result in an interval outside of the scope being created,
712   // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
713   // this, trim the intervals to the lexical scope.
714 
715   LexicalScope *Scope = LS.findLexicalScope(dl);
716   if (!Scope)
717     return;
718 
719   SlotIndex PrevEnd;
720   LocMap::iterator I = locInts.begin();
721 
722   // Iterate over the lexical scope ranges. Each time round the loop
723   // we check the intervals for overlap with the end of the previous
724   // range and the start of the next. The first range is handled as
725   // a special case where there is no PrevEnd.
726   for (const InsnRange &Range : Scope->getRanges()) {
727     SlotIndex RStart = LIS.getInstructionIndex(*Range.first);
728     SlotIndex REnd = LIS.getInstructionIndex(*Range.second);
729 
730     // At the start of each iteration I has been advanced so that
731     // I.stop() >= PrevEnd. Check for overlap.
732     if (PrevEnd && I.start() < PrevEnd) {
733       SlotIndex IStop = I.stop();
734       unsigned LocNo = I.value();
735 
736       // Stop overlaps previous end - trim the end of the interval to
737       // the scope range.
738       I.setStopUnchecked(PrevEnd);
739       ++I;
740 
741       // If the interval also overlaps the start of the "next" (i.e.
742       // current) range create a new interval for the remainder (which
743       // may be further trimmed).
744       if (RStart < IStop)
745         I.insert(RStart, IStop, LocNo);
746     }
747 
748     // Advance I so that I.stop() >= RStart, and check for overlap.
749     I.advanceTo(RStart);
750     if (!I.valid())
751       return;
752 
753     if (I.start() < RStart) {
754       // Interval start overlaps range - trim to the scope range.
755       I.setStartUnchecked(RStart);
756       // Remember that this interval was trimmed.
757       trimmedDefs.insert(RStart);
758     }
759 
760     // The end of a lexical scope range is the last instruction in the
761     // range. To convert to an interval we need the index of the
762     // instruction after it.
763     REnd = REnd.getNextIndex();
764 
765     // Advance I to first interval outside current range.
766     I.advanceTo(REnd);
767     if (!I.valid())
768       return;
769 
770     PrevEnd = REnd;
771   }
772 
773   // Check for overlap with end of final range.
774   if (PrevEnd && I.start() < PrevEnd)
775     I.setStopUnchecked(PrevEnd);
776 }
777 
778 void LDVImpl::computeIntervals() {
779   LexicalScopes LS;
780   LS.initialize(*MF);
781 
782   for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
783     userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS);
784     userValues[i]->mapVirtRegs(this);
785   }
786 }
787 
788 bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
789   clear();
790   MF = &mf;
791   LIS = &pass.getAnalysis<LiveIntervals>();
792   TRI = mf.getSubtarget().getRegisterInfo();
793   DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
794                << mf.getName() << " **********\n");
795 
796   bool Changed = collectDebugValues(mf);
797   computeIntervals();
798   DEBUG(print(dbgs()));
799   ModifiedMF = Changed;
800   return Changed;
801 }
802 
803 static void removeDebugValues(MachineFunction &mf) {
804   for (MachineBasicBlock &MBB : mf) {
805     for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) {
806       if (!MBBI->isDebugValue()) {
807         ++MBBI;
808         continue;
809       }
810       MBBI = MBB.erase(MBBI);
811     }
812   }
813 }
814 
815 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
816   if (!EnableLDV)
817     return false;
818   if (!mf.getFunction()->getSubprogram()) {
819     removeDebugValues(mf);
820     return false;
821   }
822   if (!pImpl)
823     pImpl = new LDVImpl(this);
824   return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
825 }
826 
827 void LiveDebugVariables::releaseMemory() {
828   if (pImpl)
829     static_cast<LDVImpl*>(pImpl)->clear();
830 }
831 
832 LiveDebugVariables::~LiveDebugVariables() {
833   if (pImpl)
834     delete static_cast<LDVImpl*>(pImpl);
835 }
836 
837 //===----------------------------------------------------------------------===//
838 //                           Live Range Splitting
839 //===----------------------------------------------------------------------===//
840 
841 bool
842 UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
843                          LiveIntervals& LIS) {
844   DEBUG({
845     dbgs() << "Splitting Loc" << OldLocNo << '\t';
846     print(dbgs(), nullptr);
847   });
848   bool DidChange = false;
849   LocMap::iterator LocMapI;
850   LocMapI.setMap(locInts);
851   for (unsigned i = 0; i != NewRegs.size(); ++i) {
852     LiveInterval *LI = &LIS.getInterval(NewRegs[i]);
853     if (LI->empty())
854       continue;
855 
856     // Don't allocate the new LocNo until it is needed.
857     unsigned NewLocNo = UndefLocNo;
858 
859     // Iterate over the overlaps between locInts and LI.
860     LocMapI.find(LI->beginIndex());
861     if (!LocMapI.valid())
862       continue;
863     LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
864     LiveInterval::iterator LIE = LI->end();
865     while (LocMapI.valid() && LII != LIE) {
866       // At this point, we know that LocMapI.stop() > LII->start.
867       LII = LI->advanceTo(LII, LocMapI.start());
868       if (LII == LIE)
869         break;
870 
871       // Now LII->end > LocMapI.start(). Do we have an overlap?
872       if (LocMapI.value() == OldLocNo && LII->start < LocMapI.stop()) {
873         // Overlapping correct location. Allocate NewLocNo now.
874         if (NewLocNo == UndefLocNo) {
875           MachineOperand MO = MachineOperand::CreateReg(LI->reg, false);
876           MO.setSubReg(locations[OldLocNo].getSubReg());
877           NewLocNo = getLocationNo(MO);
878           DidChange = true;
879         }
880 
881         SlotIndex LStart = LocMapI.start();
882         SlotIndex LStop  = LocMapI.stop();
883 
884         // Trim LocMapI down to the LII overlap.
885         if (LStart < LII->start)
886           LocMapI.setStartUnchecked(LII->start);
887         if (LStop > LII->end)
888           LocMapI.setStopUnchecked(LII->end);
889 
890         // Change the value in the overlap. This may trigger coalescing.
891         LocMapI.setValue(NewLocNo);
892 
893         // Re-insert any removed OldLocNo ranges.
894         if (LStart < LocMapI.start()) {
895           LocMapI.insert(LStart, LocMapI.start(), OldLocNo);
896           ++LocMapI;
897           assert(LocMapI.valid() && "Unexpected coalescing");
898         }
899         if (LStop > LocMapI.stop()) {
900           ++LocMapI;
901           LocMapI.insert(LII->end, LStop, OldLocNo);
902           --LocMapI;
903         }
904       }
905 
906       // Advance to the next overlap.
907       if (LII->end < LocMapI.stop()) {
908         if (++LII == LIE)
909           break;
910         LocMapI.advanceTo(LII->start);
911       } else {
912         ++LocMapI;
913         if (!LocMapI.valid())
914           break;
915         LII = LI->advanceTo(LII, LocMapI.start());
916       }
917     }
918   }
919 
920   // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
921   locations.erase(locations.begin() + OldLocNo);
922   LocMapI.goToBegin();
923   while (LocMapI.valid()) {
924     unsigned v = LocMapI.value();
925     if (v == OldLocNo) {
926       DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
927                    << LocMapI.stop() << ")\n");
928       LocMapI.erase();
929     } else {
930       if (v > OldLocNo)
931         LocMapI.setValueUnchecked(v-1);
932       ++LocMapI;
933     }
934   }
935 
936   DEBUG({dbgs() << "Split result: \t"; print(dbgs(), nullptr);});
937   return DidChange;
938 }
939 
940 bool
941 UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
942                          LiveIntervals &LIS) {
943   bool DidChange = false;
944   // Split locations referring to OldReg. Iterate backwards so splitLocation can
945   // safely erase unused locations.
946   for (unsigned i = locations.size(); i ; --i) {
947     unsigned LocNo = i-1;
948     const MachineOperand *Loc = &locations[LocNo];
949     if (!Loc->isReg() || Loc->getReg() != OldReg)
950       continue;
951     DidChange |= splitLocation(LocNo, NewRegs, LIS);
952   }
953   return DidChange;
954 }
955 
956 void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) {
957   bool DidChange = false;
958   for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
959     DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
960 
961   if (!DidChange)
962     return;
963 
964   // Map all of the new virtual registers.
965   UserValue *UV = lookupVirtReg(OldReg);
966   for (unsigned i = 0; i != NewRegs.size(); ++i)
967     mapVirtReg(NewRegs[i], UV);
968 }
969 
970 void LiveDebugVariables::
971 splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) {
972   if (pImpl)
973     static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
974 }
975 
976 void
977 UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI) {
978   // Iterate over locations in reverse makes it easier to handle coalescing.
979   for (unsigned i = locations.size(); i ; --i) {
980     unsigned LocNo = i-1;
981     MachineOperand &Loc = locations[LocNo];
982     // Only virtual registers are rewritten.
983     if (!Loc.isReg() || !Loc.getReg() ||
984         !TargetRegisterInfo::isVirtualRegister(Loc.getReg()))
985       continue;
986     unsigned VirtReg = Loc.getReg();
987     if (VRM.isAssignedReg(VirtReg) &&
988         TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) {
989       // This can create a %noreg operand in rare cases when the sub-register
990       // index is no longer available. That means the user value is in a
991       // non-existent sub-register, and %noreg is exactly what we want.
992       Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
993     } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
994       // FIXME: Translate SubIdx to a stackslot offset.
995       Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
996     } else {
997       Loc.setReg(0);
998       Loc.setSubReg(0);
999     }
1000     coalesceLocation(LocNo);
1001   }
1002 }
1003 
1004 /// findInsertLocation - Find an iterator for inserting a DBG_VALUE
1005 /// instruction.
1006 static MachineBasicBlock::iterator
1007 findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
1008                    LiveIntervals &LIS) {
1009   SlotIndex Start = LIS.getMBBStartIdx(MBB);
1010   Idx = Idx.getBaseIndex();
1011 
1012   // Try to find an insert location by going backwards from Idx.
1013   MachineInstr *MI;
1014   while (!(MI = LIS.getInstructionFromIndex(Idx))) {
1015     // We've reached the beginning of MBB.
1016     if (Idx == Start) {
1017       MachineBasicBlock::iterator I = MBB->SkipPHIsLabelsAndDebug(MBB->begin());
1018       return I;
1019     }
1020     Idx = Idx.getPrevIndex();
1021   }
1022 
1023   // Don't insert anything after the first terminator, though.
1024   return MI->isTerminator() ? MBB->getFirstTerminator() :
1025                               std::next(MachineBasicBlock::iterator(MI));
1026 }
1027 
1028 void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx,
1029                                  unsigned LocNo,
1030                                  LiveIntervals &LIS,
1031                                  const TargetInstrInfo &TII) {
1032   MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS);
1033   MachineOperand &Loc = locations[LocNo];
1034   ++NumInsertedDebugValues;
1035 
1036   assert(cast<DILocalVariable>(Variable)
1037              ->isValidLocationForIntrinsic(getDebugLoc()) &&
1038          "Expected inlined-at fields to agree");
1039   if (Loc.isReg())
1040     BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE),
1041             IsIndirect, Loc.getReg(), Variable, Expression);
1042   else
1043     BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE))
1044         .add(Loc)
1045         .addImm(0U)
1046         .addMetadata(Variable)
1047         .addMetadata(Expression);
1048 }
1049 
1050 void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
1051                                 const TargetInstrInfo &TII) {
1052   MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
1053 
1054   for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
1055     SlotIndex Start = I.start();
1056     SlotIndex Stop = I.stop();
1057     unsigned LocNo = I.value();
1058 
1059     // If the interval start was trimmed to the lexical scope insert the
1060     // DBG_VALUE at the previous index (otherwise it appears after the
1061     // first instruction in the range).
1062     if (trimmedDefs.count(Start))
1063       Start = Start.getPrevIndex();
1064 
1065     DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo);
1066     MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
1067     SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
1068 
1069     DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
1070     insertDebugValue(&*MBB, Start, LocNo, LIS, TII);
1071     // This interval may span multiple basic blocks.
1072     // Insert a DBG_VALUE into each one.
1073     while(Stop > MBBEnd) {
1074       // Move to the next block.
1075       Start = MBBEnd;
1076       if (++MBB == MFEnd)
1077         break;
1078       MBBEnd = LIS.getMBBEndIdx(&*MBB);
1079       DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
1080       insertDebugValue(&*MBB, Start, LocNo, LIS, TII);
1081     }
1082     DEBUG(dbgs() << '\n');
1083     if (MBB == MFEnd)
1084       break;
1085 
1086     ++I;
1087   }
1088 }
1089 
1090 void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
1091   DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
1092   if (!MF)
1093     return;
1094   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1095   for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
1096     DEBUG(userValues[i]->print(dbgs(), TRI));
1097     userValues[i]->rewriteLocations(*VRM, *TRI);
1098     userValues[i]->emitDebugValues(VRM, *LIS, *TII);
1099   }
1100   EmitDone = true;
1101 }
1102 
1103 void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
1104   if (pImpl)
1105     static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
1106 }
1107 
1108 bool LiveDebugVariables::doInitialization(Module &M) {
1109   return Pass::doInitialization(M);
1110 }
1111 
1112 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1113 LLVM_DUMP_METHOD void LiveDebugVariables::dump() const {
1114   if (pImpl)
1115     static_cast<LDVImpl*>(pImpl)->print(dbgs());
1116 }
1117 #endif
1118