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