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 "llvm/Constants.h"
25 #include "llvm/Metadata.h"
26 #include "llvm/Value.h"
27 #include "llvm/ADT/IntervalMap.h"
28 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineDominators.h"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
40 EnableLDV("live-debug-variables",
41 cl::desc("Enable the live debug variables pass"), cl::Hidden);
43 char LiveDebugVariables::ID = 0;
45 INITIALIZE_PASS_BEGIN(LiveDebugVariables, "livedebugvars",
46 "Debug Variable Analysis", false, false)
47 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
48 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
49 INITIALIZE_PASS_END(LiveDebugVariables, "livedebugvars",
50 "Debug Variable Analysis", false, false)
52 void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
53 AU.addRequired<MachineDominatorTree>();
54 AU.addRequiredTransitive<LiveIntervals>();
56 MachineFunctionPass::getAnalysisUsage(AU);
59 LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID), pImpl(0) {
60 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
63 /// Location - All the different places a user value can reside.
64 /// Note that this includes immediate values that technically aren't locations.
67 /// kind - What kind of location is this?
73 /// Kind - One of the following:
75 /// 2. Register number (physical or virtual), data.SubIdx is the subreg index.
76 /// 3. ~Frame index, data.Offset is the offset.
77 /// 4. locImm, data.ImmVal is the constant integer value.
78 /// 5. locFPImm, data.CFP points to the floating point constant.
81 /// Data - Extra data about location.
83 unsigned SubIdx; ///< For virtual registers.
84 int64_t Offset; ///< For frame indices.
85 int64_t ImmVal; ///< For locImm.
86 const ConstantFP *CFP; ///< For locFPImm.
89 Location(const MachineOperand &MO) {
90 switch(MO.getType()) {
91 case MachineOperand::MO_Register:
93 Data.SubIdx = MO.getSubReg();
95 case MachineOperand::MO_Immediate:
97 Data.ImmVal = MO.getImm();
99 case MachineOperand::MO_FPImmediate:
101 Data.CFP = MO.getFPImm();
103 case MachineOperand::MO_FrameIndex:
104 Kind = ~MO.getIndex();
105 // FIXME: MO_FrameIndex should support an offset.
114 bool operator==(const Location &RHS) const {
115 if (Kind != RHS.Kind)
121 return Data.ImmVal == RHS.Data.ImmVal;
123 return Data.CFP == RHS.Data.CFP;
126 return Data.SubIdx == RHS.Data.SubIdx;
128 return Data.Offset == RHS.Data.Offset;
132 /// isUndef - is this the singleton undef?
133 bool isUndef() const { return Kind == locUndef; }
135 /// isReg - is this a register location?
136 bool isReg() const { return Kind && Kind < locImm; }
138 void print(raw_ostream&, const TargetRegisterInfo*);
142 /// LocMap - Map of where a user value is live, and its location.
143 typedef IntervalMap<SlotIndex, unsigned, 4> LocMap;
145 /// UserValue - A user value is a part of a debug info user variable.
147 /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
148 /// holds part of a user variable. The part is identified by a byte offset.
150 /// UserValues are grouped into equivalence classes for easier searching. Two
151 /// user values are related if they refer to the same variable, or if they are
152 /// held by the same virtual register. The equivalence class is the transitive
153 /// closure of that relation.
156 const MDNode *variable; ///< The debug info variable we are part of.
157 unsigned offset; ///< Byte offset into variable.
159 UserValue *leader; ///< Equivalence class leader.
160 UserValue *next; ///< Next value in equivalence class, or null.
162 /// Numbered locations referenced by locmap.
163 SmallVector<Location, 4> locations;
165 /// Map of slot indices where this value is live.
169 /// UserValue - Create a new UserValue.
170 UserValue(const MDNode *var, unsigned o, LocMap::Allocator &alloc)
171 : variable(var), offset(o), leader(this), next(0), locInts(alloc)
174 /// getLeader - Get the leader of this value's equivalence class.
175 UserValue *getLeader() {
176 UserValue *l = leader;
177 while (l != l->leader)
182 /// getNext - Return the next UserValue in the equivalence class.
183 UserValue *getNext() const { return next; }
185 /// match - Does this UserValue match the aprameters?
186 bool match(const MDNode *Var, unsigned Offset) const {
187 return Var == variable && Offset == offset;
190 /// merge - Merge equivalence classes.
191 static UserValue *merge(UserValue *L1, UserValue *L2) {
192 L2 = L2->getLeader();
195 L1 = L1->getLeader();
198 // Splice L2 before L1's members.
201 End->leader = L1, End = End->next;
203 End->next = L1->next;
208 /// getLocationNo - Return the location number that matches Loc.
209 unsigned getLocationNo(Location Loc) {
212 unsigned n = std::find(locations.begin(), locations.end(), Loc) -
214 if (n == locations.size())
215 locations.push_back(Loc);
219 /// addDef - Add a definition point to this value.
220 void addDef(SlotIndex Idx, const MachineOperand &LocMO) {
221 // Add a singular (Idx,Idx) -> Loc mapping.
222 LocMap::iterator I = locInts.find(Idx);
223 if (!I.valid() || I.start() != Idx)
224 I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO));
227 /// extendDef - Extend the current definition as far as possible down the
228 /// dominator tree. Stop when meeting an existing def or when leaving the live
230 /// @param Idx Starting point for the definition.
231 /// @param LocNo Location number to propagate.
232 /// @param LI Restrict liveness to where LI has the value VNI. May be null.
233 /// @param VNI When LI is not null, this is the value to restrict to.
234 /// @param LIS Live intervals analysis.
235 /// @param MDT Dominator tree.
236 void extendDef(SlotIndex Idx, unsigned LocNo,
237 LiveInterval *LI, const VNInfo *VNI,
238 LiveIntervals &LIS, MachineDominatorTree &MDT);
240 /// computeIntervals - Compute the live intervals of all locations after
241 /// collecting all their def points.
242 void computeIntervals(LiveIntervals &LIS, MachineDominatorTree &MDT);
244 /// renameRegister - Update locations to rewrite OldReg as NewReg:SubIdx.
245 void renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx,
246 const TargetRegisterInfo *TRI);
248 void print(raw_ostream&, const TargetRegisterInfo*);
252 /// LDVImpl - Implementation of the LiveDebugVariables pass.
255 LiveDebugVariables &pass;
256 LocMap::Allocator allocator;
259 MachineDominatorTree *MDT;
260 const TargetRegisterInfo *TRI;
262 /// userValues - All allocated UserValue instances.
263 SmallVector<UserValue*, 8> userValues;
265 /// Map virtual register to eq class leader.
266 typedef DenseMap<unsigned, UserValue*> VRMap;
269 /// Map user variable to eq class leader.
270 typedef DenseMap<const MDNode *, UserValue*> UVMap;
273 /// getUserValue - Find or create a UserValue.
274 UserValue *getUserValue(const MDNode *Var, unsigned Offset);
276 /// lookupVirtReg - Find the EC leader for VirtReg or null.
277 UserValue *lookupVirtReg(unsigned VirtReg);
279 /// mapVirtReg - Map virtual register to an equivalence class.
280 void mapVirtReg(unsigned VirtReg, UserValue *EC);
282 /// handleDebugValue - Add DBG_VALUE instruction to our maps.
283 /// @param MI DBG_VALUE instruction
284 /// @param Idx Last valid SLotIndex before instruction.
285 /// @return True if the DBG_VALUE instruction should be deleted.
286 bool handleDebugValue(MachineInstr *MI, SlotIndex Idx);
288 /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
289 /// a UserValue def for each instruction.
290 /// @param mf MachineFunction to be scanned.
291 /// @return True if any debug values were found.
292 bool collectDebugValues(MachineFunction &mf);
294 /// computeIntervals - Compute the live intervals of all user values after
295 /// collecting all their def points.
296 void computeIntervals();
299 LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
300 bool runOnMachineFunction(MachineFunction &mf);
302 /// clear - Relase all memory.
304 DeleteContainerPointers(userValues);
310 /// renameRegister - Replace all references to OldReg wiht NewReg:SubIdx.
311 void renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx);
313 void print(raw_ostream&);
317 void Location::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
323 OS << "int:" << Data.ImmVal;
326 OS << "fp:" << Data.CFP->getValueAPF().convertToDouble();
330 if (TargetRegisterInfo::isVirtualRegister(Kind)) {
331 OS << "%reg" << Kind;
333 OS << ':' << TRI->getSubRegIndexName(Data.SubIdx);
335 OS << '%' << TRI->getName(Kind);
337 OS << "fi#" << ~Kind;
339 OS << '+' << Data.Offset;
345 void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
346 if (const MDString *MDS = dyn_cast<MDString>(variable->getOperand(2)))
347 OS << "!\"" << MDS->getString() << "\"\t";
350 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
351 OS << " [" << I.start() << ';' << I.stop() << "):";
352 if (I.value() == ~0u)
357 for (unsigned i = 0, e = locations.size(); i != e; ++i) {
358 OS << " Loc" << i << '=';
359 locations[i].print(OS, TRI);
364 void LDVImpl::print(raw_ostream &OS) {
365 OS << "********** DEBUG VARIABLES **********\n";
366 for (unsigned i = 0, e = userValues.size(); i != e; ++i)
367 userValues[i]->print(OS, TRI);
370 UserValue *LDVImpl::getUserValue(const MDNode *Var, unsigned Offset) {
371 UserValue *&Leader = userVarMap[Var];
373 UserValue *UV = Leader->getLeader();
375 for (; UV; UV = UV->getNext())
376 if (UV->match(Var, Offset))
380 UserValue *UV = new UserValue(Var, Offset, allocator);
381 userValues.push_back(UV);
382 Leader = UserValue::merge(Leader, UV);
386 void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
387 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
388 UserValue *&Leader = virtRegMap[VirtReg];
389 Leader = UserValue::merge(Leader, EC);
392 UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
393 if (UserValue *UV = virtRegMap.lookup(VirtReg))
394 return UV->getLeader();
398 bool LDVImpl::handleDebugValue(MachineInstr *MI, SlotIndex Idx) {
399 // DBG_VALUE loc, offset, variable
400 if (MI->getNumOperands() != 3 ||
401 !MI->getOperand(1).isImm() || !MI->getOperand(2).isMetadata()) {
402 DEBUG(dbgs() << "Can't handle " << *MI);
406 // Get or create the UserValue for (variable,offset).
407 unsigned Offset = MI->getOperand(1).getImm();
408 const MDNode *Var = MI->getOperand(2).getMetadata();
409 UserValue *UV = getUserValue(Var, Offset);
411 // If the location is a virtual register, make sure it is mapped.
412 if (MI->getOperand(0).isReg()) {
413 unsigned Reg = MI->getOperand(0).getReg();
414 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg))
418 UV->addDef(Idx, MI->getOperand(0));
422 bool LDVImpl::collectDebugValues(MachineFunction &mf) {
423 bool Changed = false;
424 for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
426 MachineBasicBlock *MBB = MFI;
427 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
429 if (!MBBI->isDebugValue()) {
433 // DBG_VALUE has no slot index, use the previous instruction instead.
434 SlotIndex Idx = MBBI == MBB->begin() ?
435 LIS->getMBBStartIdx(MBB) :
436 LIS->getInstructionIndex(llvm::prior(MBBI)).getDefIndex();
437 // Handle consecutive DBG_VALUE instructions with the same slot index.
439 if (handleDebugValue(MBBI, Idx)) {
440 MBBI = MBB->erase(MBBI);
444 } while (MBBI != MBBE && MBBI->isDebugValue());
450 void UserValue::extendDef(SlotIndex Idx, unsigned LocNo,
451 LiveInterval *LI, const VNInfo *VNI,
452 LiveIntervals &LIS, MachineDominatorTree &MDT) {
453 SmallVector<SlotIndex, 16> Todo;
457 SlotIndex Start = Todo.pop_back_val();
458 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
459 SlotIndex Stop = LIS.getMBBEndIdx(MBB);
460 LocMap::iterator I = locInts.find(Idx);
462 // Limit to VNI's live range.
465 LiveRange *Range = LI->getLiveRangeContaining(Start);
466 if (!Range || Range->valno != VNI)
468 if (Range->end < Stop)
469 Stop = Range->end, ToEnd = false;
472 // There could already be a short def at Start.
473 if (I.valid() && I.start() <= Start) {
474 // Stop when meeting a different location or an already extended interval.
475 Start = Start.getNextSlot();
476 if (I.value() != LocNo || I.stop() != Start)
478 // This is a one-slot placeholder. Just skip it.
482 // Limited by the next def.
483 if (I.valid() && I.start() < Stop)
484 Stop = I.start(), ToEnd = false;
489 I.insert(Start, Stop, LocNo);
491 // If we extended to the MBB end, propagate down the dominator tree.
494 const std::vector<MachineDomTreeNode*> &Children =
495 MDT.getNode(MBB)->getChildren();
496 for (unsigned i = 0, e = Children.size(); i != e; ++i)
497 Todo.push_back(LIS.getMBBStartIdx(Children[i]->getBlock()));
498 } while (!Todo.empty());
502 UserValue::computeIntervals(LiveIntervals &LIS, MachineDominatorTree &MDT) {
503 SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs;
505 // Collect all defs to be extended (Skipping undefs).
506 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
507 if (I.value() != ~0u)
508 Defs.push_back(std::make_pair(I.start(), I.value()));
510 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
511 SlotIndex Idx = Defs[i].first;
512 unsigned LocNo = Defs[i].second;
513 const Location &Loc = locations[LocNo];
515 // Register locations are constrained to where the register value is live.
516 if (Loc.isReg() && LIS.hasInterval(Loc.Kind)) {
517 LiveInterval *LI = &LIS.getInterval(Loc.Kind);
518 const VNInfo *VNI = LI->getVNInfoAt(Idx);
519 extendDef(Idx, LocNo, LI, VNI, LIS, MDT);
521 extendDef(Idx, LocNo, 0, 0, LIS, MDT);
524 // Finally, erase all the undefs.
525 for (LocMap::iterator I = locInts.begin(); I.valid();)
526 if (I.value() == ~0u)
532 void LDVImpl::computeIntervals() {
533 for (unsigned i = 0, e = userValues.size(); i != e; ++i)
534 userValues[i]->computeIntervals(*LIS, *MDT);
537 bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
539 LIS = &pass.getAnalysis<LiveIntervals>();
540 MDT = &pass.getAnalysis<MachineDominatorTree>();
541 TRI = mf.getTarget().getRegisterInfo();
543 DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
544 << ((Value*)mf.getFunction())->getName()
547 bool Changed = collectDebugValues(mf);
549 DEBUG(print(dbgs()));
553 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
557 pImpl = new LDVImpl(this);
558 return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
561 void LiveDebugVariables::releaseMemory() {
563 static_cast<LDVImpl*>(pImpl)->clear();
566 LiveDebugVariables::~LiveDebugVariables() {
568 delete static_cast<LDVImpl*>(pImpl);
572 renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx,
573 const TargetRegisterInfo *TRI) {
574 for (unsigned i = 0, e = locations.size(); i != e; ++i) {
575 Location &Loc = locations[i];
576 if (Loc.Kind != OldReg)
579 if (SubIdx && Loc.Data.SubIdx)
580 Loc.Data.SubIdx = TRI->composeSubRegIndices(SubIdx, Loc.Data.SubIdx);
585 renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx) {
586 for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
587 UV->renameRegister(OldReg, NewReg, SubIdx, TRI);
590 void LiveDebugVariables::
591 renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx) {
593 static_cast<LDVImpl*>(pImpl)->renameRegister(OldReg, NewReg, SubIdx);
597 void LiveDebugVariables::dump() {
599 static_cast<LDVImpl*>(pImpl)->print(dbgs());