1 //===- LiveDebugVariables.cpp - Tracking debug info variables -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LiveDebugVariables analysis.
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.
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.
20 //===----------------------------------------------------------------------===//
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/Analysis/DebugInfo.h"
29 #include "llvm/ADT/IntervalMap.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/CodeGen/LexicalScopes.h"
32 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
33 #include "llvm/CodeGen/MachineDominators.h"
34 #include "llvm/CodeGen/MachineFunction.h"
35 #include "llvm/CodeGen/MachineInstrBuilder.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/Passes.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
47 EnableLDV("live-debug-variables", cl::init(true),
48 cl::desc("Enable the live debug variables pass"), cl::Hidden);
50 STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
51 char LiveDebugVariables::ID = 0;
53 INITIALIZE_PASS_BEGIN(LiveDebugVariables, "livedebugvars",
54 "Debug Variable Analysis", false, false)
55 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
56 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
57 INITIALIZE_PASS_END(LiveDebugVariables, "livedebugvars",
58 "Debug Variable Analysis", false, false)
60 void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
61 AU.addRequired<MachineDominatorTree>();
62 AU.addRequiredTransitive<LiveIntervals>();
64 MachineFunctionPass::getAnalysisUsage(AU);
67 LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID), pImpl(0) {
68 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
71 /// LocMap - Map of where a user value is live, and its location.
72 typedef IntervalMap<SlotIndex, unsigned, 4> LocMap;
74 /// UserValue - A user value is a part of a debug info user variable.
76 /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
77 /// holds part of a user variable. The part is identified by a byte offset.
79 /// UserValues are grouped into equivalence classes for easier searching. Two
80 /// user values are related if they refer to the same variable, or if they are
81 /// held by the same virtual register. The equivalence class is the transitive
82 /// closure of that relation.
86 const MDNode *variable; ///< The debug info variable we are part of.
87 unsigned offset; ///< Byte offset into variable.
88 DebugLoc dl; ///< The debug location for the variable. This is
89 ///< used by dwarf writer to find lexical scope.
90 UserValue *leader; ///< Equivalence class leader.
91 UserValue *next; ///< Next value in equivalence class, or null.
93 /// Numbered locations referenced by locmap.
94 SmallVector<MachineOperand, 4> locations;
96 /// Map of slot indices where this value is live.
99 /// coalesceLocation - After LocNo was changed, check if it has become
100 /// identical to another location, and coalesce them. This may cause LocNo or
101 /// a later location to be erased, but no earlier location will be erased.
102 void coalesceLocation(unsigned LocNo);
104 /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo.
105 void insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, unsigned LocNo,
106 LiveIntervals &LIS, const TargetInstrInfo &TII);
108 /// splitLocation - Replace OldLocNo ranges with NewRegs ranges where NewRegs
109 /// is live. Returns true if any changes were made.
110 bool splitLocation(unsigned OldLocNo, ArrayRef<LiveInterval*> NewRegs);
113 /// UserValue - Create a new UserValue.
114 UserValue(const MDNode *var, unsigned o, DebugLoc L,
115 LocMap::Allocator &alloc)
116 : variable(var), offset(o), dl(L), leader(this), next(0), locInts(alloc)
119 /// getLeader - Get the leader of this value's equivalence class.
120 UserValue *getLeader() {
121 UserValue *l = leader;
122 while (l != l->leader)
127 /// getNext - Return the next UserValue in the equivalence class.
128 UserValue *getNext() const { return next; }
130 /// match - Does this UserValue match the parameters?
131 bool match(const MDNode *Var, unsigned Offset) const {
132 return Var == variable && Offset == offset;
135 /// merge - Merge equivalence classes.
136 static UserValue *merge(UserValue *L1, UserValue *L2) {
137 L2 = L2->getLeader();
140 L1 = L1->getLeader();
143 // Splice L2 before L1's members.
146 End->leader = L1, End = End->next;
148 End->next = L1->next;
153 /// getLocationNo - Return the location number that matches Loc.
154 unsigned getLocationNo(const MachineOperand &LocMO) {
156 if (LocMO.getReg() == 0)
158 // For register locations we dont care about use/def and other flags.
159 for (unsigned i = 0, e = locations.size(); i != e; ++i)
160 if (locations[i].isReg() &&
161 locations[i].getReg() == LocMO.getReg() &&
162 locations[i].getSubReg() == LocMO.getSubReg())
165 for (unsigned i = 0, e = locations.size(); i != e; ++i)
166 if (LocMO.isIdenticalTo(locations[i]))
168 locations.push_back(LocMO);
169 // We are storing a MachineOperand outside a MachineInstr.
170 locations.back().clearParent();
171 // Don't store def operands.
172 if (locations.back().isReg())
173 locations.back().setIsUse();
174 return locations.size() - 1;
177 /// mapVirtRegs - Ensure that all virtual register locations are mapped.
178 void mapVirtRegs(LDVImpl *LDV);
180 /// addDef - Add a definition point to this value.
181 void addDef(SlotIndex Idx, const MachineOperand &LocMO) {
182 // Add a singular (Idx,Idx) -> Loc mapping.
183 LocMap::iterator I = locInts.find(Idx);
184 if (!I.valid() || I.start() != Idx)
185 I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO));
187 // A later DBG_VALUE at the same SlotIndex overrides the old location.
188 I.setValue(getLocationNo(LocMO));
191 /// extendDef - Extend the current definition as far as possible down the
192 /// dominator tree. Stop when meeting an existing def or when leaving the live
194 /// End points where VNI is no longer live are added to Kills.
195 /// @param Idx Starting point for the definition.
196 /// @param LocNo Location number to propagate.
197 /// @param LI Restrict liveness to where LI has the value VNI. May be null.
198 /// @param VNI When LI is not null, this is the value to restrict to.
199 /// @param Kills Append end points of VNI's live range to Kills.
200 /// @param LIS Live intervals analysis.
201 /// @param MDT Dominator tree.
202 void extendDef(SlotIndex Idx, unsigned LocNo,
203 LiveInterval *LI, const VNInfo *VNI,
204 SmallVectorImpl<SlotIndex> *Kills,
205 LiveIntervals &LIS, MachineDominatorTree &MDT,
208 /// addDefsFromCopies - The value in LI/LocNo may be copies to other
209 /// registers. Determine if any of the copies are available at the kill
210 /// points, and add defs if possible.
211 /// @param LI Scan for copies of the value in LI->reg.
212 /// @param LocNo Location number of LI->reg.
213 /// @param Kills Points where the range of LocNo could be extended.
214 /// @param NewDefs Append (Idx, LocNo) of inserted defs here.
215 void addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
216 const SmallVectorImpl<SlotIndex> &Kills,
217 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
218 MachineRegisterInfo &MRI,
221 /// computeIntervals - Compute the live intervals of all locations after
222 /// collecting all their def points.
223 void computeIntervals(MachineRegisterInfo &MRI,
224 LiveIntervals &LIS, MachineDominatorTree &MDT,
227 /// renameRegister - Update locations to rewrite OldReg as NewReg:SubIdx.
228 void renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx,
229 const TargetRegisterInfo *TRI);
231 /// splitRegister - Replace OldReg ranges with NewRegs ranges where NewRegs is
232 /// live. Returns true if any changes were made.
233 bool splitRegister(unsigned OldLocNo, ArrayRef<LiveInterval*> NewRegs);
235 /// rewriteLocations - Rewrite virtual register locations according to the
236 /// provided virtual register map.
237 void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI);
239 /// emitDebugVariables - Recreate DBG_VALUE instruction from data structures.
240 void emitDebugValues(VirtRegMap *VRM,
241 LiveIntervals &LIS, const TargetInstrInfo &TRI);
243 /// findDebugLoc - Return DebugLoc used for this DBG_VALUE instruction. A
244 /// variable may have more than one corresponding DBG_VALUE instructions.
245 /// Only first one needs DebugLoc to identify variable's lexical scope
247 DebugLoc findDebugLoc();
248 void print(raw_ostream&, const TargetMachine*);
252 /// LDVImpl - Implementation of the LiveDebugVariables pass.
255 LiveDebugVariables &pass;
256 LocMap::Allocator allocator;
260 MachineDominatorTree *MDT;
261 const TargetRegisterInfo *TRI;
263 /// userValues - All allocated UserValue instances.
264 SmallVector<UserValue*, 8> userValues;
266 /// Map virtual register to eq class leader.
267 typedef DenseMap<unsigned, UserValue*> VRMap;
268 VRMap virtRegToEqClass;
270 /// Map user variable to eq class leader.
271 typedef DenseMap<const MDNode *, UserValue*> UVMap;
274 /// getUserValue - Find or create a UserValue.
275 UserValue *getUserValue(const MDNode *Var, unsigned Offset, DebugLoc DL);
277 /// lookupVirtReg - Find the EC leader for VirtReg or null.
278 UserValue *lookupVirtReg(unsigned VirtReg);
280 /// handleDebugValue - Add DBG_VALUE instruction to our maps.
281 /// @param MI DBG_VALUE instruction
282 /// @param Idx Last valid SLotIndex before instruction.
283 /// @return True if the DBG_VALUE instruction should be deleted.
284 bool handleDebugValue(MachineInstr *MI, SlotIndex Idx);
286 /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
287 /// a UserValue def for each instruction.
288 /// @param mf MachineFunction to be scanned.
289 /// @return True if any debug values were found.
290 bool collectDebugValues(MachineFunction &mf);
292 /// computeIntervals - Compute the live intervals of all user values after
293 /// collecting all their def points.
294 void computeIntervals();
297 LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
298 bool runOnMachineFunction(MachineFunction &mf);
300 /// clear - Relase all memory.
302 DeleteContainerPointers(userValues);
304 virtRegToEqClass.clear();
308 /// mapVirtReg - Map virtual register to an equivalence class.
309 void mapVirtReg(unsigned VirtReg, UserValue *EC);
311 /// renameRegister - Replace all references to OldReg with NewReg:SubIdx.
312 void renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx);
314 /// splitRegister - Replace all references to OldReg with NewRegs.
315 void splitRegister(unsigned OldReg, ArrayRef<LiveInterval*> NewRegs);
317 /// emitDebugVariables - Recreate DBG_VALUE instruction from data structures.
318 void emitDebugValues(VirtRegMap *VRM);
320 void print(raw_ostream&);
324 void UserValue::print(raw_ostream &OS, const TargetMachine *TM) {
325 DIVariable DV(variable);
327 DV.printExtendedName(OS);
331 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
332 OS << " [" << I.start() << ';' << I.stop() << "):";
333 if (I.value() == ~0u)
338 for (unsigned i = 0, e = locations.size(); i != e; ++i) {
339 OS << " Loc" << i << '=';
340 locations[i].print(OS, TM);
345 void LDVImpl::print(raw_ostream &OS) {
346 OS << "********** DEBUG VARIABLES **********\n";
347 for (unsigned i = 0, e = userValues.size(); i != e; ++i)
348 userValues[i]->print(OS, &MF->getTarget());
351 void UserValue::coalesceLocation(unsigned LocNo) {
352 unsigned KeepLoc = 0;
353 for (unsigned e = locations.size(); KeepLoc != e; ++KeepLoc) {
354 if (KeepLoc == LocNo)
356 if (locations[KeepLoc].isIdenticalTo(locations[LocNo]))
360 if (KeepLoc == locations.size())
363 // Keep the smaller location, erase the larger one.
364 unsigned EraseLoc = LocNo;
365 if (KeepLoc > EraseLoc)
366 std::swap(KeepLoc, EraseLoc);
367 locations.erase(locations.begin() + EraseLoc);
370 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
371 unsigned v = I.value();
373 I.setValue(KeepLoc); // Coalesce when possible.
374 else if (v > EraseLoc)
375 I.setValueUnchecked(v-1); // Avoid coalescing with untransformed values.
379 void UserValue::mapVirtRegs(LDVImpl *LDV) {
380 for (unsigned i = 0, e = locations.size(); i != e; ++i)
381 if (locations[i].isReg() &&
382 TargetRegisterInfo::isVirtualRegister(locations[i].getReg()))
383 LDV->mapVirtReg(locations[i].getReg(), this);
386 UserValue *LDVImpl::getUserValue(const MDNode *Var, unsigned Offset,
388 UserValue *&Leader = userVarMap[Var];
390 UserValue *UV = Leader->getLeader();
392 for (; UV; UV = UV->getNext())
393 if (UV->match(Var, Offset))
397 UserValue *UV = new UserValue(Var, Offset, DL, allocator);
398 userValues.push_back(UV);
399 Leader = UserValue::merge(Leader, UV);
403 void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
404 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
405 UserValue *&Leader = virtRegToEqClass[VirtReg];
406 Leader = UserValue::merge(Leader, EC);
409 UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
410 if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
411 return UV->getLeader();
415 bool LDVImpl::handleDebugValue(MachineInstr *MI, SlotIndex Idx) {
416 // DBG_VALUE loc, offset, variable
417 if (MI->getNumOperands() != 3 ||
418 !MI->getOperand(1).isImm() || !MI->getOperand(2).isMetadata()) {
419 DEBUG(dbgs() << "Can't handle " << *MI);
423 // Get or create the UserValue for (variable,offset).
424 unsigned Offset = MI->getOperand(1).getImm();
425 const MDNode *Var = MI->getOperand(2).getMetadata();
426 UserValue *UV = getUserValue(Var, Offset, MI->getDebugLoc());
427 UV->addDef(Idx, MI->getOperand(0));
431 bool LDVImpl::collectDebugValues(MachineFunction &mf) {
432 bool Changed = false;
433 for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
435 MachineBasicBlock *MBB = MFI;
436 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
438 if (!MBBI->isDebugValue()) {
442 // DBG_VALUE has no slot index, use the previous instruction instead.
443 SlotIndex Idx = MBBI == MBB->begin() ?
444 LIS->getMBBStartIdx(MBB) :
445 LIS->getInstructionIndex(llvm::prior(MBBI)).getDefIndex();
446 // Handle consecutive DBG_VALUE instructions with the same slot index.
448 if (handleDebugValue(MBBI, Idx)) {
449 MBBI = MBB->erase(MBBI);
453 } while (MBBI != MBBE && MBBI->isDebugValue());
459 void UserValue::extendDef(SlotIndex Idx, unsigned LocNo,
460 LiveInterval *LI, const VNInfo *VNI,
461 SmallVectorImpl<SlotIndex> *Kills,
462 LiveIntervals &LIS, MachineDominatorTree &MDT,
464 SmallVector<SlotIndex, 16> Todo;
466 SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
467 LS.getMachineBasicBlocks(dl, LBlocks);
469 SlotIndex Start = Todo.pop_back_val();
470 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
471 SlotIndex Stop = LIS.getMBBEndIdx(MBB);
472 LocMap::iterator I = locInts.find(Start);
474 // Limit to VNI's live range.
477 LiveRange *Range = LI->getLiveRangeContaining(Start);
478 if (!Range || Range->valno != VNI) {
480 Kills->push_back(Start);
483 if (Range->end < Stop)
484 Stop = Range->end, ToEnd = false;
487 // There could already be a short def at Start.
488 if (I.valid() && I.start() <= Start) {
489 // Stop when meeting a different location or an already extended interval.
490 Start = Start.getNextSlot();
491 if (I.value() != LocNo || I.stop() != Start)
493 // This is a one-slot placeholder. Just skip it.
497 // Limited by the next def.
498 if (I.valid() && I.start() < Stop)
499 Stop = I.start(), ToEnd = false;
500 // Limited by VNI's live range.
501 else if (!ToEnd && Kills)
502 Kills->push_back(Stop);
507 I.insert(Start, Stop, LocNo);
509 // If we extended to the MBB end, propagate down the dominator tree.
512 const std::vector<MachineDomTreeNode*> &Children =
513 MDT.getNode(MBB)->getChildren();
514 for (unsigned i = 0, e = Children.size(); i != e; ++i) {
515 MachineBasicBlock *MBB = Children[i]->getBlock();
516 if (LBlocks.count(MBB) != 0 || LS.dominates(dl, MBB))
517 Todo.push_back(LIS.getMBBStartIdx(MBB));
519 } while (!Todo.empty());
523 UserValue::addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
524 const SmallVectorImpl<SlotIndex> &Kills,
525 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
526 MachineRegisterInfo &MRI, LiveIntervals &LIS) {
529 // Don't track copies from physregs, there are too many uses.
530 if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
533 // Collect all the (vreg, valno) pairs that are copies of LI.
534 SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
535 for (MachineRegisterInfo::use_nodbg_iterator
536 UI = MRI.use_nodbg_begin(LI->reg),
537 UE = MRI.use_nodbg_end(); UI != UE; ++UI) {
538 // Copies of the full value.
539 if (UI.getOperand().getSubReg() || !UI->isCopy())
541 MachineInstr *MI = &*UI;
542 unsigned DstReg = MI->getOperand(0).getReg();
544 // Don't follow copies to physregs. These are usually setting up call
545 // arguments, and the argument registers are always call clobbered. We are
546 // better off in the source register which could be a callee-saved register,
547 // or it could be spilled.
548 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
551 // Is LocNo extended to reach this copy? If not, another def may be blocking
552 // it, or we are looking at a wrong value of LI.
553 SlotIndex Idx = LIS.getInstructionIndex(MI);
554 LocMap::iterator I = locInts.find(Idx.getUseIndex());
555 if (!I.valid() || I.value() != LocNo)
558 if (!LIS.hasInterval(DstReg))
560 LiveInterval *DstLI = &LIS.getInterval(DstReg);
561 const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getDefIndex());
562 assert(DstVNI && DstVNI->def == Idx.getDefIndex() && "Bad copy value");
563 CopyValues.push_back(std::make_pair(DstLI, DstVNI));
566 if (CopyValues.empty())
569 DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI << '\n');
571 // Try to add defs of the copied values for each kill point.
572 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
573 SlotIndex Idx = Kills[i];
574 for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
575 LiveInterval *DstLI = CopyValues[j].first;
576 const VNInfo *DstVNI = CopyValues[j].second;
577 if (DstLI->getVNInfoAt(Idx) != DstVNI)
579 // Check that there isn't already a def at Idx
580 LocMap::iterator I = locInts.find(Idx);
581 if (I.valid() && I.start() <= Idx)
583 DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
584 << DstVNI->id << " in " << *DstLI << '\n');
585 MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
586 assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
587 unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
588 I.insert(Idx, Idx.getNextSlot(), LocNo);
589 NewDefs.push_back(std::make_pair(Idx, LocNo));
596 UserValue::computeIntervals(MachineRegisterInfo &MRI,
598 MachineDominatorTree &MDT,
600 SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs;
602 // Collect all defs to be extended (Skipping undefs).
603 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
604 if (I.value() != ~0u)
605 Defs.push_back(std::make_pair(I.start(), I.value()));
607 // Extend all defs, and possibly add new ones along the way.
608 for (unsigned i = 0; i != Defs.size(); ++i) {
609 SlotIndex Idx = Defs[i].first;
610 unsigned LocNo = Defs[i].second;
611 const MachineOperand &Loc = locations[LocNo];
613 // Register locations are constrained to where the register value is live.
614 if (Loc.isReg() && LIS.hasInterval(Loc.getReg())) {
615 LiveInterval *LI = &LIS.getInterval(Loc.getReg());
616 const VNInfo *VNI = LI->getVNInfoAt(Idx);
617 SmallVector<SlotIndex, 16> Kills;
618 extendDef(Idx, LocNo, LI, VNI, &Kills, LIS, MDT, LS);
619 addDefsFromCopies(LI, LocNo, Kills, Defs, MRI, LIS);
621 extendDef(Idx, LocNo, 0, 0, 0, LIS, MDT, LS);
624 // Finally, erase all the undefs.
625 for (LocMap::iterator I = locInts.begin(); I.valid();)
626 if (I.value() == ~0u)
632 void LDVImpl::computeIntervals() {
633 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
634 userValues[i]->computeIntervals(MF->getRegInfo(), *LIS, *MDT, LS);
635 userValues[i]->mapVirtRegs(this);
639 bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
641 LIS = &pass.getAnalysis<LiveIntervals>();
642 MDT = &pass.getAnalysis<MachineDominatorTree>();
643 TRI = mf.getTarget().getRegisterInfo();
646 DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
647 << ((Value*)mf.getFunction())->getName()
650 bool Changed = collectDebugValues(mf);
652 DEBUG(print(dbgs()));
657 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
661 pImpl = new LDVImpl(this);
662 return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
665 void LiveDebugVariables::releaseMemory() {
667 static_cast<LDVImpl*>(pImpl)->clear();
670 LiveDebugVariables::~LiveDebugVariables() {
672 delete static_cast<LDVImpl*>(pImpl);
676 renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx,
677 const TargetRegisterInfo *TRI) {
678 for (unsigned i = locations.size(); i; --i) {
679 unsigned LocNo = i - 1;
680 MachineOperand &Loc = locations[LocNo];
681 if (!Loc.isReg() || Loc.getReg() != OldReg)
683 if (TargetRegisterInfo::isPhysicalRegister(NewReg))
684 Loc.substPhysReg(NewReg, *TRI);
686 Loc.substVirtReg(NewReg, SubIdx, *TRI);
687 coalesceLocation(LocNo);
692 renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx) {
693 UserValue *UV = lookupVirtReg(OldReg);
697 if (TargetRegisterInfo::isVirtualRegister(NewReg))
698 mapVirtReg(NewReg, UV);
699 virtRegToEqClass.erase(OldReg);
702 UV->renameRegister(OldReg, NewReg, SubIdx, TRI);
707 void LiveDebugVariables::
708 renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx) {
710 static_cast<LDVImpl*>(pImpl)->renameRegister(OldReg, NewReg, SubIdx);
713 //===----------------------------------------------------------------------===//
714 // Live Range Splitting
715 //===----------------------------------------------------------------------===//
718 UserValue::splitLocation(unsigned OldLocNo, ArrayRef<LiveInterval*> NewRegs) {
720 dbgs() << "Splitting Loc" << OldLocNo << '\t';
723 bool DidChange = false;
724 LocMap::iterator LocMapI;
725 LocMapI.setMap(locInts);
726 for (unsigned i = 0; i != NewRegs.size(); ++i) {
727 LiveInterval *LI = NewRegs[i];
731 // Don't allocate the new LocNo until it is needed.
732 unsigned NewLocNo = ~0u;
734 // Iterate over the overlaps between locInts and LI.
735 LocMapI.find(LI->beginIndex());
736 if (!LocMapI.valid())
738 LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
739 LiveInterval::iterator LIE = LI->end();
740 while (LocMapI.valid() && LII != LIE) {
741 // At this point, we know that LocMapI.stop() > LII->start.
742 LII = LI->advanceTo(LII, LocMapI.start());
746 // Now LII->end > LocMapI.start(). Do we have an overlap?
747 if (LocMapI.value() == OldLocNo && LII->start < LocMapI.stop()) {
748 // Overlapping correct location. Allocate NewLocNo now.
749 if (NewLocNo == ~0u) {
750 MachineOperand MO = MachineOperand::CreateReg(LI->reg, false);
751 MO.setSubReg(locations[OldLocNo].getSubReg());
752 NewLocNo = getLocationNo(MO);
756 SlotIndex LStart = LocMapI.start();
757 SlotIndex LStop = LocMapI.stop();
759 // Trim LocMapI down to the LII overlap.
760 if (LStart < LII->start)
761 LocMapI.setStartUnchecked(LII->start);
762 if (LStop > LII->end)
763 LocMapI.setStopUnchecked(LII->end);
765 // Change the value in the overlap. This may trigger coalescing.
766 LocMapI.setValue(NewLocNo);
768 // Re-insert any removed OldLocNo ranges.
769 if (LStart < LocMapI.start()) {
770 LocMapI.insert(LStart, LocMapI.start(), OldLocNo);
772 assert(LocMapI.valid() && "Unexpected coalescing");
774 if (LStop > LocMapI.stop()) {
776 LocMapI.insert(LII->end, LStop, OldLocNo);
781 // Advance to the next overlap.
782 if (LII->end < LocMapI.stop()) {
785 LocMapI.advanceTo(LII->start);
788 if (!LocMapI.valid())
790 LII = LI->advanceTo(LII, LocMapI.start());
795 // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
796 locations.erase(locations.begin() + OldLocNo);
798 while (LocMapI.valid()) {
799 unsigned v = LocMapI.value();
801 DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
802 << LocMapI.stop() << ")\n");
806 LocMapI.setValueUnchecked(v-1);
811 DEBUG({dbgs() << "Split result: \t"; print(dbgs(), 0);});
816 UserValue::splitRegister(unsigned OldReg, ArrayRef<LiveInterval*> NewRegs) {
817 bool DidChange = false;
818 // Split locations referring to OldReg. Iterate backwards so splitLocation can
819 // safely erase unuused locations.
820 for (unsigned i = locations.size(); i ; --i) {
821 unsigned LocNo = i-1;
822 const MachineOperand *Loc = &locations[LocNo];
823 if (!Loc->isReg() || Loc->getReg() != OldReg)
825 DidChange |= splitLocation(LocNo, NewRegs);
830 void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<LiveInterval*> NewRegs) {
831 bool DidChange = false;
832 for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
833 DidChange |= UV->splitRegister(OldReg, NewRegs);
838 // Map all of the new virtual registers.
839 UserValue *UV = lookupVirtReg(OldReg);
840 for (unsigned i = 0; i != NewRegs.size(); ++i)
841 mapVirtReg(NewRegs[i]->reg, UV);
844 void LiveDebugVariables::
845 splitRegister(unsigned OldReg, ArrayRef<LiveInterval*> NewRegs) {
847 static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
851 UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI) {
852 // Iterate over locations in reverse makes it easier to handle coalescing.
853 for (unsigned i = locations.size(); i ; --i) {
854 unsigned LocNo = i-1;
855 MachineOperand &Loc = locations[LocNo];
856 // Only virtual registers are rewritten.
857 if (!Loc.isReg() || !Loc.getReg() ||
858 !TargetRegisterInfo::isVirtualRegister(Loc.getReg()))
860 unsigned VirtReg = Loc.getReg();
861 if (VRM.isAssignedReg(VirtReg) &&
862 TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) {
863 // This can create a %noreg operand in rare cases when the sub-register
864 // index is no longer available. That means the user value is in a
865 // non-existent sub-register, and %noreg is exactly what we want.
866 Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
867 } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT &&
868 VRM.isSpillSlotUsed(VRM.getStackSlot(VirtReg))) {
869 // FIXME: Translate SubIdx to a stackslot offset.
870 Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
875 coalesceLocation(LocNo);
879 /// findInsertLocation - Find an iterator for inserting a DBG_VALUE
881 static MachineBasicBlock::iterator
882 findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
883 LiveIntervals &LIS) {
884 SlotIndex Start = LIS.getMBBStartIdx(MBB);
885 Idx = Idx.getBaseIndex();
887 // Try to find an insert location by going backwards from Idx.
889 while (!(MI = LIS.getInstructionFromIndex(Idx))) {
890 // We've reached the beginning of MBB.
892 MachineBasicBlock::iterator I = MBB->SkipPHIsAndLabels(MBB->begin());
895 Idx = Idx.getPrevIndex();
898 // Don't insert anything after the first terminator, though.
899 return MI->getDesc().isTerminator() ? MBB->getFirstTerminator() :
900 llvm::next(MachineBasicBlock::iterator(MI));
903 DebugLoc UserValue::findDebugLoc() {
908 void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx,
911 const TargetInstrInfo &TII) {
912 MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS);
913 MachineOperand &Loc = locations[LocNo];
914 ++NumInsertedDebugValues;
916 // Frame index locations may require a target callback.
918 MachineInstr *MI = TII.emitFrameIndexDebugValue(*MBB->getParent(),
919 Loc.getIndex(), offset, variable,
926 // This is not a frame index, or the target is happy with a standard FI.
927 BuildMI(*MBB, I, findDebugLoc(), TII.get(TargetOpcode::DBG_VALUE))
928 .addOperand(Loc).addImm(offset).addMetadata(variable);
931 void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
932 const TargetInstrInfo &TII) {
933 MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
935 for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
936 SlotIndex Start = I.start();
937 SlotIndex Stop = I.stop();
938 unsigned LocNo = I.value();
939 DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo);
940 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
941 SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB);
943 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
944 insertDebugValue(MBB, Start, LocNo, LIS, TII);
945 // This interval may span multiple basic blocks.
946 // Insert a DBG_VALUE into each one.
947 while(Stop > MBBEnd) {
948 // Move to the next block.
952 MBBEnd = LIS.getMBBEndIdx(MBB);
953 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
954 insertDebugValue(MBB, Start, LocNo, LIS, TII);
956 DEBUG(dbgs() << '\n');
964 void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
965 DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
966 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
967 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
968 DEBUG(userValues[i]->print(dbgs(), &MF->getTarget()));
969 userValues[i]->rewriteLocations(*VRM, *TRI);
970 userValues[i]->emitDebugValues(VRM, *LIS, *TII);
974 void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
976 static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
981 void LiveDebugVariables::dump() {
983 static_cast<LDVImpl*>(pImpl)->print(dbgs());