Appropriately truncate debug info range in dwarf output.
[oota-llvm.git] / lib / CodeGen / LiveDebugVariables.cpp
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 #define DEBUG_TYPE "livedebug"
23 #include "LiveDebugVariables.h"
24 #include "VirtRegMap.h"
25 #include "llvm/Constants.h"
26 #include "llvm/Metadata.h"
27 #include "llvm/Value.h"
28 #include "llvm/ADT/IntervalMap.h"
29 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
30 #include "llvm/CodeGen/MachineDominators.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/Passes.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39
40 using namespace llvm;
41
42 char LiveDebugVariables::ID = 0;
43
44 INITIALIZE_PASS_BEGIN(LiveDebugVariables, "livedebugvars",
45                 "Debug Variable Analysis", false, false)
46 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
47 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
48 INITIALIZE_PASS_END(LiveDebugVariables, "livedebugvars",
49                 "Debug Variable Analysis", false, false)
50
51 void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
52   AU.addRequired<MachineDominatorTree>();
53   AU.addRequiredTransitive<LiveIntervals>();
54   AU.setPreservesAll();
55   MachineFunctionPass::getAnalysisUsage(AU);
56 }
57
58 LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID), pImpl(0) {
59   initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
60 }
61
62 /// Location - All the different places a user value can reside.
63 /// Note that this includes immediate values that technically aren't locations.
64 namespace {
65 struct Location {
66   /// kind - What kind of location is this?
67   enum Kind {
68     locUndef = 0,
69     locImm   = 0x80000000,
70     locFPImm
71   };
72   /// Kind - One of the following:
73   /// 1. locUndef
74   /// 2. Register number (physical or virtual), data.SubIdx is the subreg index.
75   /// 3. ~Frame index, data.Offset is the offset.
76   /// 4. locImm, data.ImmVal is the constant integer value.
77   /// 5. locFPImm, data.CFP points to the floating point constant.
78   unsigned Kind;
79
80   /// Data - Extra data about location.
81   union {
82     unsigned SubIdx;          ///< For virtual registers.
83     int64_t Offset;           ///< For frame indices.
84     int64_t ImmVal;           ///< For locImm.
85     const ConstantFP *CFP;    ///< For locFPImm.
86   } Data;
87
88   Location(const MachineOperand &MO) {
89     switch(MO.getType()) {
90     case MachineOperand::MO_Register:
91       Kind = MO.getReg();
92       Data.SubIdx = MO.getSubReg();
93       return;
94     case MachineOperand::MO_Immediate:
95       Kind = locImm;
96       Data.ImmVal = MO.getImm();
97       return;
98     case MachineOperand::MO_FPImmediate:
99       Kind = locFPImm;
100       Data.CFP = MO.getFPImm();
101       return;
102     case MachineOperand::MO_FrameIndex:
103       Kind = ~MO.getIndex();
104       // FIXME: MO_FrameIndex should support an offset.
105       Data.Offset = 0;
106       return;
107     default:
108       Kind = locUndef;
109       return;
110     }
111   }
112
113   /// addOperand - Add this location as a machine operand to MI.
114   MachineInstrBuilder addOperand(MachineInstrBuilder MI) const {
115     switch (Kind) {
116     case locImm:
117       return MI.addImm(Data.ImmVal);
118     case locFPImm:
119       return MI.addFPImm(Data.CFP);
120     default:
121       if (isFrameIndex())
122         return MI.addFrameIndex(getFrameIndex());
123       else
124         return MI.addReg(Kind);  // reg and undef.
125     }
126   }
127
128   bool operator==(const Location &RHS) const {
129     if (Kind != RHS.Kind)
130       return false;
131     switch (Kind) {
132     case locUndef:
133       return true;
134     case locImm:
135       return Data.ImmVal == RHS.Data.ImmVal;
136     case locFPImm:
137       return Data.CFP == RHS.Data.CFP;
138     default:
139       if (isReg())
140         return Data.SubIdx == RHS.Data.SubIdx;
141       else
142          return Data.Offset == RHS.Data.Offset;
143     }
144   }
145
146   /// isUndef - is this the singleton undef?
147   bool isUndef() const { return Kind == locUndef; }
148
149   /// isReg - is this a register location?
150   bool isReg() const { return Kind && Kind < locImm; }
151
152   /// isFrameIndex - is this a frame index location?
153   bool isFrameIndex() const { return Kind > locFPImm; }
154
155   int getFrameIndex() const { return ~Kind; }
156
157   void print(raw_ostream&, const TargetRegisterInfo*);
158 };
159 }
160
161 /// LocMap - Map of where a user value is live, and its location.
162 typedef IntervalMap<SlotIndex, unsigned, 4> LocMap;
163
164 /// UserValue - A user value is a part of a debug info user variable.
165 ///
166 /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
167 /// holds part of a user variable. The part is identified by a byte offset.
168 ///
169 /// UserValues are grouped into equivalence classes for easier searching. Two
170 /// user values are related if they refer to the same variable, or if they are
171 /// held by the same virtual register. The equivalence class is the transitive
172 /// closure of that relation.
173 namespace {
174 class UserValue {
175   const MDNode *variable; ///< The debug info variable we are part of.
176   unsigned offset;        ///< Byte offset into variable.
177
178   UserValue *leader;      ///< Equivalence class leader.
179   UserValue *next;        ///< Next value in equivalence class, or null.
180
181   /// Numbered locations referenced by locmap.
182   SmallVector<Location, 4> locations;
183
184   /// Map of slot indices where this value is live.
185   LocMap locInts;
186
187   /// coalesceLocation - After LocNo was changed, check if it has become
188   /// identical to another location, and coalesce them. This may cause LocNo or
189   /// a later location to be erased, but no earlier location will be erased.
190   void coalesceLocation(unsigned LocNo);
191
192   /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo.
193   void insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, unsigned LocNo,
194                         LiveIntervals &LIS, const TargetInstrInfo &TII);
195
196   /// insertDebugKill - Insert an undef DBG_VALUE into MBB at Idx.
197   void insertDebugKill(MachineBasicBlock *MBB, SlotIndex Idx,
198                        LiveIntervals &LIS, const TargetInstrInfo &TII);
199
200 public:
201   /// UserValue - Create a new UserValue.
202   UserValue(const MDNode *var, unsigned o, LocMap::Allocator &alloc)
203     : variable(var), offset(o), leader(this), next(0), locInts(alloc)
204   {}
205
206   /// getLeader - Get the leader of this value's equivalence class.
207   UserValue *getLeader() {
208     UserValue *l = leader;
209     while (l != l->leader)
210       l = l->leader;
211     return leader = l;
212   }
213
214   /// getNext - Return the next UserValue in the equivalence class.
215   UserValue *getNext() const { return next; }
216
217   /// match - Does this UserValue match the aprameters?
218   bool match(const MDNode *Var, unsigned Offset) const {
219     return Var == variable && Offset == offset;
220   }
221
222   /// merge - Merge equivalence classes.
223   static UserValue *merge(UserValue *L1, UserValue *L2) {
224     L2 = L2->getLeader();
225     if (!L1)
226       return L2;
227     L1 = L1->getLeader();
228     if (L1 == L2)
229       return L1;
230     // Splice L2 before L1's members.
231     UserValue *End = L2;
232     while (End->next)
233       End->leader = L1, End = End->next;
234     End->leader = L1;
235     End->next = L1->next;
236     L1->next = L2;
237     return L1;
238   }
239
240   /// getLocationNo - Return the location number that matches Loc.
241   unsigned getLocationNo(Location Loc) {
242     if (Loc.isUndef())
243       return ~0u;
244     unsigned n = std::find(locations.begin(), locations.end(), Loc) -
245                  locations.begin();
246     if (n == locations.size())
247       locations.push_back(Loc);
248     return n;
249   }
250
251   /// addDef - Add a definition point to this value.
252   void addDef(SlotIndex Idx, const MachineOperand &LocMO) {
253     // Add a singular (Idx,Idx) -> Loc mapping.
254     LocMap::iterator I = locInts.find(Idx);
255     if (!I.valid() || I.start() != Idx)
256       I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO));
257   }
258
259   /// extendDef - Extend the current definition as far as possible down the
260   /// dominator tree. Stop when meeting an existing def or when leaving the live
261   /// range of VNI.
262   /// @param Idx   Starting point for the definition.
263   /// @param LocNo Location number to propagate.
264   /// @param LI    Restrict liveness to where LI has the value VNI. May be null.
265   /// @param VNI   When LI is not null, this is the value to restrict to.
266   /// @param LIS   Live intervals analysis.
267   /// @param MDT   Dominator tree.
268   void extendDef(SlotIndex Idx, unsigned LocNo,
269                  LiveInterval *LI, const VNInfo *VNI,
270                  LiveIntervals &LIS, MachineDominatorTree &MDT);
271
272   /// computeIntervals - Compute the live intervals of all locations after
273   /// collecting all their def points.
274   void computeIntervals(LiveIntervals &LIS, MachineDominatorTree &MDT);
275
276   /// renameRegister - Update locations to rewrite OldReg as NewReg:SubIdx.
277   void renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx,
278                       const TargetRegisterInfo *TRI);
279
280   /// rewriteLocations - Rewrite virtual register locations according to the
281   /// provided virtual register map.
282   void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI);
283
284   /// emitDebugVariables - Recreate DBG_VALUE instruction from data structures.
285   void emitDebugValues(VirtRegMap *VRM,
286                        LiveIntervals &LIS, const TargetInstrInfo &TRI);
287
288   void print(raw_ostream&, const TargetRegisterInfo*);
289 };
290 } // namespace
291
292 /// LDVImpl - Implementation of the LiveDebugVariables pass.
293 namespace {
294 class LDVImpl {
295   LiveDebugVariables &pass;
296   LocMap::Allocator allocator;
297   MachineFunction *MF;
298   LiveIntervals *LIS;
299   MachineDominatorTree *MDT;
300   const TargetRegisterInfo *TRI;
301
302   /// userValues - All allocated UserValue instances.
303   SmallVector<UserValue*, 8> userValues;
304
305   /// Map virtual register to eq class leader.
306   typedef DenseMap<unsigned, UserValue*> VRMap;
307   VRMap virtRegToEqClass;
308
309   /// Map user variable to eq class leader.
310   typedef DenseMap<const MDNode *, UserValue*> UVMap;
311   UVMap userVarMap;
312
313   /// getUserValue - Find or create a UserValue.
314   UserValue *getUserValue(const MDNode *Var, unsigned Offset);
315
316   /// lookupVirtReg - Find the EC leader for VirtReg or null.
317   UserValue *lookupVirtReg(unsigned VirtReg);
318
319   /// mapVirtReg - Map virtual register to an equivalence class.
320   void mapVirtReg(unsigned VirtReg, UserValue *EC);
321
322   /// handleDebugValue - Add DBG_VALUE instruction to our maps.
323   /// @param MI  DBG_VALUE instruction
324   /// @param Idx Last valid SLotIndex before instruction.
325   /// @return    True if the DBG_VALUE instruction should be deleted.
326   bool handleDebugValue(MachineInstr *MI, SlotIndex Idx);
327
328   /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
329   /// a UserValue def for each instruction.
330   /// @param mf MachineFunction to be scanned.
331   /// @return True if any debug values were found.
332   bool collectDebugValues(MachineFunction &mf);
333
334   /// computeIntervals - Compute the live intervals of all user values after
335   /// collecting all their def points.
336   void computeIntervals();
337
338 public:
339   LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
340   bool runOnMachineFunction(MachineFunction &mf);
341
342   /// clear - Relase all memory.
343   void clear() {
344     DeleteContainerPointers(userValues);
345     userValues.clear();
346     virtRegToEqClass.clear();
347     userVarMap.clear();
348   }
349
350   /// renameRegister - Replace all references to OldReg wiht NewReg:SubIdx.
351   void renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx);
352
353   /// emitDebugVariables - Recreate DBG_VALUE instruction from data structures.
354   void emitDebugValues(VirtRegMap *VRM);
355
356   void print(raw_ostream&);
357 };
358 } // namespace
359
360 void Location::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
361   switch (Kind) {
362   case locUndef:
363     OS << "undef";
364     return;
365   case locImm:
366     OS << "int:" << Data.ImmVal;
367     return;
368   case locFPImm:
369     OS << "fp:" << Data.CFP->getValueAPF().convertToDouble();
370     return;
371   default:
372     if (isReg()) {
373       if (TargetRegisterInfo::isVirtualRegister(Kind)) {
374         OS << "%reg" << Kind;
375         if (Data.SubIdx)
376           OS << ':' << TRI->getSubRegIndexName(Data.SubIdx);
377       } else
378         OS << '%' << TRI->getName(Kind);
379     } else {
380       OS << "fi#" << ~Kind;
381       if (Data.Offset)
382         OS << '+' << Data.Offset;
383     }
384     return;
385   }
386 }
387
388 void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
389   if (const MDString *MDS = dyn_cast<MDString>(variable->getOperand(2)))
390     OS << "!\"" << MDS->getString() << "\"\t";
391   if (offset)
392     OS << '+' << offset;
393   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
394     OS << " [" << I.start() << ';' << I.stop() << "):";
395     if (I.value() == ~0u)
396       OS << "undef";
397     else
398       OS << I.value();
399   }
400   for (unsigned i = 0, e = locations.size(); i != e; ++i) {
401     OS << " Loc" << i << '=';
402     locations[i].print(OS, TRI);
403   }
404   OS << '\n';
405 }
406
407 void LDVImpl::print(raw_ostream &OS) {
408   OS << "********** DEBUG VARIABLES **********\n";
409   for (unsigned i = 0, e = userValues.size(); i != e; ++i)
410     userValues[i]->print(OS, TRI);
411 }
412
413 void UserValue::coalesceLocation(unsigned LocNo) {
414   unsigned KeepLoc = std::find(locations.begin(), locations.begin() + LocNo,
415                                locations[LocNo]) - locations.begin();
416   unsigned EraseLoc = LocNo;
417   if (KeepLoc == LocNo) {
418     EraseLoc = std::find(locations.begin() + LocNo + 1, locations.end(),
419                          locations[LocNo]) - locations.begin();
420     // No matches.
421     if (EraseLoc == locations.size())
422       return;
423   }
424   assert(KeepLoc < EraseLoc);
425   locations.erase(locations.begin() + EraseLoc);
426
427   // Rewrite values.
428   for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
429     unsigned v = I.value();
430     if (v == EraseLoc)
431       I.setValue(KeepLoc);      // Coalesce when possible.
432     else if (v > EraseLoc)
433       I.setValueUnchecked(v-1); // Avoid coalescing with untransformed values.
434   }
435 }
436
437 UserValue *LDVImpl::getUserValue(const MDNode *Var, unsigned Offset) {
438   UserValue *&Leader = userVarMap[Var];
439   if (Leader) {
440     UserValue *UV = Leader->getLeader();
441     Leader = UV;
442     for (; UV; UV = UV->getNext())
443       if (UV->match(Var, Offset))
444         return UV;
445   }
446
447   UserValue *UV = new UserValue(Var, Offset, allocator);
448   userValues.push_back(UV);
449   Leader = UserValue::merge(Leader, UV);
450   return UV;
451 }
452
453 void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
454   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
455   UserValue *&Leader = virtRegToEqClass[VirtReg];
456   Leader = UserValue::merge(Leader, EC);
457 }
458
459 UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
460   if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
461     return UV->getLeader();
462   return 0;
463 }
464
465 bool LDVImpl::handleDebugValue(MachineInstr *MI, SlotIndex Idx) {
466   // DBG_VALUE loc, offset, variable
467   if (MI->getNumOperands() != 3 ||
468       !MI->getOperand(1).isImm() || !MI->getOperand(2).isMetadata()) {
469     DEBUG(dbgs() << "Can't handle " << *MI);
470     return false;
471   }
472
473   // Get or create the UserValue for (variable,offset).
474   unsigned Offset = MI->getOperand(1).getImm();
475   const MDNode *Var = MI->getOperand(2).getMetadata();
476   UserValue *UV = getUserValue(Var, Offset);
477
478   // If the location is a virtual register, make sure it is mapped.
479   if (MI->getOperand(0).isReg()) {
480     unsigned Reg = MI->getOperand(0).getReg();
481     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg))
482       mapVirtReg(Reg, UV);
483   }
484
485   UV->addDef(Idx, MI->getOperand(0));
486   return true;
487 }
488
489 bool LDVImpl::collectDebugValues(MachineFunction &mf) {
490   bool Changed = false;
491   for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
492        ++MFI) {
493     MachineBasicBlock *MBB = MFI;
494     for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
495          MBBI != MBBE;) {
496       if (!MBBI->isDebugValue()) {
497         ++MBBI;
498         continue;
499       }
500       // DBG_VALUE has no slot index, use the previous instruction instead.
501       SlotIndex Idx = MBBI == MBB->begin() ?
502         LIS->getMBBStartIdx(MBB) :
503         LIS->getInstructionIndex(llvm::prior(MBBI)).getDefIndex();
504       // Handle consecutive DBG_VALUE instructions with the same slot index.
505       do {
506         if (handleDebugValue(MBBI, Idx)) {
507           MBBI = MBB->erase(MBBI);
508           Changed = true;
509         } else
510           ++MBBI;
511       } while (MBBI != MBBE && MBBI->isDebugValue());
512     }
513   }
514   return Changed;
515 }
516
517 void UserValue::extendDef(SlotIndex Idx, unsigned LocNo,
518                           LiveInterval *LI, const VNInfo *VNI,
519                           LiveIntervals &LIS, MachineDominatorTree &MDT) {
520   SmallVector<SlotIndex, 16> Todo;
521   Todo.push_back(Idx);
522
523   do {
524     SlotIndex Start = Todo.pop_back_val();
525     MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
526     SlotIndex Stop = LIS.getMBBEndIdx(MBB);
527     LocMap::iterator I = locInts.find(Idx);
528
529     // Limit to VNI's live range.
530     bool ToEnd = true;
531     if (LI && VNI) {
532       LiveRange *Range = LI->getLiveRangeContaining(Start);
533       if (!Range || Range->valno != VNI)
534         continue;
535       if (Range->end < Stop)
536         Stop = Range->end, ToEnd = false;
537     }
538
539     // There could already be a short def at Start.
540     if (I.valid() && I.start() <= Start) {
541       // Stop when meeting a different location or an already extended interval.
542       Start = Start.getNextSlot();
543       if (I.value() != LocNo || I.stop() != Start)
544         continue;
545       // This is a one-slot placeholder. Just skip it.
546       ++I;
547     }
548
549     // Limited by the next def.
550     if (I.valid() && I.start() < Stop)
551       Stop = I.start(), ToEnd = false;
552
553     if (Start >= Stop)
554       continue;
555
556     I.insert(Start, Stop, LocNo);
557
558     // If we extended to the MBB end, propagate down the dominator tree.
559     if (!ToEnd)
560       continue;
561     const std::vector<MachineDomTreeNode*> &Children =
562       MDT.getNode(MBB)->getChildren();
563     for (unsigned i = 0, e = Children.size(); i != e; ++i)
564       Todo.push_back(LIS.getMBBStartIdx(Children[i]->getBlock()));
565   } while (!Todo.empty());
566 }
567
568 void
569 UserValue::computeIntervals(LiveIntervals &LIS, MachineDominatorTree &MDT) {
570   SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs;
571
572   // Collect all defs to be extended (Skipping undefs).
573   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
574     if (I.value() != ~0u)
575       Defs.push_back(std::make_pair(I.start(), I.value()));
576
577   for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
578     SlotIndex Idx = Defs[i].first;
579     unsigned LocNo = Defs[i].second;
580     const Location &Loc = locations[LocNo];
581
582     // Register locations are constrained to where the register value is live.
583     if (Loc.isReg() && LIS.hasInterval(Loc.Kind)) {
584       LiveInterval *LI = &LIS.getInterval(Loc.Kind);
585       const VNInfo *VNI = LI->getVNInfoAt(Idx);
586       extendDef(Idx, LocNo, LI, VNI, LIS, MDT);
587     } else
588       extendDef(Idx, LocNo, 0, 0, LIS, MDT);
589   }
590
591   // Finally, erase all the undefs.
592   for (LocMap::iterator I = locInts.begin(); I.valid();)
593     if (I.value() == ~0u)
594       I.erase();
595     else
596       ++I;
597 }
598
599 void LDVImpl::computeIntervals() {
600   for (unsigned i = 0, e = userValues.size(); i != e; ++i)
601     userValues[i]->computeIntervals(*LIS, *MDT);
602 }
603
604 bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
605   MF = &mf;
606   LIS = &pass.getAnalysis<LiveIntervals>();
607   MDT = &pass.getAnalysis<MachineDominatorTree>();
608   TRI = mf.getTarget().getRegisterInfo();
609   clear();
610   DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
611                << ((Value*)mf.getFunction())->getName()
612                << " **********\n");
613
614   bool Changed = collectDebugValues(mf);
615   computeIntervals();
616   DEBUG(print(dbgs()));
617   return Changed;
618 }
619
620 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
621   if (!pImpl)
622     pImpl = new LDVImpl(this);
623   return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
624 }
625
626 void LiveDebugVariables::releaseMemory() {
627   if (pImpl)
628     static_cast<LDVImpl*>(pImpl)->clear();
629 }
630
631 LiveDebugVariables::~LiveDebugVariables() {
632   if (pImpl)
633     delete static_cast<LDVImpl*>(pImpl);
634 }
635
636 void UserValue::
637 renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx,
638                const TargetRegisterInfo *TRI) {
639   for (unsigned i = locations.size(); i; --i) {
640     unsigned LocNo = i - 1;
641     Location &Loc = locations[LocNo];
642     if (Loc.Kind != OldReg)
643       continue;
644     Loc.Kind = NewReg;
645     if (SubIdx && Loc.Data.SubIdx)
646       Loc.Data.SubIdx = TRI->composeSubRegIndices(SubIdx, Loc.Data.SubIdx);
647     coalesceLocation(LocNo);
648   }
649 }
650
651 void LDVImpl::
652 renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx) {
653   UserValue *UV = lookupVirtReg(OldReg);
654   if (!UV)
655     return;
656
657   if (TargetRegisterInfo::isVirtualRegister(NewReg))
658     mapVirtReg(NewReg, UV);
659   virtRegToEqClass.erase(OldReg);
660
661   do {
662     UV->renameRegister(OldReg, NewReg, SubIdx, TRI);
663     UV = UV->getNext();
664   } while (UV);
665 }
666
667 void LiveDebugVariables::
668 renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx) {
669   if (pImpl)
670     static_cast<LDVImpl*>(pImpl)->renameRegister(OldReg, NewReg, SubIdx);
671 }
672
673 void
674 UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI) {
675   // Iterate over locations in reverse makes it easier to handle coalescing.
676   for (unsigned i = locations.size(); i ; --i) {
677     unsigned LocNo = i-1;
678     Location &Loc = locations[LocNo];
679     // Only virtual registers are rewritten.
680     if (!Loc.isReg() || !TargetRegisterInfo::isVirtualRegister(Loc.Kind))
681       continue;
682     unsigned VirtReg = Loc.Kind;
683     if (VRM.isAssignedReg(VirtReg)) {
684       unsigned PhysReg = VRM.getPhys(VirtReg);
685       if (Loc.Data.SubIdx)
686         PhysReg = TRI.getSubReg(PhysReg, Loc.Data.SubIdx);
687       Loc.Kind = PhysReg;
688       Loc.Data.SubIdx = 0;
689     } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
690       Loc.Kind = ~VRM.getStackSlot(VirtReg);
691       // FIXME: Translate SubIdx to a stackslot offset.
692       Loc.Data.Offset = 0;
693     } else {
694       Loc.Kind = Location::locUndef;
695     }
696     coalesceLocation(LocNo);
697   }
698   DEBUG(print(dbgs(), &TRI));
699 }
700
701 /// findInsertLocation - Find an iterator and DebugLoc for inserting a DBG_VALUE
702 /// instruction.
703 static MachineBasicBlock::iterator
704 findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx, DebugLoc &DL,
705                    LiveIntervals &LIS) {
706   SlotIndex Start = LIS.getMBBStartIdx(MBB);
707   Idx = Idx.getBaseIndex();
708
709   // Try to find an insert location by going backwards from Idx.
710   MachineInstr *MI;
711   while (!(MI = LIS.getInstructionFromIndex(Idx))) {
712     // We've reached the beginning of MBB.
713     if (Idx == Start) {
714       MachineBasicBlock::iterator I = MBB->SkipPHIsAndLabels(MBB->begin());
715       if (I != MBB->end())
716         DL = I->getDebugLoc();
717       return I;
718     }
719     Idx = Idx.getPrevIndex();
720   }
721   // We found an instruction. The insert point is after the instr.
722   DL = MI->getDebugLoc();
723   return llvm::next(MachineBasicBlock::iterator(MI));
724 }
725
726 void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx,
727                                  unsigned LocNo,
728                                  LiveIntervals &LIS,
729                                  const TargetInstrInfo &TII) {
730   DebugLoc DL;
731   MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, DL, LIS);
732   Location &Loc = locations[LocNo];
733
734   // Frame index locations may require a target callback.
735   if (Loc.isFrameIndex()) {
736     MachineInstr *MI = TII.emitFrameIndexDebugValue(*MBB->getParent(),
737                                           Loc.getFrameIndex(),
738                                           offset, variable, DL);
739     if (MI) {
740       MBB->insert(I, MI);
741       return;
742     }
743   }
744   // This is not a frame index, or the target is happy with a standard FI.
745   Loc.addOperand(BuildMI(*MBB, I, DL, TII.get(TargetOpcode::DBG_VALUE)))
746     .addImm(offset).addMetadata(variable);
747 }
748
749 void UserValue::insertDebugKill(MachineBasicBlock *MBB, SlotIndex Idx,
750                                LiveIntervals &LIS, const TargetInstrInfo &TII) {
751   DebugLoc DL;
752   MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, DL, LIS);
753   BuildMI(*MBB, I, DL, TII.get(TargetOpcode::DBG_VALUE)).addReg(0)
754     .addImm(offset).addMetadata(variable);
755 }
756
757 void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
758                                 const TargetInstrInfo &TII) {
759   MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
760
761   for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
762     SlotIndex Start = I.start();
763     SlotIndex Stop = I.stop();
764     unsigned LocNo = I.value();
765     DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo);
766     MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
767     SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB);
768
769     DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
770     insertDebugValue(MBB, Start, LocNo, LIS, TII);
771
772     // This interval may span multiple basic blocks.
773     // Insert a DBG_VALUE into each one.
774     while(Stop > MBBEnd) {
775       // Move to the next block.
776       Start = MBBEnd;
777       if (++MBB == MFEnd)
778         break;
779       MBBEnd = LIS.getMBBEndIdx(MBB);
780       DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
781       insertDebugValue(MBB, Start, LocNo, LIS, TII);
782     }
783     DEBUG(dbgs() << '\n');
784     if (MBB == MFEnd)
785       break;
786
787     ++I;
788     if (Stop == MBBEnd)
789       continue;
790     // The current interval ends before MBB.
791     // Insert a kill if there is a gap.
792     if (!I.valid() || I.start() > Stop)
793       insertDebugKill(MBB, Stop, LIS, TII);
794   }
795 }
796
797 void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
798   DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
799   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
800   for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
801     userValues[i]->rewriteLocations(*VRM, *TRI);
802     userValues[i]->emitDebugValues(VRM, *LIS, *TII);
803   }
804 }
805
806 void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
807   if (pImpl)
808     static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
809 }
810
811
812 #ifndef NDEBUG
813 void LiveDebugVariables::dump() {
814   if (pImpl)
815     static_cast<LDVImpl*>(pImpl)->print(dbgs());
816 }
817 #endif
818