1 //===------ LiveDebugValues.cpp - Tracking Debug Value MIs ----------------===//
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 pass implements a data flow analysis that propagates debug location
11 /// information by inserting additional DBG_VALUE instructions into the machine
12 /// instruction stream. The pass internally builds debug location liveness
13 /// ranges to determine the points where additional DBG_VALUEs need to be
16 /// This is a separate pass from DbgValueHistoryCalculator to facilitate
17 /// testing and improve modularity.
19 //===----------------------------------------------------------------------===//
21 #include "llvm/ADT/PostOrderIterator.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SparseBitVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/UniqueVector.h"
26 #include "llvm/CodeGen/LexicalScopes.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineFunctionPass.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/Passes.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetRegisterInfo.h"
37 #include "llvm/Target/TargetSubtargetInfo.h"
43 #define DEBUG_TYPE "live-debug-values"
45 STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
49 // \brief If @MI is a DBG_VALUE with debug value described by a defined
50 // register, returns the number of this register. In the other case, returns 0.
51 static unsigned isDbgValueDescribedByReg(const MachineInstr &MI) {
52 assert(MI.isDebugValue() && "expected a DBG_VALUE");
53 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
54 // If location of variable is described using a register (directly
55 // or indirectly), this register is always a first operand.
56 return MI.getOperand(0).isReg() ? MI.getOperand(0).getReg() : 0;
59 class LiveDebugValues : public MachineFunctionPass {
62 const TargetRegisterInfo *TRI;
63 const TargetInstrInfo *TII;
66 /// Keeps track of lexical scopes associated with a user value's source
68 class UserValueScopes {
71 SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
74 UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(std::move(D)), LS(L) {}
76 /// Return true if current scope dominates at least one machine
77 /// instruction in a given machine basic block.
78 bool dominates(MachineBasicBlock *MBB) {
80 LS.getMachineBasicBlocks(DL, LBlocks);
81 return LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB);
85 /// Based on std::pair so it can be used as an index into a DenseMap.
86 typedef std::pair<const DILocalVariable *, const DILocation *>
88 /// A potentially inlined instance of a variable.
89 struct DebugVariable : public DebugVariableBase {
90 DebugVariable(const DILocalVariable *Var, const DILocation *InlinedAt)
91 : DebugVariableBase(Var, InlinedAt) {}
93 const DILocalVariable *getVar() const { return this->first; };
94 const DILocation *getInlinedAt() const { return this->second; };
96 bool operator<(const DebugVariable &DV) const {
97 if (getVar() == DV.getVar())
98 return getInlinedAt() < DV.getInlinedAt();
99 return getVar() < DV.getVar();
103 /// A pair of debug variable and value location.
105 const DebugVariable Var;
106 const MachineInstr &MI; ///< Only used for cloning a new DBG_VALUE.
107 mutable UserValueScopes UVS;
108 enum { InvalidKind = 0, RegisterKind } Kind;
110 /// The value location. Stored separately to avoid repeatedly
111 /// extracting it from MI.
120 VarLoc(const MachineInstr &MI, LexicalScopes &LS)
121 : Var(MI.getDebugVariable(), MI.getDebugLoc()->getInlinedAt()), MI(MI),
122 UVS(MI.getDebugLoc(), LS), Kind(InvalidKind) {
123 static_assert((sizeof(Loc) == sizeof(uint64_t)),
124 "hash does not cover all members of Loc");
125 assert(MI.isDebugValue() && "not a DBG_VALUE");
126 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
127 if (int RegNo = isDbgValueDescribedByReg(MI)) {
129 Loc.RegisterLoc.RegNo = RegNo;
131 MI.isIndirectDebugValue() ? MI.getOperand(1).getImm() : 0;
132 // We don't support offsets larger than 4GiB here. They are
133 // slated to be replaced with DIExpressions anyway.
134 if (Offset >= (1ULL << 32))
137 Loc.RegisterLoc.Offset = Offset;
141 /// If this variable is described by a register, return it,
142 /// otherwise return 0.
143 unsigned isDescribedByReg() const {
144 if (Kind == RegisterKind)
145 return Loc.RegisterLoc.RegNo;
149 /// Determine whether the lexical scope of this value's debug location
151 bool dominates(MachineBasicBlock &MBB) const { return UVS.dominates(&MBB); }
153 void dump() const { MI.dump(); }
155 bool operator==(const VarLoc &Other) const {
156 return Var == Other.Var && Loc.Hash == Other.Loc.Hash;
159 /// This operator guarantees that VarLocs are sorted by Variable first.
160 bool operator<(const VarLoc &Other) const {
161 if (Var == Other.Var)
162 return Loc.Hash < Other.Loc.Hash;
163 return Var < Other.Var;
167 typedef UniqueVector<VarLoc> VarLocMap;
168 typedef SparseBitVector<> VarLocSet;
169 typedef SmallDenseMap<const MachineBasicBlock *, VarLocSet> VarLocInMBB;
171 /// This holds the working set of currently open ranges. For fast
172 /// access, this is done both as a set of VarLocIDs, and a map of
173 /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
174 /// previous open ranges for the same variable.
175 class OpenRangesSet {
177 SmallDenseMap<DebugVariableBase, unsigned, 8> Vars;
180 const VarLocSet &getVarLocs() const { return VarLocs; }
182 /// Terminate all open ranges for Var by removing it from the set.
183 void erase(DebugVariable Var) {
184 auto It = Vars.find(Var);
185 if (It != Vars.end()) {
186 unsigned ID = It->second;
192 /// Terminate all open ranges listed in \c KillSet by removing
193 /// them from the set.
194 void erase(const VarLocSet &KillSet, const VarLocMap &VarLocIDs) {
195 VarLocs.intersectWithComplement(KillSet);
196 for (unsigned ID : KillSet)
197 Vars.erase(VarLocIDs[ID].Var);
200 /// Insert a new range into the set.
201 void insert(unsigned VarLocID, DebugVariableBase Var) {
202 VarLocs.set(VarLocID);
203 Vars.insert({Var, VarLocID});
212 /// Return whether the set is empty or not.
214 assert(Vars.empty() == VarLocs.empty() && "open ranges are inconsistent");
215 return VarLocs.empty();
219 void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
220 VarLocMap &VarLocIDs);
221 void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
222 const VarLocMap &VarLocIDs);
223 bool transferTerminatorInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
224 VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
225 bool transfer(MachineInstr &MI, OpenRangesSet &OpenRanges,
226 VarLocInMBB &OutLocs, VarLocMap &VarLocIDs);
228 bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
229 const VarLocMap &VarLocIDs,
230 SmallPtrSet<const MachineBasicBlock *, 16> &Visited);
232 bool ExtendRanges(MachineFunction &MF);
237 /// Default construct and initialize the pass.
240 /// Tell the pass manager which passes we depend on and what
241 /// information we preserve.
242 void getAnalysisUsage(AnalysisUsage &AU) const override;
244 MachineFunctionProperties getRequiredProperties() const override {
245 return MachineFunctionProperties().set(
246 MachineFunctionProperties::Property::NoVRegs);
249 /// Print to ostream with a message.
250 void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
251 const VarLocMap &VarLocIDs, const char *msg,
252 raw_ostream &Out) const;
254 /// Calculate the liveness information for the given machine function.
255 bool runOnMachineFunction(MachineFunction &MF) override;
260 //===----------------------------------------------------------------------===//
262 //===----------------------------------------------------------------------===//
264 char LiveDebugValues::ID = 0;
265 char &llvm::LiveDebugValuesID = LiveDebugValues::ID;
266 INITIALIZE_PASS(LiveDebugValues, "livedebugvalues", "Live DEBUG_VALUE analysis",
269 /// Default construct and initialize the pass.
270 LiveDebugValues::LiveDebugValues() : MachineFunctionPass(ID) {
271 initializeLiveDebugValuesPass(*PassRegistry::getPassRegistry());
274 /// Tell the pass manager which passes we depend on and what information we
276 void LiveDebugValues::getAnalysisUsage(AnalysisUsage &AU) const {
277 AU.setPreservesCFG();
278 MachineFunctionPass::getAnalysisUsage(AU);
281 //===----------------------------------------------------------------------===//
282 // Debug Range Extension Implementation
283 //===----------------------------------------------------------------------===//
285 void LiveDebugValues::printVarLocInMBB(const MachineFunction &MF,
286 const VarLocInMBB &V,
287 const VarLocMap &VarLocIDs,
289 raw_ostream &Out) const {
290 Out << '\n' << msg << '\n';
291 for (const MachineBasicBlock &BB : MF) {
292 const auto &L = V.lookup(&BB);
293 Out << "MBB: " << BB.getName() << ":\n";
294 for (unsigned VLL : L) {
295 const VarLoc &VL = VarLocIDs[VLL];
296 Out << " Var: " << VL.Var.getVar()->getName();
304 /// End all previous ranges related to @MI and start a new range from @MI
305 /// if it is a DBG_VALUE instr.
306 void LiveDebugValues::transferDebugValue(const MachineInstr &MI,
307 OpenRangesSet &OpenRanges,
308 VarLocMap &VarLocIDs) {
309 if (!MI.isDebugValue())
311 const DILocalVariable *Var = MI.getDebugVariable();
312 const DILocation *DebugLoc = MI.getDebugLoc();
313 const DILocation *InlinedAt = DebugLoc->getInlinedAt();
314 assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
315 "Expected inlined-at fields to agree");
317 // End all previous ranges of Var.
318 DebugVariable V(Var, InlinedAt);
321 // Add the VarLoc to OpenRanges from this DBG_VALUE.
322 // TODO: Currently handles DBG_VALUE which has only reg as location.
323 if (isDbgValueDescribedByReg(MI)) {
325 unsigned ID = VarLocIDs.insert(VL);
326 OpenRanges.insert(ID, VL.Var);
330 /// A definition of a register may mark the end of a range.
331 void LiveDebugValues::transferRegisterDef(MachineInstr &MI,
332 OpenRangesSet &OpenRanges,
333 const VarLocMap &VarLocIDs) {
334 MachineFunction *MF = MI.getParent()->getParent();
335 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
336 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
337 SparseBitVector<> KillSet;
338 for (const MachineOperand &MO : MI.operands()) {
339 if (MO.isReg() && MO.isDef() && MO.getReg() &&
340 TRI->isPhysicalRegister(MO.getReg())) {
341 // Remove ranges of all aliased registers.
342 for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
343 for (unsigned ID : OpenRanges.getVarLocs())
344 if (VarLocIDs[ID].isDescribedByReg() == *RAI)
346 } else if (MO.isRegMask()) {
347 // Remove ranges of all clobbered registers. Register masks don't usually
348 // list SP as preserved. While the debug info may be off for an
349 // instruction or two around callee-cleanup calls, transferring the
350 // DEBUG_VALUE across the call is still a better user experience.
351 for (unsigned ID : OpenRanges.getVarLocs()) {
352 unsigned Reg = VarLocIDs[ID].isDescribedByReg();
353 if (Reg && Reg != SP && MO.clobbersPhysReg(Reg))
358 OpenRanges.erase(KillSet, VarLocIDs);
361 /// Terminate all open ranges at the end of the current basic block.
362 bool LiveDebugValues::transferTerminatorInst(MachineInstr &MI,
363 OpenRangesSet &OpenRanges,
364 VarLocInMBB &OutLocs,
365 const VarLocMap &VarLocIDs) {
366 bool Changed = false;
367 const MachineBasicBlock *CurMBB = MI.getParent();
368 if (!(MI.isTerminator() || (&MI == &CurMBB->instr_back())))
371 if (OpenRanges.empty())
374 DEBUG(for (unsigned ID : OpenRanges.getVarLocs()) {
375 // Copy OpenRanges to OutLocs, if not already present.
376 dbgs() << "Add to OutLocs: "; VarLocIDs[ID].dump();
378 VarLocSet &VLS = OutLocs[CurMBB];
379 Changed = VLS |= OpenRanges.getVarLocs();
384 /// This routine creates OpenRanges and OutLocs.
385 bool LiveDebugValues::transfer(MachineInstr &MI, OpenRangesSet &OpenRanges,
386 VarLocInMBB &OutLocs, VarLocMap &VarLocIDs) {
387 bool Changed = false;
388 transferDebugValue(MI, OpenRanges, VarLocIDs);
389 transferRegisterDef(MI, OpenRanges, VarLocIDs);
390 Changed = transferTerminatorInst(MI, OpenRanges, OutLocs, VarLocIDs);
394 /// This routine joins the analysis results of all incoming edges in @MBB by
395 /// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
396 /// source variable in all the predecessors of @MBB reside in the same location.
397 bool LiveDebugValues::join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs,
398 VarLocInMBB &InLocs, const VarLocMap &VarLocIDs,
399 SmallPtrSet<const MachineBasicBlock *, 16> &Visited) {
400 DEBUG(dbgs() << "join MBB: " << MBB.getName() << "\n");
401 bool Changed = false;
403 VarLocSet InLocsT; // Temporary incoming locations.
405 // For all predecessors of this MBB, find the set of VarLocs that
408 for (auto p : MBB.predecessors()) {
409 // Ignore unvisited predecessor blocks. As we are processing
410 // the blocks in reverse post-order any unvisited block can
411 // be considered to not remove any incoming values.
412 if (!Visited.count(p))
414 auto OL = OutLocs.find(p);
415 // Join is null in case of empty OutLocs from any of the pred.
416 if (OL == OutLocs.end())
419 // Just copy over the Out locs to incoming locs for the first visited
420 // predecessor, and for all other predecessors join the Out locs.
422 InLocsT = OL->second;
424 InLocsT &= OL->second;
428 // Filter out DBG_VALUES that are out of scope.
430 for (auto ID : InLocsT)
431 if (!VarLocIDs[ID].dominates(MBB))
433 InLocsT.intersectWithComplement(KillSet);
435 // As we are processing blocks in reverse post-order we
436 // should have processed at least one predecessor, unless it
437 // is the entry block which has no predecessor.
438 assert((NumVisited || MBB.pred_empty()) &&
439 "Should have processed at least one predecessor");
443 VarLocSet &ILS = InLocs[&MBB];
445 // Insert DBG_VALUE instructions, if not already inserted.
446 VarLocSet Diff = InLocsT;
447 Diff.intersectWithComplement(ILS);
448 for (auto ID : Diff) {
449 // This VarLoc is not found in InLocs i.e. it is not yet inserted. So, a
450 // new range is started for the var from the mbb's beginning by inserting
451 // a new DBG_VALUE. transfer() will end this range however appropriate.
452 const VarLoc &DiffIt = VarLocIDs[ID];
453 const MachineInstr *DMI = &DiffIt.MI;
455 BuildMI(MBB, MBB.instr_begin(), DMI->getDebugLoc(), DMI->getDesc(),
456 DMI->isIndirectDebugValue(), DMI->getOperand(0).getReg(), 0,
457 DMI->getDebugVariable(), DMI->getDebugExpression());
458 if (DMI->isIndirectDebugValue())
459 MI->getOperand(1).setImm(DMI->getOperand(1).getImm());
460 DEBUG(dbgs() << "Inserted: "; MI->dump(););
468 /// Calculate the liveness information for the given machine function and
469 /// extend ranges across basic blocks.
470 bool LiveDebugValues::ExtendRanges(MachineFunction &MF) {
472 DEBUG(dbgs() << "\nDebug Range Extension\n");
474 bool Changed = false;
475 bool OLChanged = false;
476 bool MBBJoined = false;
478 VarLocMap VarLocIDs; // Map VarLoc<>unique ID for use in bitvectors.
479 OpenRangesSet OpenRanges; // Ranges that are open until end of bb.
480 VarLocInMBB OutLocs; // Ranges that exist beyond bb.
481 VarLocInMBB InLocs; // Ranges that are incoming after joining.
483 DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
484 DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
485 std::priority_queue<unsigned int, std::vector<unsigned int>,
486 std::greater<unsigned int>>
488 std::priority_queue<unsigned int, std::vector<unsigned int>,
489 std::greater<unsigned int>>
492 // Initialize every mbb with OutLocs.
495 transfer(MI, OpenRanges, OutLocs, VarLocIDs);
497 DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "OutLocs after initialization",
500 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
501 unsigned int RPONumber = 0;
502 for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) {
503 OrderToBB[RPONumber] = *RI;
504 BBToOrder[*RI] = RPONumber;
505 Worklist.push(RPONumber);
508 // This is a standard "union of predecessor outs" dataflow problem.
509 // To solve it, we perform join() and transfer() using the two worklist method
510 // until the ranges converge.
511 // Ranges have converged when both worklists are empty.
512 SmallPtrSet<const MachineBasicBlock *, 16> Visited;
513 while (!Worklist.empty() || !Pending.empty()) {
514 // We track what is on the pending worklist to avoid inserting the same
515 // thing twice. We could avoid this with a custom priority queue, but this
516 // is probably not worth it.
517 SmallPtrSet<MachineBasicBlock *, 16> OnPending;
518 DEBUG(dbgs() << "Processing Worklist\n");
519 while (!Worklist.empty()) {
520 MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
522 MBBJoined = join(*MBB, OutLocs, InLocs, VarLocIDs, Visited);
527 for (auto &MI : *MBB)
528 OLChanged |= transfer(MI, OpenRanges, OutLocs, VarLocIDs);
530 DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
531 "OutLocs after propagating", dbgs()));
532 DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
533 "InLocs after propagating", dbgs()));
537 for (auto s : MBB->successors())
538 if (OnPending.insert(s).second) {
539 Pending.push(BBToOrder[s]);
544 Worklist.swap(Pending);
545 // At this point, pending must be empty, since it was just the empty
547 assert(Pending.empty() && "Pending should be empty");
550 DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
551 DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
555 bool LiveDebugValues::runOnMachineFunction(MachineFunction &MF) {
556 if (!MF.getFunction()->getSubprogram())
557 // LiveDebugValues will already have removed all DBG_VALUEs.
560 TRI = MF.getSubtarget().getRegisterInfo();
561 TII = MF.getSubtarget().getInstrInfo();
564 bool Changed = ExtendRanges(MF);