blob: 9a15a2723daba601af6b3a0d2800f382766ff023 [file] [log] [blame]
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +00001//===- 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
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000022#define DEBUG_TYPE "livedebug"
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000023#include "LiveDebugVariables.h"
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000024#include "llvm/Constants.h"
25#include "llvm/Metadata.h"
26#include "llvm/Value.h"
27#include "llvm/ADT/IntervalMap.h"
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000028#include "llvm/CodeGen/LiveIntervalAnalysis.h"
29#include "llvm/CodeGen/MachineFunction.h"
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000030#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000031#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000032#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/Debug.h"
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000034#include "llvm/Target/TargetMachine.h"
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000035#include "llvm/Target/TargetRegisterInfo.h"
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000036
37using namespace llvm;
38
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000039static cl::opt<bool>
40EnableLDV("live-debug-variables",
41 cl::desc("Enable the live debug variables pass"), cl::Hidden);
42
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000043char LiveDebugVariables::ID = 0;
44
45INITIALIZE_PASS_BEGIN(LiveDebugVariables, "livedebugvars",
46 "Debug Variable Analysis", false, false)
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000047INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000048INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
49INITIALIZE_PASS_END(LiveDebugVariables, "livedebugvars",
50 "Debug Variable Analysis", false, false)
51
52void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000053 AU.addRequired<MachineDominatorTree>();
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000054 AU.addRequiredTransitive<LiveIntervals>();
55 AU.setPreservesAll();
56 MachineFunctionPass::getAnalysisUsage(AU);
57}
58
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000059LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID), pImpl(0) {
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +000060 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
61}
62
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +000063/// Location - All the different places a user value can reside.
64/// Note that this includes immediate values that technically aren't locations.
65namespace {
66struct Location {
67 /// kind - What kind of location is this?
68 enum Kind {
69 locUndef = 0,
70 locImm = 0x80000000,
71 locFPImm
72 };
73 /// Kind - One of the following:
74 /// 1. locUndef
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.
79 unsigned Kind;
80
81 /// Data - Extra data about location.
82 union {
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.
87 } Data;
88
89 Location(const MachineOperand &MO) {
90 switch(MO.getType()) {
91 case MachineOperand::MO_Register:
92 Kind = MO.getReg();
93 Data.SubIdx = MO.getSubReg();
94 return;
95 case MachineOperand::MO_Immediate:
96 Kind = locImm;
97 Data.ImmVal = MO.getImm();
98 return;
99 case MachineOperand::MO_FPImmediate:
100 Kind = locFPImm;
101 Data.CFP = MO.getFPImm();
102 return;
103 case MachineOperand::MO_FrameIndex:
104 Kind = ~MO.getIndex();
105 // FIXME: MO_FrameIndex should support an offset.
106 Data.Offset = 0;
107 return;
108 default:
109 Kind = locUndef;
110 return;
111 }
112 }
113
114 bool operator==(const Location &RHS) const {
115 if (Kind != RHS.Kind)
116 return false;
117 switch (Kind) {
118 case locUndef:
119 return true;
120 case locImm:
121 return Data.ImmVal == RHS.Data.ImmVal;
122 case locFPImm:
123 return Data.CFP == RHS.Data.CFP;
124 default:
125 if (isReg())
126 return Data.SubIdx == RHS.Data.SubIdx;
127 else
128 return Data.Offset == RHS.Data.Offset;
129 }
130 }
131
132 /// isUndef - is this the singleton undef?
133 bool isUndef() const { return Kind == locUndef; }
134
135 /// isReg - is this a register location?
136 bool isReg() const { return Kind && Kind < locImm; }
137
138 void print(raw_ostream&, const TargetRegisterInfo*);
139};
140}
141
142/// LocMap - Map of where a user value is live, and its location.
143typedef IntervalMap<SlotIndex, unsigned, 4> LocMap;
144
145/// UserValue - A user value is a part of a debug info user variable.
146///
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.
149///
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.
154namespace {
155class UserValue {
156 const MDNode *variable; ///< The debug info variable we are part of.
157 unsigned offset; ///< Byte offset into variable.
158
159 UserValue *leader; ///< Equivalence class leader.
160 UserValue *next; ///< Next value in equivalence class, or null.
161
162 /// Numbered locations referenced by locmap.
163 SmallVector<Location, 4> locations;
164
165 /// Map of slot indices where this value is live.
166 LocMap locInts;
167
168public:
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)
172 {}
173
174 /// getLeader - Get the leader of this value's equivalence class.
175 UserValue *getLeader() {
176 UserValue *l = leader;
177 while (l != l->leader)
178 l = l->leader;
179 return leader = l;
180 }
181
182 /// getNext - Return the next UserValue in the equivalence class.
183 UserValue *getNext() const { return next; }
184
185 /// match - Does this UserValue match the aprameters?
186 bool match(const MDNode *Var, unsigned Offset) const {
187 return Var == variable && Offset == offset;
188 }
189
190 /// merge - Merge equivalence classes.
191 static UserValue *merge(UserValue *L1, UserValue *L2) {
192 L2 = L2->getLeader();
193 if (!L1)
194 return L2;
195 L1 = L1->getLeader();
196 if (L1 == L2)
197 return L1;
198 // Splice L2 before L1's members.
199 UserValue *End = L2;
200 while (End->next)
201 End->leader = L1, End = End->next;
202 End->leader = L1;
203 End->next = L1->next;
204 L1->next = L2;
205 return L1;
206 }
207
208 /// getLocationNo - Return the location number that matches Loc.
209 unsigned getLocationNo(Location Loc) {
210 if (Loc.isUndef())
211 return ~0u;
212 unsigned n = std::find(locations.begin(), locations.end(), Loc) -
213 locations.begin();
214 if (n == locations.size())
215 locations.push_back(Loc);
216 return n;
217 }
218
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));
225 }
226
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
229 /// range of VNI.
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);
239
240 /// computeIntervals - Compute the live intervals of all locations after
241 /// collecting all their def points.
242 void computeIntervals(LiveIntervals &LIS, MachineDominatorTree &MDT);
243
244 void print(raw_ostream&, const TargetRegisterInfo*);
245};
246} // namespace
247
248/// LDVImpl - Implementation of the LiveDebugVariables pass.
249namespace {
250class LDVImpl {
251 LiveDebugVariables &pass;
252 LocMap::Allocator allocator;
253 MachineFunction *MF;
254 LiveIntervals *LIS;
255 MachineDominatorTree *MDT;
256 const TargetRegisterInfo *TRI;
257
258 /// userValues - All allocated UserValue instances.
259 SmallVector<UserValue*, 8> userValues;
260
261 /// Map virtual register to eq class leader.
262 typedef DenseMap<unsigned, UserValue*> VRMap;
263 VRMap virtRegMap;
264
265 /// Map user variable to eq class leader.
266 typedef DenseMap<const MDNode *, UserValue*> UVMap;
267 UVMap userVarMap;
268
269 /// getUserValue - Find or create a UserValue.
270 UserValue *getUserValue(const MDNode *Var, unsigned Offset);
271
272 /// mapVirtReg - Map virtual register to an equivalence class.
273 void mapVirtReg(unsigned VirtReg, UserValue *EC);
274
275 /// handleDebugValue - Add DBG_VALUE instruction to our maps.
276 /// @param MI DBG_VALUE instruction
277 /// @param Idx Last valid SLotIndex before instruction.
278 /// @return True if the DBG_VALUE instruction should be deleted.
279 bool handleDebugValue(MachineInstr *MI, SlotIndex Idx);
280
281 /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
282 /// a UserValue def for each instruction.
283 /// @param mf MachineFunction to be scanned.
284 /// @return True if any debug values were found.
285 bool collectDebugValues(MachineFunction &mf);
286
287 /// computeIntervals - Compute the live intervals of all user values after
288 /// collecting all their def points.
289 void computeIntervals();
290
291public:
292 LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
293 bool runOnMachineFunction(MachineFunction &mf);
294
295 /// clear - Relase all memory.
296 void clear() {
297 DeleteContainerPointers(userValues);
298 userValues.clear();
299 virtRegMap.clear();
300 userVarMap.clear();
301 }
302
303 void print(raw_ostream&);
304};
305} // namespace
306
307void Location::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
308 switch (Kind) {
309 case locUndef:
310 OS << "undef";
311 return;
312 case locImm:
313 OS << "int:" << Data.ImmVal;
314 return;
315 case locFPImm:
316 OS << "fp:" << Data.CFP->getValueAPF().convertToDouble();
317 return;
318 default:
319 if (isReg()) {
320 if (TargetRegisterInfo::isVirtualRegister(Kind)) {
321 OS << "%reg" << Kind;
322 if (Data.SubIdx)
323 OS << ':' << TRI->getSubRegIndexName(Data.SubIdx);
324 } else
325 OS << '%' << TRI->getName(Kind);
326 } else {
327 OS << "fi#" << ~Kind;
328 if (Data.Offset)
329 OS << '+' << Data.Offset;
330 }
331 return;
332 }
333}
334
335void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
336 if (const MDString *MDS = dyn_cast<MDString>(variable->getOperand(2)))
337 OS << "!\"" << MDS->getString() << "\"\t";
338 if (offset)
339 OS << '+' << offset;
340 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
341 OS << " [" << I.start() << ';' << I.stop() << "):";
342 if (I.value() == ~0u)
343 OS << "undef";
344 else
345 OS << I.value();
346 }
347 for (unsigned i = 0, e = locations.size(); i != e; ++i) {
348 OS << " Loc" << i << '=';
349 locations[i].print(OS, TRI);
350 }
351 OS << '\n';
352}
353
354void LDVImpl::print(raw_ostream &OS) {
355 OS << "********** DEBUG VARIABLES **********\n";
356 for (unsigned i = 0, e = userValues.size(); i != e; ++i)
357 userValues[i]->print(OS, TRI);
358}
359
360UserValue *LDVImpl::getUserValue(const MDNode *Var, unsigned Offset) {
361 UserValue *&Leader = userVarMap[Var];
362 if (Leader) {
363 UserValue *UV = Leader->getLeader();
364 Leader = UV;
365 for (; UV; UV = UV->getNext())
366 if (UV->match(Var, Offset))
367 return UV;
368 }
369
370 UserValue *UV = new UserValue(Var, Offset, allocator);
371 userValues.push_back(UV);
372 Leader = UserValue::merge(Leader, UV);
373 return UV;
374}
375
376void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
377 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
378 UserValue *&Leader = virtRegMap[VirtReg];
379 Leader = UserValue::merge(Leader, EC);
380}
381
382bool LDVImpl::handleDebugValue(MachineInstr *MI, SlotIndex Idx) {
383 // DBG_VALUE loc, offset, variable
384 if (MI->getNumOperands() != 3 ||
385 !MI->getOperand(1).isImm() || !MI->getOperand(2).isMetadata()) {
386 DEBUG(dbgs() << "Can't handle " << *MI);
387 return false;
388 }
389
390 // Get or create the UserValue for (variable,offset).
391 unsigned Offset = MI->getOperand(1).getImm();
392 const MDNode *Var = MI->getOperand(2).getMetadata();
393 UserValue *UV = getUserValue(Var, Offset);
394
395 // If the location is a virtual register, make sure it is mapped.
396 if (MI->getOperand(0).isReg()) {
397 unsigned Reg = MI->getOperand(0).getReg();
398 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg))
399 mapVirtReg(Reg, UV);
400 }
401
402 UV->addDef(Idx, MI->getOperand(0));
403 return true;
404}
405
406bool LDVImpl::collectDebugValues(MachineFunction &mf) {
407 bool Changed = false;
408 for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
409 ++MFI) {
410 MachineBasicBlock *MBB = MFI;
411 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
412 MBBI != MBBE;) {
413 if (!MBBI->isDebugValue()) {
414 ++MBBI;
415 continue;
416 }
417 // DBG_VALUE has no slot index, use the previous instruction instead.
418 SlotIndex Idx = MBBI == MBB->begin() ?
419 LIS->getMBBStartIdx(MBB) :
420 LIS->getInstructionIndex(llvm::prior(MBBI)).getDefIndex();
421 // Handle consecutive DBG_VALUE instructions with the same slot index.
422 do {
423 if (handleDebugValue(MBBI, Idx)) {
424 MBBI = MBB->erase(MBBI);
425 Changed = true;
426 } else
427 ++MBBI;
428 } while (MBBI != MBBE && MBBI->isDebugValue());
429 }
430 }
431 return Changed;
432}
433
434void UserValue::extendDef(SlotIndex Idx, unsigned LocNo,
435 LiveInterval *LI, const VNInfo *VNI,
436 LiveIntervals &LIS, MachineDominatorTree &MDT) {
437 SmallVector<SlotIndex, 16> Todo;
438 Todo.push_back(Idx);
439
440 do {
441 SlotIndex Start = Todo.pop_back_val();
442 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
443 SlotIndex Stop = LIS.getMBBEndIdx(MBB);
444 LocMap::iterator I = locInts.find(Idx);
445
446 // Limit to VNI's live range.
447 bool ToEnd = true;
448 if (LI && VNI) {
449 LiveRange *Range = LI->getLiveRangeContaining(Start);
450 if (!Range || Range->valno != VNI)
451 continue;
452 if (Range->end < Stop)
453 Stop = Range->end, ToEnd = false;
454 }
455
456 // There could already be a short def at Start.
457 if (I.valid() && I.start() <= Start) {
458 // Stop when meeting a different location or an already extended interval.
459 Start = Start.getNextSlot();
460 if (I.value() != LocNo || I.stop() != Start)
461 continue;
462 // This is a one-slot placeholder. Just skip it.
463 ++I;
464 }
465
466 // Limited by the next def.
467 if (I.valid() && I.start() < Stop)
468 Stop = I.start(), ToEnd = false;
469
470 if (Start >= Stop)
471 continue;
472
473 I.insert(Start, Stop, LocNo);
474
475 // If we extended to the MBB end, propagate down the dominator tree.
476 if (!ToEnd)
477 continue;
478 const std::vector<MachineDomTreeNode*> &Children =
479 MDT.getNode(MBB)->getChildren();
480 for (unsigned i = 0, e = Children.size(); i != e; ++i)
481 Todo.push_back(LIS.getMBBStartIdx(Children[i]->getBlock()));
482 } while (!Todo.empty());
483}
484
485void
486UserValue::computeIntervals(LiveIntervals &LIS, MachineDominatorTree &MDT) {
487 SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs;
488
489 // Collect all defs to be extended (Skipping undefs).
490 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
491 if (I.value() != ~0u)
492 Defs.push_back(std::make_pair(I.start(), I.value()));
493
494 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
495 SlotIndex Idx = Defs[i].first;
496 unsigned LocNo = Defs[i].second;
497 const Location &Loc = locations[LocNo];
498
499 // Register locations are constrained to where the register value is live.
500 if (Loc.isReg() && LIS.hasInterval(Loc.Kind)) {
501 LiveInterval *LI = &LIS.getInterval(Loc.Kind);
502 const VNInfo *VNI = LI->getVNInfoAt(Idx);
503 extendDef(Idx, LocNo, LI, VNI, LIS, MDT);
504 } else
505 extendDef(Idx, LocNo, 0, 0, LIS, MDT);
506 }
507
508 // Finally, erase all the undefs.
509 for (LocMap::iterator I = locInts.begin(); I.valid();)
510 if (I.value() == ~0u)
511 I.erase();
512 else
513 ++I;
514}
515
516void LDVImpl::computeIntervals() {
517 for (unsigned i = 0, e = userValues.size(); i != e; ++i)
518 userValues[i]->computeIntervals(*LIS, *MDT);
519}
520
521bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
522 MF = &mf;
523 LIS = &pass.getAnalysis<LiveIntervals>();
524 MDT = &pass.getAnalysis<MachineDominatorTree>();
525 TRI = mf.getTarget().getRegisterInfo();
526 clear();
527 DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
528 << ((Value*)mf.getFunction())->getName()
529 << " **********\n");
530
531 bool Changed = collectDebugValues(mf);
532 computeIntervals();
533 DEBUG(print(dbgs()));
534 return Changed;
535}
536
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +0000537bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000538 if (!EnableLDV)
539 return false;
540 if (!pImpl)
541 pImpl = new LDVImpl(this);
542 return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
543}
544
545void LiveDebugVariables::releaseMemory() {
546 if (pImpl)
547 static_cast<LDVImpl*>(pImpl)->clear();
548}
549
550LiveDebugVariables::~LiveDebugVariables() {
551 if (pImpl)
552 delete static_cast<LDVImpl*>(pImpl);
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +0000553}