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