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 #include "LiveDebugVariables.h"
23 #include "llvm/ADT/IntervalMap.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/CodeGen/LexicalScopes.h"
26 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
27 #include "llvm/CodeGen/MachineDominators.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/CodeGen/VirtRegMap.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DebugInfo.h"
35 #include "llvm/IR/Metadata.h"
36 #include "llvm/IR/Value.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Target/TargetSubtargetInfo.h"
48 #define DEBUG_TYPE "livedebug"
51 EnableLDV("live-debug-variables", cl::init(true),
52 cl::desc("Enable the live debug variables pass"), cl::Hidden);
54 STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
55 char LiveDebugVariables::ID = 0;
57 INITIALIZE_PASS_BEGIN(LiveDebugVariables, "livedebugvars",
58 "Debug Variable Analysis", false, false)
59 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
60 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
61 INITIALIZE_PASS_END(LiveDebugVariables, "livedebugvars",
62 "Debug Variable Analysis", false, false)
64 void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
65 AU.addRequired<MachineDominatorTree>();
66 AU.addRequiredTransitive<LiveIntervals>();
68 MachineFunctionPass::getAnalysisUsage(AU);
71 LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID), pImpl(nullptr) {
72 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
75 /// LocMap - Map of where a user value is live, and its location.
76 typedef IntervalMap<SlotIndex, unsigned, 4> LocMap;
79 /// UserValueScopes - Keeps track of lexical scopes associated with a
80 /// user value's source location.
81 class UserValueScopes {
84 SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
87 UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(D), LS(L) {}
89 /// dominates - Return true if current scope dominates at least one machine
90 /// instruction in a given machine basic block.
91 bool dominates(MachineBasicBlock *MBB) {
93 LS.getMachineBasicBlocks(DL, LBlocks);
94 return LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB);
97 } // end anonymous namespace
99 /// UserValue - A user value is a part of a debug info user variable.
101 /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
102 /// holds part of a user variable. The part is identified by a byte offset.
104 /// UserValues are grouped into equivalence classes for easier searching. Two
105 /// user values are related if they refer to the same variable, or if they are
106 /// held by the same virtual register. The equivalence class is the transitive
107 /// closure of that relation.
111 const MDNode *Variable; ///< The debug info variable we are part of.
112 const MDNode *Expression; ///< Any complex address expression.
113 unsigned offset; ///< Byte offset into variable.
114 bool IsIndirect; ///< true if this is a register-indirect+offset value.
115 DebugLoc dl; ///< The debug location for the variable. This is
116 ///< used by dwarf writer to find lexical scope.
117 UserValue *leader; ///< Equivalence class leader.
118 UserValue *next; ///< Next value in equivalence class, or null.
120 /// Numbered locations referenced by locmap.
121 SmallVector<MachineOperand, 4> locations;
123 /// Map of slot indices where this value is live.
126 /// coalesceLocation - After LocNo was changed, check if it has become
127 /// identical to another location, and coalesce them. This may cause LocNo or
128 /// a later location to be erased, but no earlier location will be erased.
129 void coalesceLocation(unsigned LocNo);
131 /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo.
132 void insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, unsigned LocNo,
133 LiveIntervals &LIS, const TargetInstrInfo &TII);
135 /// splitLocation - Replace OldLocNo ranges with NewRegs ranges where NewRegs
136 /// is live. Returns true if any changes were made.
137 bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
141 /// UserValue - Create a new UserValue.
142 UserValue(const MDNode *var, const MDNode *expr, unsigned o, bool i,
143 DebugLoc L, LocMap::Allocator &alloc)
144 : Variable(var), Expression(expr), offset(o), IsIndirect(i), dl(L),
145 leader(this), next(nullptr), locInts(alloc) {}
147 /// getLeader - Get the leader of this value's equivalence class.
148 UserValue *getLeader() {
149 UserValue *l = leader;
150 while (l != l->leader)
155 /// getNext - Return the next UserValue in the equivalence class.
156 UserValue *getNext() const { return next; }
158 /// match - Does this UserValue match the parameters?
159 bool match(const MDNode *Var, const MDNode *Expr, const DILocation *IA,
160 unsigned Offset, bool indirect) const {
161 return Var == Variable && Expr == Expression && dl->getInlinedAt() == IA &&
162 Offset == offset && indirect == IsIndirect;
165 /// merge - Merge equivalence classes.
166 static UserValue *merge(UserValue *L1, UserValue *L2) {
167 L2 = L2->getLeader();
170 L1 = L1->getLeader();
173 // Splice L2 before L1's members.
176 End->leader = L1, End = End->next;
178 End->next = L1->next;
183 /// getLocationNo - Return the location number that matches Loc.
184 unsigned getLocationNo(const MachineOperand &LocMO) {
186 if (LocMO.getReg() == 0)
188 // For register locations we dont care about use/def and other flags.
189 for (unsigned i = 0, e = locations.size(); i != e; ++i)
190 if (locations[i].isReg() &&
191 locations[i].getReg() == LocMO.getReg() &&
192 locations[i].getSubReg() == LocMO.getSubReg())
195 for (unsigned i = 0, e = locations.size(); i != e; ++i)
196 if (LocMO.isIdenticalTo(locations[i]))
198 locations.push_back(LocMO);
199 // We are storing a MachineOperand outside a MachineInstr.
200 locations.back().clearParent();
201 // Don't store def operands.
202 if (locations.back().isReg())
203 locations.back().setIsUse();
204 return locations.size() - 1;
207 /// mapVirtRegs - Ensure that all virtual register locations are mapped.
208 void mapVirtRegs(LDVImpl *LDV);
210 /// addDef - Add a definition point to this value.
211 void addDef(SlotIndex Idx, const MachineOperand &LocMO) {
212 // Add a singular (Idx,Idx) -> Loc mapping.
213 LocMap::iterator I = locInts.find(Idx);
214 if (!I.valid() || I.start() != Idx)
215 I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO));
217 // A later DBG_VALUE at the same SlotIndex overrides the old location.
218 I.setValue(getLocationNo(LocMO));
221 /// extendDef - Extend the current definition as far as possible down the
222 /// dominator tree. Stop when meeting an existing def or when leaving the live
224 /// End points where VNI is no longer live are added to Kills.
225 /// @param Idx Starting point for the definition.
226 /// @param LocNo Location number to propagate.
227 /// @param LR Restrict liveness to where LR has the value VNI. May be null.
228 /// @param VNI When LR is not null, this is the value to restrict to.
229 /// @param Kills Append end points of VNI's live range to Kills.
230 /// @param LIS Live intervals analysis.
231 /// @param MDT Dominator tree.
232 void extendDef(SlotIndex Idx, unsigned LocNo,
233 LiveRange *LR, const VNInfo *VNI,
234 SmallVectorImpl<SlotIndex> *Kills,
235 LiveIntervals &LIS, MachineDominatorTree &MDT,
236 UserValueScopes &UVS);
238 /// addDefsFromCopies - The value in LI/LocNo may be copies to other
239 /// registers. Determine if any of the copies are available at the kill
240 /// points, and add defs if possible.
241 /// @param LI Scan for copies of the value in LI->reg.
242 /// @param LocNo Location number of LI->reg.
243 /// @param Kills Points where the range of LocNo could be extended.
244 /// @param NewDefs Append (Idx, LocNo) of inserted defs here.
245 void addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
246 const SmallVectorImpl<SlotIndex> &Kills,
247 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
248 MachineRegisterInfo &MRI,
251 /// computeIntervals - Compute the live intervals of all locations after
252 /// collecting all their def points.
253 void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
254 LiveIntervals &LIS, MachineDominatorTree &MDT,
255 UserValueScopes &UVS);
257 /// splitRegister - Replace OldReg ranges with NewRegs ranges where NewRegs is
258 /// live. Returns true if any changes were made.
259 bool splitRegister(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
262 /// rewriteLocations - Rewrite virtual register locations according to the
263 /// provided virtual register map.
264 void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI);
266 /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
267 void emitDebugValues(VirtRegMap *VRM,
268 LiveIntervals &LIS, const TargetInstrInfo &TRI);
270 /// getDebugLoc - Return DebugLoc of this UserValue.
271 DebugLoc getDebugLoc() { return dl;}
272 void print(raw_ostream &, const TargetRegisterInfo *);
276 /// LDVImpl - Implementation of the LiveDebugVariables pass.
279 LiveDebugVariables &pass;
280 LocMap::Allocator allocator;
284 MachineDominatorTree *MDT;
285 const TargetRegisterInfo *TRI;
287 /// Whether emitDebugValues is called.
289 /// Whether the machine function is modified during the pass.
292 /// userValues - All allocated UserValue instances.
293 SmallVector<std::unique_ptr<UserValue>, 8> userValues;
295 /// Map virtual register to eq class leader.
296 typedef DenseMap<unsigned, UserValue*> VRMap;
297 VRMap virtRegToEqClass;
299 /// Map user variable to eq class leader.
300 typedef DenseMap<const MDNode *, UserValue*> UVMap;
303 /// getUserValue - Find or create a UserValue.
304 UserValue *getUserValue(const MDNode *Var, const MDNode *Expr,
305 unsigned Offset, bool IsIndirect, DebugLoc DL);
307 /// lookupVirtReg - Find the EC leader for VirtReg or null.
308 UserValue *lookupVirtReg(unsigned VirtReg);
310 /// handleDebugValue - Add DBG_VALUE instruction to our maps.
311 /// @param MI DBG_VALUE instruction
312 /// @param Idx Last valid SLotIndex before instruction.
313 /// @return True if the DBG_VALUE instruction should be deleted.
314 bool handleDebugValue(MachineInstr *MI, SlotIndex Idx);
316 /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
317 /// a UserValue def for each instruction.
318 /// @param mf MachineFunction to be scanned.
319 /// @return True if any debug values were found.
320 bool collectDebugValues(MachineFunction &mf);
322 /// computeIntervals - Compute the live intervals of all user values after
323 /// collecting all their def points.
324 void computeIntervals();
327 LDVImpl(LiveDebugVariables *ps)
328 : pass(*ps), MF(nullptr), EmitDone(false), ModifiedMF(false) {}
329 bool runOnMachineFunction(MachineFunction &mf);
331 /// clear - Release all memory.
335 virtRegToEqClass.clear();
337 // Make sure we call emitDebugValues if the machine function was modified.
338 assert((!ModifiedMF || EmitDone) &&
339 "Dbg values are not emitted in LDV");
345 /// mapVirtReg - Map virtual register to an equivalence class.
346 void mapVirtReg(unsigned VirtReg, UserValue *EC);
348 /// splitRegister - Replace all references to OldReg with NewRegs.
349 void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs);
351 /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
352 void emitDebugValues(VirtRegMap *VRM);
354 void print(raw_ostream&);
358 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
359 const LLVMContext &Ctx) {
363 auto *Scope = cast<DIScope>(DL.getScope());
364 // Omit the directory, because it's likely to be long and uninteresting.
365 CommentOS << Scope->getFilename();
366 CommentOS << ':' << DL.getLine();
367 if (DL.getCol() != 0)
368 CommentOS << ':' << DL.getCol();
370 DebugLoc InlinedAtDL = DL.getInlinedAt();
375 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
379 static void printExtendedName(raw_ostream &OS, const DILocalVariable *V,
380 const DILocation *DL) {
381 const LLVMContext &Ctx = V->getContext();
382 StringRef Res = V->getName();
384 OS << Res << "," << V->getLine();
385 if (auto *InlinedAt = DL->getInlinedAt()) {
386 if (DebugLoc InlinedAtDL = InlinedAt) {
388 printDebugLoc(InlinedAtDL, OS, Ctx);
394 void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
395 auto *DV = cast<DILocalVariable>(Variable);
397 printExtendedName(OS, DV, dl);
402 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
403 OS << " [" << I.start() << ';' << I.stop() << "):";
404 if (I.value() == ~0u)
409 for (unsigned i = 0, e = locations.size(); i != e; ++i) {
410 OS << " Loc" << i << '=';
411 locations[i].print(OS, TRI);
416 void LDVImpl::print(raw_ostream &OS) {
417 OS << "********** DEBUG VARIABLES **********\n";
418 for (unsigned i = 0, e = userValues.size(); i != e; ++i)
419 userValues[i]->print(OS, TRI);
422 void UserValue::coalesceLocation(unsigned LocNo) {
423 unsigned KeepLoc = 0;
424 for (unsigned e = locations.size(); KeepLoc != e; ++KeepLoc) {
425 if (KeepLoc == LocNo)
427 if (locations[KeepLoc].isIdenticalTo(locations[LocNo]))
431 if (KeepLoc == locations.size())
434 // Keep the smaller location, erase the larger one.
435 unsigned EraseLoc = LocNo;
436 if (KeepLoc > EraseLoc)
437 std::swap(KeepLoc, EraseLoc);
438 locations.erase(locations.begin() + EraseLoc);
441 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
442 unsigned v = I.value();
444 I.setValue(KeepLoc); // Coalesce when possible.
445 else if (v > EraseLoc)
446 I.setValueUnchecked(v-1); // Avoid coalescing with untransformed values.
450 void UserValue::mapVirtRegs(LDVImpl *LDV) {
451 for (unsigned i = 0, e = locations.size(); i != e; ++i)
452 if (locations[i].isReg() &&
453 TargetRegisterInfo::isVirtualRegister(locations[i].getReg()))
454 LDV->mapVirtReg(locations[i].getReg(), this);
457 UserValue *LDVImpl::getUserValue(const MDNode *Var, const MDNode *Expr,
458 unsigned Offset, bool IsIndirect,
460 UserValue *&Leader = userVarMap[Var];
462 UserValue *UV = Leader->getLeader();
464 for (; UV; UV = UV->getNext())
465 if (UV->match(Var, Expr, DL->getInlinedAt(), Offset, IsIndirect))
469 userValues.push_back(
470 make_unique<UserValue>(Var, Expr, Offset, IsIndirect, DL, allocator));
471 UserValue *UV = userValues.back().get();
472 Leader = UserValue::merge(Leader, UV);
476 void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
477 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
478 UserValue *&Leader = virtRegToEqClass[VirtReg];
479 Leader = UserValue::merge(Leader, EC);
482 UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
483 if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
484 return UV->getLeader();
488 bool LDVImpl::handleDebugValue(MachineInstr *MI, SlotIndex Idx) {
489 // DBG_VALUE loc, offset, variable
490 if (MI->getNumOperands() != 4 ||
491 !(MI->getOperand(1).isReg() || MI->getOperand(1).isImm()) ||
492 !MI->getOperand(2).isMetadata()) {
493 DEBUG(dbgs() << "Can't handle " << *MI);
497 // Get or create the UserValue for (variable,offset).
498 bool IsIndirect = MI->isIndirectDebugValue();
499 unsigned Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
500 const MDNode *Var = MI->getDebugVariable();
501 const MDNode *Expr = MI->getDebugExpression();
504 getUserValue(Var, Expr, Offset, IsIndirect, MI->getDebugLoc());
505 UV->addDef(Idx, MI->getOperand(0));
509 bool LDVImpl::collectDebugValues(MachineFunction &mf) {
510 bool Changed = false;
511 for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
513 MachineBasicBlock *MBB = &*MFI;
514 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
516 if (!MBBI->isDebugValue()) {
520 // DBG_VALUE has no slot index, use the previous instruction instead.
521 SlotIndex Idx = MBBI == MBB->begin() ?
522 LIS->getMBBStartIdx(MBB) :
523 LIS->getInstructionIndex(std::prev(MBBI)).getRegSlot();
524 // Handle consecutive DBG_VALUE instructions with the same slot index.
526 if (handleDebugValue(MBBI, Idx)) {
527 MBBI = MBB->erase(MBBI);
531 } while (MBBI != MBBE && MBBI->isDebugValue());
537 void UserValue::extendDef(SlotIndex Idx, unsigned LocNo,
538 LiveRange *LR, const VNInfo *VNI,
539 SmallVectorImpl<SlotIndex> *Kills,
540 LiveIntervals &LIS, MachineDominatorTree &MDT,
541 UserValueScopes &UVS) {
542 SmallVector<SlotIndex, 16> Todo;
545 SlotIndex Start = Todo.pop_back_val();
546 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
547 SlotIndex Stop = LIS.getMBBEndIdx(MBB);
548 LocMap::iterator I = locInts.find(Start);
550 // Limit to VNI's live range.
553 LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
554 if (!Segment || Segment->valno != VNI) {
556 Kills->push_back(Start);
559 if (Segment->end < Stop)
560 Stop = Segment->end, ToEnd = false;
563 // There could already be a short def at Start.
564 if (I.valid() && I.start() <= Start) {
565 // Stop when meeting a different location or an already extended interval.
566 Start = Start.getNextSlot();
567 if (I.value() != LocNo || I.stop() != Start)
569 // This is a one-slot placeholder. Just skip it.
573 // Limited by the next def.
574 if (I.valid() && I.start() < Stop)
575 Stop = I.start(), ToEnd = false;
576 // Limited by VNI's live range.
577 else if (!ToEnd && Kills)
578 Kills->push_back(Stop);
583 I.insert(Start, Stop, LocNo);
585 // If we extended to the MBB end, propagate down the dominator tree.
588 const std::vector<MachineDomTreeNode*> &Children =
589 MDT.getNode(MBB)->getChildren();
590 for (unsigned i = 0, e = Children.size(); i != e; ++i) {
591 MachineBasicBlock *MBB = Children[i]->getBlock();
592 if (UVS.dominates(MBB))
593 Todo.push_back(LIS.getMBBStartIdx(MBB));
595 } while (!Todo.empty());
599 UserValue::addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
600 const SmallVectorImpl<SlotIndex> &Kills,
601 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
602 MachineRegisterInfo &MRI, LiveIntervals &LIS) {
605 // Don't track copies from physregs, there are too many uses.
606 if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
609 // Collect all the (vreg, valno) pairs that are copies of LI.
610 SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
611 for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) {
612 MachineInstr *MI = MO.getParent();
613 // Copies of the full value.
614 if (MO.getSubReg() || !MI->isCopy())
616 unsigned DstReg = MI->getOperand(0).getReg();
618 // Don't follow copies to physregs. These are usually setting up call
619 // arguments, and the argument registers are always call clobbered. We are
620 // better off in the source register which could be a callee-saved register,
621 // or it could be spilled.
622 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
625 // Is LocNo extended to reach this copy? If not, another def may be blocking
626 // it, or we are looking at a wrong value of LI.
627 SlotIndex Idx = LIS.getInstructionIndex(MI);
628 LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
629 if (!I.valid() || I.value() != LocNo)
632 if (!LIS.hasInterval(DstReg))
634 LiveInterval *DstLI = &LIS.getInterval(DstReg);
635 const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
636 assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
637 CopyValues.push_back(std::make_pair(DstLI, DstVNI));
640 if (CopyValues.empty())
643 DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI << '\n');
645 // Try to add defs of the copied values for each kill point.
646 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
647 SlotIndex Idx = Kills[i];
648 for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
649 LiveInterval *DstLI = CopyValues[j].first;
650 const VNInfo *DstVNI = CopyValues[j].second;
651 if (DstLI->getVNInfoAt(Idx) != DstVNI)
653 // Check that there isn't already a def at Idx
654 LocMap::iterator I = locInts.find(Idx);
655 if (I.valid() && I.start() <= Idx)
657 DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
658 << DstVNI->id << " in " << *DstLI << '\n');
659 MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
660 assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
661 unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
662 I.insert(Idx, Idx.getNextSlot(), LocNo);
663 NewDefs.push_back(std::make_pair(Idx, LocNo));
670 UserValue::computeIntervals(MachineRegisterInfo &MRI,
671 const TargetRegisterInfo &TRI,
673 MachineDominatorTree &MDT,
674 UserValueScopes &UVS) {
675 SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs;
677 // Collect all defs to be extended (Skipping undefs).
678 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
679 if (I.value() != ~0u)
680 Defs.push_back(std::make_pair(I.start(), I.value()));
682 // Extend all defs, and possibly add new ones along the way.
683 for (unsigned i = 0; i != Defs.size(); ++i) {
684 SlotIndex Idx = Defs[i].first;
685 unsigned LocNo = Defs[i].second;
686 const MachineOperand &Loc = locations[LocNo];
689 extendDef(Idx, LocNo, nullptr, nullptr, nullptr, LIS, MDT, UVS);
693 // Register locations are constrained to where the register value is live.
694 if (TargetRegisterInfo::isVirtualRegister(Loc.getReg())) {
695 LiveInterval *LI = nullptr;
696 const VNInfo *VNI = nullptr;
697 if (LIS.hasInterval(Loc.getReg())) {
698 LI = &LIS.getInterval(Loc.getReg());
699 VNI = LI->getVNInfoAt(Idx);
701 SmallVector<SlotIndex, 16> Kills;
702 extendDef(Idx, LocNo, LI, VNI, &Kills, LIS, MDT, UVS);
704 addDefsFromCopies(LI, LocNo, Kills, Defs, MRI, LIS);
708 // For physregs, use the live range of the first regunit as a guide.
709 unsigned Unit = *MCRegUnitIterator(Loc.getReg(), &TRI);
710 LiveRange *LR = &LIS.getRegUnit(Unit);
711 const VNInfo *VNI = LR->getVNInfoAt(Idx);
712 // Don't track copies from physregs, it is too expensive.
713 extendDef(Idx, LocNo, LR, VNI, nullptr, LIS, MDT, UVS);
716 // Finally, erase all the undefs.
717 for (LocMap::iterator I = locInts.begin(); I.valid();)
718 if (I.value() == ~0u)
724 void LDVImpl::computeIntervals() {
725 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
726 UserValueScopes UVS(userValues[i]->getDebugLoc(), LS);
727 userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, *MDT, UVS);
728 userValues[i]->mapVirtRegs(this);
732 bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
735 LIS = &pass.getAnalysis<LiveIntervals>();
736 MDT = &pass.getAnalysis<MachineDominatorTree>();
737 TRI = mf.getSubtarget().getRegisterInfo();
739 DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
740 << mf.getName() << " **********\n");
742 bool Changed = collectDebugValues(mf);
744 DEBUG(print(dbgs()));
745 ModifiedMF = Changed;
749 static void removeDebugValues(MachineFunction &mf) {
750 for (MachineBasicBlock &MBB : mf) {
751 for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) {
752 if (!MBBI->isDebugValue()) {
756 MBBI = MBB.erase(MBBI);
761 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
764 if (!mf.getFunction()->getSubprogram()) {
765 removeDebugValues(mf);
769 pImpl = new LDVImpl(this);
770 return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
773 void LiveDebugVariables::releaseMemory() {
775 static_cast<LDVImpl*>(pImpl)->clear();
778 LiveDebugVariables::~LiveDebugVariables() {
780 delete static_cast<LDVImpl*>(pImpl);
783 //===----------------------------------------------------------------------===//
784 // Live Range Splitting
785 //===----------------------------------------------------------------------===//
788 UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
789 LiveIntervals& LIS) {
791 dbgs() << "Splitting Loc" << OldLocNo << '\t';
792 print(dbgs(), nullptr);
794 bool DidChange = false;
795 LocMap::iterator LocMapI;
796 LocMapI.setMap(locInts);
797 for (unsigned i = 0; i != NewRegs.size(); ++i) {
798 LiveInterval *LI = &LIS.getInterval(NewRegs[i]);
802 // Don't allocate the new LocNo until it is needed.
803 unsigned NewLocNo = ~0u;
805 // Iterate over the overlaps between locInts and LI.
806 LocMapI.find(LI->beginIndex());
807 if (!LocMapI.valid())
809 LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
810 LiveInterval::iterator LIE = LI->end();
811 while (LocMapI.valid() && LII != LIE) {
812 // At this point, we know that LocMapI.stop() > LII->start.
813 LII = LI->advanceTo(LII, LocMapI.start());
817 // Now LII->end > LocMapI.start(). Do we have an overlap?
818 if (LocMapI.value() == OldLocNo && LII->start < LocMapI.stop()) {
819 // Overlapping correct location. Allocate NewLocNo now.
820 if (NewLocNo == ~0u) {
821 MachineOperand MO = MachineOperand::CreateReg(LI->reg, false);
822 MO.setSubReg(locations[OldLocNo].getSubReg());
823 NewLocNo = getLocationNo(MO);
827 SlotIndex LStart = LocMapI.start();
828 SlotIndex LStop = LocMapI.stop();
830 // Trim LocMapI down to the LII overlap.
831 if (LStart < LII->start)
832 LocMapI.setStartUnchecked(LII->start);
833 if (LStop > LII->end)
834 LocMapI.setStopUnchecked(LII->end);
836 // Change the value in the overlap. This may trigger coalescing.
837 LocMapI.setValue(NewLocNo);
839 // Re-insert any removed OldLocNo ranges.
840 if (LStart < LocMapI.start()) {
841 LocMapI.insert(LStart, LocMapI.start(), OldLocNo);
843 assert(LocMapI.valid() && "Unexpected coalescing");
845 if (LStop > LocMapI.stop()) {
847 LocMapI.insert(LII->end, LStop, OldLocNo);
852 // Advance to the next overlap.
853 if (LII->end < LocMapI.stop()) {
856 LocMapI.advanceTo(LII->start);
859 if (!LocMapI.valid())
861 LII = LI->advanceTo(LII, LocMapI.start());
866 // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
867 locations.erase(locations.begin() + OldLocNo);
869 while (LocMapI.valid()) {
870 unsigned v = LocMapI.value();
872 DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
873 << LocMapI.stop() << ")\n");
877 LocMapI.setValueUnchecked(v-1);
882 DEBUG({dbgs() << "Split result: \t"; print(dbgs(), nullptr);});
887 UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
888 LiveIntervals &LIS) {
889 bool DidChange = false;
890 // Split locations referring to OldReg. Iterate backwards so splitLocation can
891 // safely erase unused locations.
892 for (unsigned i = locations.size(); i ; --i) {
893 unsigned LocNo = i-1;
894 const MachineOperand *Loc = &locations[LocNo];
895 if (!Loc->isReg() || Loc->getReg() != OldReg)
897 DidChange |= splitLocation(LocNo, NewRegs, LIS);
902 void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) {
903 bool DidChange = false;
904 for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
905 DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
910 // Map all of the new virtual registers.
911 UserValue *UV = lookupVirtReg(OldReg);
912 for (unsigned i = 0; i != NewRegs.size(); ++i)
913 mapVirtReg(NewRegs[i], UV);
916 void LiveDebugVariables::
917 splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) {
919 static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
923 UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI) {
924 // Iterate over locations in reverse makes it easier to handle coalescing.
925 for (unsigned i = locations.size(); i ; --i) {
926 unsigned LocNo = i-1;
927 MachineOperand &Loc = locations[LocNo];
928 // Only virtual registers are rewritten.
929 if (!Loc.isReg() || !Loc.getReg() ||
930 !TargetRegisterInfo::isVirtualRegister(Loc.getReg()))
932 unsigned VirtReg = Loc.getReg();
933 if (VRM.isAssignedReg(VirtReg) &&
934 TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) {
935 // This can create a %noreg operand in rare cases when the sub-register
936 // index is no longer available. That means the user value is in a
937 // non-existent sub-register, and %noreg is exactly what we want.
938 Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
939 } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
940 // FIXME: Translate SubIdx to a stackslot offset.
941 Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
946 coalesceLocation(LocNo);
950 /// findInsertLocation - Find an iterator for inserting a DBG_VALUE
952 static MachineBasicBlock::iterator
953 findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
954 LiveIntervals &LIS) {
955 SlotIndex Start = LIS.getMBBStartIdx(MBB);
956 Idx = Idx.getBaseIndex();
958 // Try to find an insert location by going backwards from Idx.
960 while (!(MI = LIS.getInstructionFromIndex(Idx))) {
961 // We've reached the beginning of MBB.
963 MachineBasicBlock::iterator I = MBB->SkipPHIsAndLabels(MBB->begin());
966 Idx = Idx.getPrevIndex();
969 // Don't insert anything after the first terminator, though.
970 return MI->isTerminator() ? MBB->getFirstTerminator() :
971 std::next(MachineBasicBlock::iterator(MI));
974 void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx,
977 const TargetInstrInfo &TII) {
978 MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS);
979 MachineOperand &Loc = locations[LocNo];
980 ++NumInsertedDebugValues;
982 assert(cast<DILocalVariable>(Variable)
983 ->isValidLocationForIntrinsic(getDebugLoc()) &&
984 "Expected inlined-at fields to agree");
986 BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE),
987 IsIndirect, Loc.getReg(), offset, Variable, Expression);
989 BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE))
992 .addMetadata(Variable)
993 .addMetadata(Expression);
996 void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
997 const TargetInstrInfo &TII) {
998 MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
1000 for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
1001 SlotIndex Start = I.start();
1002 SlotIndex Stop = I.stop();
1003 unsigned LocNo = I.value();
1004 DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo);
1005 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
1006 SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
1008 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
1009 insertDebugValue(&*MBB, Start, LocNo, LIS, TII);
1010 // This interval may span multiple basic blocks.
1011 // Insert a DBG_VALUE into each one.
1012 while(Stop > MBBEnd) {
1013 // Move to the next block.
1017 MBBEnd = LIS.getMBBEndIdx(&*MBB);
1018 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
1019 insertDebugValue(&*MBB, Start, LocNo, LIS, TII);
1021 DEBUG(dbgs() << '\n');
1029 void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
1030 DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
1033 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1034 for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
1035 DEBUG(userValues[i]->print(dbgs(), TRI));
1036 userValues[i]->rewriteLocations(*VRM, *TRI);
1037 userValues[i]->emitDebugValues(VRM, *LIS, *TII);
1042 void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
1044 static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
1047 bool LiveDebugVariables::doInitialization(Module &M) {
1048 return Pass::doInitialization(M);
1052 void LiveDebugVariables::dump() {
1054 static_cast<LDVImpl*>(pImpl)->print(dbgs());