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