blob: 98c6dea75904b58521ff490df58f61fe7745d4d3 [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
Devang Patel51a666f2011-01-07 22:33:41 +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 Olesen5daec222010-12-03 22:25:07 +0000191 /// coalesceLocation - After LocNo was changed, check if it has become
192 /// identical to another location, and coalesce them. This may cause LocNo or
193 /// a later location to be erased, but no earlier location will be erased.
194 void coalesceLocation(unsigned LocNo);
195
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000196 /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo.
197 void insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, unsigned LocNo,
198 LiveIntervals &LIS, const TargetInstrInfo &TII);
199
200 /// insertDebugKill - Insert an undef DBG_VALUE into MBB at Idx.
201 void insertDebugKill(MachineBasicBlock *MBB, SlotIndex Idx,
202 LiveIntervals &LIS, const TargetInstrInfo &TII);
203
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000204public:
205 /// UserValue - Create a new UserValue.
206 UserValue(const MDNode *var, unsigned o, LocMap::Allocator &alloc)
207 : variable(var), offset(o), leader(this), next(0), locInts(alloc)
208 {}
209
210 /// getLeader - Get the leader of this value's equivalence class.
211 UserValue *getLeader() {
212 UserValue *l = leader;
213 while (l != l->leader)
214 l = l->leader;
215 return leader = l;
216 }
217
218 /// getNext - Return the next UserValue in the equivalence class.
219 UserValue *getNext() const { return next; }
220
221 /// match - Does this UserValue match the aprameters?
222 bool match(const MDNode *Var, unsigned Offset) const {
223 return Var == variable && Offset == offset;
224 }
225
226 /// merge - Merge equivalence classes.
227 static UserValue *merge(UserValue *L1, UserValue *L2) {
228 L2 = L2->getLeader();
229 if (!L1)
230 return L2;
231 L1 = L1->getLeader();
232 if (L1 == L2)
233 return L1;
234 // Splice L2 before L1's members.
235 UserValue *End = L2;
236 while (End->next)
237 End->leader = L1, End = End->next;
238 End->leader = L1;
239 End->next = L1->next;
240 L1->next = L2;
241 return L1;
242 }
243
244 /// getLocationNo - Return the location number that matches Loc.
245 unsigned getLocationNo(Location Loc) {
246 if (Loc.isUndef())
247 return ~0u;
248 unsigned n = std::find(locations.begin(), locations.end(), Loc) -
249 locations.begin();
250 if (n == locations.size())
251 locations.push_back(Loc);
252 return n;
253 }
254
255 /// addDef - Add a definition point to this value.
256 void addDef(SlotIndex Idx, const MachineOperand &LocMO) {
257 // Add a singular (Idx,Idx) -> Loc mapping.
258 LocMap::iterator I = locInts.find(Idx);
259 if (!I.valid() || I.start() != Idx)
260 I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO));
261 }
262
263 /// extendDef - Extend the current definition as far as possible down the
264 /// dominator tree. Stop when meeting an existing def or when leaving the live
265 /// range of VNI.
266 /// @param Idx Starting point for the definition.
267 /// @param LocNo Location number to propagate.
268 /// @param LI Restrict liveness to where LI has the value VNI. May be null.
269 /// @param VNI When LI is not null, this is the value to restrict to.
270 /// @param LIS Live intervals analysis.
271 /// @param MDT Dominator tree.
272 void extendDef(SlotIndex Idx, unsigned LocNo,
273 LiveInterval *LI, const VNInfo *VNI,
274 LiveIntervals &LIS, MachineDominatorTree &MDT);
275
276 /// computeIntervals - Compute the live intervals of all locations after
277 /// collecting all their def points.
278 void computeIntervals(LiveIntervals &LIS, MachineDominatorTree &MDT);
279
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000280 /// renameRegister - Update locations to rewrite OldReg as NewReg:SubIdx.
281 void renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx,
282 const TargetRegisterInfo *TRI);
283
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000284 /// rewriteLocations - Rewrite virtual register locations according to the
285 /// provided virtual register map.
286 void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI);
287
288 /// emitDebugVariables - Recreate DBG_VALUE instruction from data structures.
289 void emitDebugValues(VirtRegMap *VRM,
290 LiveIntervals &LIS, const TargetInstrInfo &TRI);
291
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000292 void print(raw_ostream&, const TargetRegisterInfo*);
293};
294} // namespace
295
296/// LDVImpl - Implementation of the LiveDebugVariables pass.
297namespace {
298class LDVImpl {
299 LiveDebugVariables &pass;
300 LocMap::Allocator allocator;
301 MachineFunction *MF;
302 LiveIntervals *LIS;
303 MachineDominatorTree *MDT;
304 const TargetRegisterInfo *TRI;
305
306 /// userValues - All allocated UserValue instances.
307 SmallVector<UserValue*, 8> userValues;
308
309 /// Map virtual register to eq class leader.
310 typedef DenseMap<unsigned, UserValue*> VRMap;
Jakob Stoklund Olesen6ed4c6a2010-12-03 22:25:09 +0000311 VRMap virtRegToEqClass;
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000312
313 /// Map user variable to eq class leader.
314 typedef DenseMap<const MDNode *, UserValue*> UVMap;
315 UVMap userVarMap;
316
317 /// getUserValue - Find or create a UserValue.
318 UserValue *getUserValue(const MDNode *Var, unsigned Offset);
319
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000320 /// lookupVirtReg - Find the EC leader for VirtReg or null.
321 UserValue *lookupVirtReg(unsigned VirtReg);
322
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000323 /// mapVirtReg - Map virtual register to an equivalence class.
324 void mapVirtReg(unsigned VirtReg, UserValue *EC);
325
326 /// handleDebugValue - Add DBG_VALUE instruction to our maps.
327 /// @param MI DBG_VALUE instruction
328 /// @param Idx Last valid SLotIndex before instruction.
329 /// @return True if the DBG_VALUE instruction should be deleted.
330 bool handleDebugValue(MachineInstr *MI, SlotIndex Idx);
331
332 /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
333 /// a UserValue def for each instruction.
334 /// @param mf MachineFunction to be scanned.
335 /// @return True if any debug values were found.
336 bool collectDebugValues(MachineFunction &mf);
337
338 /// computeIntervals - Compute the live intervals of all user values after
339 /// collecting all their def points.
340 void computeIntervals();
341
342public:
343 LDVImpl(LiveDebugVariables *ps) : pass(*ps) {}
344 bool runOnMachineFunction(MachineFunction &mf);
345
346 /// clear - Relase all memory.
347 void clear() {
348 DeleteContainerPointers(userValues);
349 userValues.clear();
Jakob Stoklund Olesen6ed4c6a2010-12-03 22:25:09 +0000350 virtRegToEqClass.clear();
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000351 userVarMap.clear();
352 }
353
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000354 /// renameRegister - Replace all references to OldReg wiht NewReg:SubIdx.
355 void renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx);
356
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000357 /// emitDebugVariables - Recreate DBG_VALUE instruction from data structures.
358 void emitDebugValues(VirtRegMap *VRM);
359
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000360 void print(raw_ostream&);
361};
362} // namespace
363
364void Location::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
365 switch (Kind) {
366 case locUndef:
367 OS << "undef";
368 return;
369 case locImm:
370 OS << "int:" << Data.ImmVal;
371 return;
372 case locFPImm:
373 OS << "fp:" << Data.CFP->getValueAPF().convertToDouble();
374 return;
375 default:
376 if (isReg()) {
Jakob Stoklund Olesen43142682011-01-09 03:05:53 +0000377 OS << PrintReg(Kind, TRI, Data.SubIdx);
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000378 } 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
Jakob Stoklund Olesen5daec222010-12-03 22:25:07 +0000412void UserValue::coalesceLocation(unsigned LocNo) {
413 unsigned KeepLoc = std::find(locations.begin(), locations.begin() + LocNo,
414 locations[LocNo]) - locations.begin();
415 unsigned EraseLoc = LocNo;
416 if (KeepLoc == LocNo) {
417 EraseLoc = std::find(locations.begin() + LocNo + 1, locations.end(),
418 locations[LocNo]) - locations.begin();
419 // No matches.
420 if (EraseLoc == locations.size())
421 return;
422 }
423 assert(KeepLoc < EraseLoc);
424 locations.erase(locations.begin() + EraseLoc);
425
426 // Rewrite values.
427 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
428 unsigned v = I.value();
429 if (v == EraseLoc)
430 I.setValue(KeepLoc); // Coalesce when possible.
431 else if (v > EraseLoc)
432 I.setValueUnchecked(v-1); // Avoid coalescing with untransformed values.
433 }
434}
435
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000436UserValue *LDVImpl::getUserValue(const MDNode *Var, unsigned Offset) {
437 UserValue *&Leader = userVarMap[Var];
438 if (Leader) {
439 UserValue *UV = Leader->getLeader();
440 Leader = UV;
441 for (; UV; UV = UV->getNext())
442 if (UV->match(Var, Offset))
443 return UV;
444 }
445
446 UserValue *UV = new UserValue(Var, Offset, allocator);
447 userValues.push_back(UV);
448 Leader = UserValue::merge(Leader, UV);
449 return UV;
450}
451
452void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
453 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
Jakob Stoklund Olesen6ed4c6a2010-12-03 22:25:09 +0000454 UserValue *&Leader = virtRegToEqClass[VirtReg];
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000455 Leader = UserValue::merge(Leader, EC);
456}
457
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000458UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
Jakob Stoklund Olesen6ed4c6a2010-12-03 22:25:09 +0000459 if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000460 return UV->getLeader();
461 return 0;
462}
463
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000464bool LDVImpl::handleDebugValue(MachineInstr *MI, SlotIndex Idx) {
465 // DBG_VALUE loc, offset, variable
466 if (MI->getNumOperands() != 3 ||
467 !MI->getOperand(1).isImm() || !MI->getOperand(2).isMetadata()) {
468 DEBUG(dbgs() << "Can't handle " << *MI);
469 return false;
470 }
471
472 // Get or create the UserValue for (variable,offset).
473 unsigned Offset = MI->getOperand(1).getImm();
474 const MDNode *Var = MI->getOperand(2).getMetadata();
475 UserValue *UV = getUserValue(Var, Offset);
476
477 // If the location is a virtual register, make sure it is mapped.
478 if (MI->getOperand(0).isReg()) {
479 unsigned Reg = MI->getOperand(0).getReg();
480 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg))
481 mapVirtReg(Reg, UV);
482 }
483
484 UV->addDef(Idx, MI->getOperand(0));
485 return true;
486}
487
488bool LDVImpl::collectDebugValues(MachineFunction &mf) {
489 bool Changed = false;
490 for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
491 ++MFI) {
492 MachineBasicBlock *MBB = MFI;
493 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
494 MBBI != MBBE;) {
495 if (!MBBI->isDebugValue()) {
496 ++MBBI;
497 continue;
498 }
499 // DBG_VALUE has no slot index, use the previous instruction instead.
500 SlotIndex Idx = MBBI == MBB->begin() ?
501 LIS->getMBBStartIdx(MBB) :
502 LIS->getInstructionIndex(llvm::prior(MBBI)).getDefIndex();
503 // Handle consecutive DBG_VALUE instructions with the same slot index.
504 do {
505 if (handleDebugValue(MBBI, Idx)) {
506 MBBI = MBB->erase(MBBI);
507 Changed = true;
508 } else
509 ++MBBI;
510 } while (MBBI != MBBE && MBBI->isDebugValue());
511 }
512 }
513 return Changed;
514}
515
516void UserValue::extendDef(SlotIndex Idx, unsigned LocNo,
517 LiveInterval *LI, const VNInfo *VNI,
518 LiveIntervals &LIS, MachineDominatorTree &MDT) {
519 SmallVector<SlotIndex, 16> Todo;
520 Todo.push_back(Idx);
521
522 do {
523 SlotIndex Start = Todo.pop_back_val();
524 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
525 SlotIndex Stop = LIS.getMBBEndIdx(MBB);
526 LocMap::iterator I = locInts.find(Idx);
527
528 // Limit to VNI's live range.
529 bool ToEnd = true;
530 if (LI && VNI) {
531 LiveRange *Range = LI->getLiveRangeContaining(Start);
532 if (!Range || Range->valno != VNI)
533 continue;
534 if (Range->end < Stop)
535 Stop = Range->end, ToEnd = false;
536 }
537
538 // There could already be a short def at Start.
539 if (I.valid() && I.start() <= Start) {
540 // Stop when meeting a different location or an already extended interval.
541 Start = Start.getNextSlot();
542 if (I.value() != LocNo || I.stop() != Start)
543 continue;
544 // This is a one-slot placeholder. Just skip it.
545 ++I;
546 }
547
548 // Limited by the next def.
549 if (I.valid() && I.start() < Stop)
550 Stop = I.start(), ToEnd = false;
551
552 if (Start >= Stop)
553 continue;
554
555 I.insert(Start, Stop, LocNo);
556
557 // If we extended to the MBB end, propagate down the dominator tree.
558 if (!ToEnd)
559 continue;
560 const std::vector<MachineDomTreeNode*> &Children =
561 MDT.getNode(MBB)->getChildren();
562 for (unsigned i = 0, e = Children.size(); i != e; ++i)
563 Todo.push_back(LIS.getMBBStartIdx(Children[i]->getBlock()));
564 } while (!Todo.empty());
565}
566
567void
568UserValue::computeIntervals(LiveIntervals &LIS, MachineDominatorTree &MDT) {
569 SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs;
570
571 // Collect all defs to be extended (Skipping undefs).
572 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
573 if (I.value() != ~0u)
574 Defs.push_back(std::make_pair(I.start(), I.value()));
575
576 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
577 SlotIndex Idx = Defs[i].first;
578 unsigned LocNo = Defs[i].second;
579 const Location &Loc = locations[LocNo];
580
581 // Register locations are constrained to where the register value is live.
582 if (Loc.isReg() && LIS.hasInterval(Loc.Kind)) {
583 LiveInterval *LI = &LIS.getInterval(Loc.Kind);
584 const VNInfo *VNI = LI->getVNInfoAt(Idx);
585 extendDef(Idx, LocNo, LI, VNI, LIS, MDT);
586 } else
587 extendDef(Idx, LocNo, 0, 0, LIS, MDT);
588 }
589
590 // Finally, erase all the undefs.
591 for (LocMap::iterator I = locInts.begin(); I.valid();)
592 if (I.value() == ~0u)
593 I.erase();
594 else
595 ++I;
596}
597
598void LDVImpl::computeIntervals() {
599 for (unsigned i = 0, e = userValues.size(); i != e; ++i)
600 userValues[i]->computeIntervals(*LIS, *MDT);
601}
602
603bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
604 MF = &mf;
605 LIS = &pass.getAnalysis<LiveIntervals>();
606 MDT = &pass.getAnalysis<MachineDominatorTree>();
607 TRI = mf.getTarget().getRegisterInfo();
608 clear();
609 DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
610 << ((Value*)mf.getFunction())->getName()
611 << " **********\n");
612
613 bool Changed = collectDebugValues(mf);
614 computeIntervals();
615 DEBUG(print(dbgs()));
616 return Changed;
617}
618
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +0000619bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
Devang Patel51a666f2011-01-07 22:33:41 +0000620 if (!EnableLDV)
621 return false;
Jakob Stoklund Olesen06135162010-12-02 00:37:37 +0000622 if (!pImpl)
623 pImpl = new LDVImpl(this);
624 return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
625}
626
627void LiveDebugVariables::releaseMemory() {
628 if (pImpl)
629 static_cast<LDVImpl*>(pImpl)->clear();
630}
631
632LiveDebugVariables::~LiveDebugVariables() {
633 if (pImpl)
634 delete static_cast<LDVImpl*>(pImpl);
Jakob Stoklund Olesenbb7b23f2010-11-30 02:17:10 +0000635}
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000636
637void UserValue::
638renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx,
639 const TargetRegisterInfo *TRI) {
Jakob Stoklund Olesen5daec222010-12-03 22:25:07 +0000640 for (unsigned i = locations.size(); i; --i) {
641 unsigned LocNo = i - 1;
642 Location &Loc = locations[LocNo];
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000643 if (Loc.Kind != OldReg)
644 continue;
645 Loc.Kind = NewReg;
646 if (SubIdx && Loc.Data.SubIdx)
647 Loc.Data.SubIdx = TRI->composeSubRegIndices(SubIdx, Loc.Data.SubIdx);
Jakob Stoklund Olesen5daec222010-12-03 22:25:07 +0000648 coalesceLocation(LocNo);
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000649 }
650}
651
652void LDVImpl::
653renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx) {
Jakob Stoklund Olesen8d2584a2010-12-03 21:47:08 +0000654 UserValue *UV = lookupVirtReg(OldReg);
655 if (!UV)
656 return;
657
658 if (TargetRegisterInfo::isVirtualRegister(NewReg))
659 mapVirtReg(NewReg, UV);
Jakob Stoklund Olesen6ed4c6a2010-12-03 22:25:09 +0000660 virtRegToEqClass.erase(OldReg);
Jakob Stoklund Olesen8d2584a2010-12-03 21:47:08 +0000661
662 do {
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000663 UV->renameRegister(OldReg, NewReg, SubIdx, TRI);
Jakob Stoklund Olesen8d2584a2010-12-03 21:47:08 +0000664 UV = UV->getNext();
665 } while (UV);
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000666}
667
668void LiveDebugVariables::
669renameRegister(unsigned OldReg, unsigned NewReg, unsigned SubIdx) {
670 if (pImpl)
671 static_cast<LDVImpl*>(pImpl)->renameRegister(OldReg, NewReg, SubIdx);
672}
673
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000674void
675UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI) {
676 // Iterate over locations in reverse makes it easier to handle coalescing.
677 for (unsigned i = locations.size(); i ; --i) {
678 unsigned LocNo = i-1;
679 Location &Loc = locations[LocNo];
680 // Only virtual registers are rewritten.
681 if (!Loc.isReg() || !TargetRegisterInfo::isVirtualRegister(Loc.Kind))
682 continue;
683 unsigned VirtReg = Loc.Kind;
684 if (VRM.isAssignedReg(VirtReg)) {
685 unsigned PhysReg = VRM.getPhys(VirtReg);
686 if (Loc.Data.SubIdx)
687 PhysReg = TRI.getSubReg(PhysReg, Loc.Data.SubIdx);
688 Loc.Kind = PhysReg;
689 Loc.Data.SubIdx = 0;
690 } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
691 Loc.Kind = ~VRM.getStackSlot(VirtReg);
692 // FIXME: Translate SubIdx to a stackslot offset.
693 Loc.Data.Offset = 0;
694 } else {
695 Loc.Kind = Location::locUndef;
696 }
Jakob Stoklund Olesen5daec222010-12-03 22:25:07 +0000697 coalesceLocation(LocNo);
Jakob Stoklund Olesen42acf062010-12-03 21:47:10 +0000698 }
699 DEBUG(print(dbgs(), &TRI));
700}
701
702/// findInsertLocation - Find an iterator and DebugLoc for inserting a DBG_VALUE
703/// instruction.
704static MachineBasicBlock::iterator
705findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx, DebugLoc &DL,
706 LiveIntervals &LIS) {
707 SlotIndex Start = LIS.getMBBStartIdx(MBB);
708 Idx = Idx.getBaseIndex();
709
710 // Try to find an insert location by going backwards from Idx.
711 MachineInstr *MI;
712 while (!(MI = LIS.getInstructionFromIndex(Idx))) {
713 // We've reached the beginning of MBB.
714 if (Idx == Start) {
715 MachineBasicBlock::iterator I = MBB->SkipPHIsAndLabels(MBB->begin());
716 if (I != MBB->end())
717 DL = I->getDebugLoc();
718 return I;
719 }
720 Idx = Idx.getPrevIndex();
721 }
722 // We found an instruction. The insert point is after the instr.
723 DL = MI->getDebugLoc();
724 return llvm::next(MachineBasicBlock::iterator(MI));
725}
726
727void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx,
728 unsigned LocNo,
729 LiveIntervals &LIS,
730 const TargetInstrInfo &TII) {
731 DebugLoc DL;
732 MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, DL, LIS);
733 Location &Loc = locations[LocNo];
734
735 // Frame index locations may require a target callback.
736 if (Loc.isFrameIndex()) {
737 MachineInstr *MI = TII.emitFrameIndexDebugValue(*MBB->getParent(),
738 Loc.getFrameIndex(),
739 offset, variable, DL);
740 if (MI) {
741 MBB->insert(I, MI);
742 return;
743 }
744 }
745 // This is not a frame index, or the target is happy with a standard FI.
746 Loc.addOperand(BuildMI(*MBB, I, DL, TII.get(TargetOpcode::DBG_VALUE)))
747 .addImm(offset).addMetadata(variable);
748}
749
750void UserValue::insertDebugKill(MachineBasicBlock *MBB, SlotIndex Idx,
751 LiveIntervals &LIS, const TargetInstrInfo &TII) {
752 DebugLoc DL;
753 MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, DL, LIS);
754 BuildMI(*MBB, I, DL, TII.get(TargetOpcode::DBG_VALUE)).addReg(0)
755 .addImm(offset).addMetadata(variable);
756}
757
758void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
759 const TargetInstrInfo &TII) {
760 MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
761
762 for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
763 SlotIndex Start = I.start();
764 SlotIndex Stop = I.stop();
765 unsigned LocNo = I.value();
766 DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo);
767 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
768 SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB);
769
770 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
771 insertDebugValue(MBB, Start, LocNo, LIS, TII);
772
773 // This interval may span multiple basic blocks.
774 // Insert a DBG_VALUE into each one.
775 while(Stop > MBBEnd) {
776 // Move to the next block.
777 Start = MBBEnd;
778 if (++MBB == MFEnd)
779 break;
780 MBBEnd = LIS.getMBBEndIdx(MBB);
781 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
782 insertDebugValue(MBB, Start, LocNo, LIS, TII);
783 }
784 DEBUG(dbgs() << '\n');
785 if (MBB == MFEnd)
786 break;
787
788 ++I;
789 if (Stop == MBBEnd)
790 continue;
791 // The current interval ends before MBB.
792 // Insert a kill if there is a gap.
793 if (!I.valid() || I.start() > Stop)
794 insertDebugKill(MBB, Stop, LIS, TII);
795 }
796}
797
798void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
799 DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
800 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
801 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
802 userValues[i]->rewriteLocations(*VRM, *TRI);
803 userValues[i]->emitDebugValues(VRM, *LIS, *TII);
804 }
805}
806
807void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
808 if (pImpl)
809 static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
810}
811
812
Jakob Stoklund Olesen30e21282010-12-02 18:15:44 +0000813#ifndef NDEBUG
814void LiveDebugVariables::dump() {
815 if (pImpl)
816 static_cast<LDVImpl*>(pImpl)->print(dbgs());
817}
818#endif
819