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/ArrayRef.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/IntervalMap.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/CodeGen/LexicalScopes.h"
32 #include "llvm/CodeGen/LiveInterval.h"
33 #include "llvm/CodeGen/LiveIntervals.h"
34 #include "llvm/CodeGen/MachineBasicBlock.h"
35 #include "llvm/CodeGen/MachineDominators.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineInstr.h"
38 #include "llvm/CodeGen/MachineInstrBuilder.h"
39 #include "llvm/CodeGen/MachineOperand.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/SlotIndexes.h"
42 #include "llvm/CodeGen/TargetInstrInfo.h"
43 #include "llvm/CodeGen/TargetOpcodes.h"
44 #include "llvm/CodeGen/TargetRegisterInfo.h"
45 #include "llvm/CodeGen/TargetSubtargetInfo.h"
46 #include "llvm/CodeGen/VirtRegMap.h"
47 #include "llvm/Config/llvm-config.h"
48 #include "llvm/IR/DebugInfoMetadata.h"
49 #include "llvm/IR/DebugLoc.h"
50 #include "llvm/IR/Function.h"
51 #include "llvm/IR/Metadata.h"
52 #include "llvm/MC/MCRegisterInfo.h"
53 #include "llvm/Pass.h"
54 #include "llvm/Support/Casting.h"
55 #include "llvm/Support/CommandLine.h"
56 #include "llvm/Support/Compiler.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/raw_ostream.h"
67 #define DEBUG_TYPE "livedebugvars"
70 EnableLDV("live-debug-variables", cl::init(true),
71 cl::desc("Enable the live debug variables pass"), cl::Hidden
);
73 STATISTIC(NumInsertedDebugValues
, "Number of DBG_VALUEs inserted");
75 char LiveDebugVariables::ID
= 0;
77 INITIALIZE_PASS_BEGIN(LiveDebugVariables
, DEBUG_TYPE
,
78 "Debug Variable Analysis", false, false)
79 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree
)
80 INITIALIZE_PASS_DEPENDENCY(LiveIntervals
)
81 INITIALIZE_PASS_END(LiveDebugVariables
, DEBUG_TYPE
,
82 "Debug Variable Analysis", false, false)
84 void LiveDebugVariables::getAnalysisUsage(AnalysisUsage
&AU
) const {
85 AU
.addRequired
<MachineDominatorTree
>();
86 AU
.addRequiredTransitive
<LiveIntervals
>();
88 MachineFunctionPass::getAnalysisUsage(AU
);
91 LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID
) {
92 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
95 enum : unsigned { UndefLocNo
= ~0U };
97 /// Describes a location by number along with some flags about the original
98 /// usage of the location.
99 class DbgValueLocation
{
101 DbgValueLocation(unsigned LocNo
, bool WasIndirect
)
102 : LocNo(LocNo
), WasIndirect(WasIndirect
) {
103 static_assert(sizeof(*this) == sizeof(unsigned), "bad bitfield packing");
104 assert(locNo() == LocNo
&& "location truncation");
107 DbgValueLocation() : LocNo(0), WasIndirect(0) {}
109 unsigned locNo() const {
110 // Fix up the undef location number, which gets truncated.
111 return LocNo
== INT_MAX
? UndefLocNo
: LocNo
;
113 bool wasIndirect() const { return WasIndirect
; }
114 bool isUndef() const { return locNo() == UndefLocNo
; }
116 DbgValueLocation
changeLocNo(unsigned NewLocNo
) const {
117 return DbgValueLocation(NewLocNo
, WasIndirect
);
120 friend inline bool operator==(const DbgValueLocation
&LHS
,
121 const DbgValueLocation
&RHS
) {
122 return LHS
.LocNo
== RHS
.LocNo
&& LHS
.WasIndirect
== RHS
.WasIndirect
;
125 friend inline bool operator!=(const DbgValueLocation
&LHS
,
126 const DbgValueLocation
&RHS
) {
127 return !(LHS
== RHS
);
132 unsigned WasIndirect
: 1;
135 /// Map of where a user value is live, and its location.
136 using LocMap
= IntervalMap
<SlotIndex
, DbgValueLocation
, 4>;
138 /// Map of stack slot offsets for spilled locations.
139 /// Non-spilled locations are not added to the map.
140 using SpillOffsetMap
= DenseMap
<unsigned, unsigned>;
146 /// A user value is a part of a debug info user variable.
148 /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
149 /// holds part of a user variable. The part is identified by a byte offset.
151 /// UserValues are grouped into equivalence classes for easier searching. Two
152 /// user values are related if they refer to the same variable, or if they are
153 /// held by the same virtual register. The equivalence class is the transitive
154 /// closure of that relation.
156 const DILocalVariable
*Variable
; ///< The debug info variable we are part of.
157 const DIExpression
*Expression
; ///< Any complex address expression.
158 DebugLoc dl
; ///< The debug location for the variable. This is
159 ///< used by dwarf writer to find lexical scope.
160 UserValue
*leader
; ///< Equivalence class leader.
161 UserValue
*next
= nullptr; ///< Next value in equivalence class, or null.
163 /// Numbered locations referenced by locmap.
164 SmallVector
<MachineOperand
, 4> locations
;
166 /// Map of slot indices where this value is live.
169 /// Set of interval start indexes that have been trimmed to the
171 SmallSet
<SlotIndex
, 2> trimmedDefs
;
173 /// Insert a DBG_VALUE into MBB at Idx for LocNo.
174 void insertDebugValue(MachineBasicBlock
*MBB
, SlotIndex StartIdx
,
175 SlotIndex StopIdx
, DbgValueLocation Loc
, bool Spilled
,
176 unsigned SpillOffset
, LiveIntervals
&LIS
,
177 const TargetInstrInfo
&TII
,
178 const TargetRegisterInfo
&TRI
);
180 /// Replace OldLocNo ranges with NewRegs ranges where NewRegs
181 /// is live. Returns true if any changes were made.
182 bool splitLocation(unsigned OldLocNo
, ArrayRef
<unsigned> NewRegs
,
186 /// Create a new UserValue.
187 UserValue(const DILocalVariable
*var
, const DIExpression
*expr
, DebugLoc L
,
188 LocMap::Allocator
&alloc
)
189 : Variable(var
), Expression(expr
), dl(std::move(L
)), leader(this),
192 /// Get the leader of this value's equivalence class.
193 UserValue
*getLeader() {
194 UserValue
*l
= leader
;
195 while (l
!= l
->leader
)
200 /// Return the next UserValue in the equivalence class.
201 UserValue
*getNext() const { return next
; }
203 /// Does this UserValue match the parameters?
204 bool match(const DILocalVariable
*Var
, const DIExpression
*Expr
,
205 const DILocation
*IA
) const {
206 // FIXME: The fragment should be part of the equivalence class, but not
207 // other things in the expression like stack values.
208 return Var
== Variable
&& Expr
== Expression
&& dl
->getInlinedAt() == IA
;
211 /// Merge equivalence classes.
212 static UserValue
*merge(UserValue
*L1
, UserValue
*L2
) {
213 L2
= L2
->getLeader();
216 L1
= L1
->getLeader();
219 // Splice L2 before L1's members.
226 End
->next
= L1
->next
;
231 /// Return the location number that matches Loc.
233 /// For undef values we always return location number UndefLocNo without
234 /// inserting anything in locations. Since locations is a vector and the
235 /// location number is the position in the vector and UndefLocNo is ~0,
236 /// we would need a very big vector to put the value at the right position.
237 unsigned getLocationNo(const MachineOperand
&LocMO
) {
239 if (LocMO
.getReg() == 0)
241 // For register locations we dont care about use/def and other flags.
242 for (unsigned i
= 0, e
= locations
.size(); i
!= e
; ++i
)
243 if (locations
[i
].isReg() &&
244 locations
[i
].getReg() == LocMO
.getReg() &&
245 locations
[i
].getSubReg() == LocMO
.getSubReg())
248 for (unsigned i
= 0, e
= locations
.size(); i
!= e
; ++i
)
249 if (LocMO
.isIdenticalTo(locations
[i
]))
251 locations
.push_back(LocMO
);
252 // We are storing a MachineOperand outside a MachineInstr.
253 locations
.back().clearParent();
254 // Don't store def operands.
255 if (locations
.back().isReg()) {
256 if (locations
.back().isDef())
257 locations
.back().setIsDead(false);
258 locations
.back().setIsUse();
260 return locations
.size() - 1;
263 /// Ensure that all virtual register locations are mapped.
264 void mapVirtRegs(LDVImpl
*LDV
);
266 /// Add a definition point to this value.
267 void addDef(SlotIndex Idx
, const MachineOperand
&LocMO
, bool IsIndirect
) {
268 DbgValueLocation
Loc(getLocationNo(LocMO
), IsIndirect
);
269 // Add a singular (Idx,Idx) -> Loc mapping.
270 LocMap::iterator I
= locInts
.find(Idx
);
271 if (!I
.valid() || I
.start() != Idx
)
272 I
.insert(Idx
, Idx
.getNextSlot(), Loc
);
274 // A later DBG_VALUE at the same SlotIndex overrides the old location.
278 /// Extend the current definition as far as possible down.
280 /// Stop when meeting an existing def or when leaving the live
281 /// range of VNI. End points where VNI is no longer live are added to Kills.
283 /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
284 /// data-flow analysis to propagate them beyond basic block boundaries.
286 /// \param Idx Starting point for the definition.
287 /// \param Loc Location number to propagate.
288 /// \param LR Restrict liveness to where LR has the value VNI. May be null.
289 /// \param VNI When LR is not null, this is the value to restrict to.
290 /// \param [out] Kills Append end points of VNI's live range to Kills.
291 /// \param LIS Live intervals analysis.
292 void extendDef(SlotIndex Idx
, DbgValueLocation Loc
,
293 LiveRange
*LR
, const VNInfo
*VNI
,
294 SmallVectorImpl
<SlotIndex
> *Kills
,
297 /// The value in LI/LocNo may be copies to other registers. Determine if
298 /// any of the copies are available at the kill points, and add defs if
301 /// \param LI Scan for copies of the value in LI->reg.
302 /// \param LocNo Location number of LI->reg.
303 /// \param WasIndirect Indicates if the original use of LI->reg was indirect
304 /// \param Kills Points where the range of LocNo could be extended.
305 /// \param [in,out] NewDefs Append (Idx, LocNo) of inserted defs here.
306 void addDefsFromCopies(
307 LiveInterval
*LI
, unsigned LocNo
, bool WasIndirect
,
308 const SmallVectorImpl
<SlotIndex
> &Kills
,
309 SmallVectorImpl
<std::pair
<SlotIndex
, DbgValueLocation
>> &NewDefs
,
310 MachineRegisterInfo
&MRI
, LiveIntervals
&LIS
);
312 /// Compute the live intervals of all locations after collecting all their
314 void computeIntervals(MachineRegisterInfo
&MRI
, const TargetRegisterInfo
&TRI
,
315 LiveIntervals
&LIS
, LexicalScopes
&LS
);
317 /// Replace OldReg ranges with NewRegs ranges where NewRegs is
318 /// live. Returns true if any changes were made.
319 bool splitRegister(unsigned OldReg
, ArrayRef
<unsigned> NewRegs
,
322 /// Rewrite virtual register locations according to the provided virtual
323 /// register map. Record the stack slot offsets for the locations that
325 void rewriteLocations(VirtRegMap
&VRM
, const MachineFunction
&MF
,
326 const TargetInstrInfo
&TII
,
327 const TargetRegisterInfo
&TRI
,
328 SpillOffsetMap
&SpillOffsets
);
330 /// Recreate DBG_VALUE instruction from data structures.
331 void emitDebugValues(VirtRegMap
*VRM
, LiveIntervals
&LIS
,
332 const TargetInstrInfo
&TII
,
333 const TargetRegisterInfo
&TRI
,
334 const SpillOffsetMap
&SpillOffsets
);
336 /// Return DebugLoc of this UserValue.
337 DebugLoc
getDebugLoc() { return dl
;}
339 void print(raw_ostream
&, const TargetRegisterInfo
*);
342 /// Implementation of the LiveDebugVariables pass.
344 LiveDebugVariables
&pass
;
345 LocMap::Allocator allocator
;
346 MachineFunction
*MF
= nullptr;
348 const TargetRegisterInfo
*TRI
;
350 /// Whether emitDebugValues is called.
351 bool EmitDone
= false;
353 /// Whether the machine function is modified during the pass.
354 bool ModifiedMF
= false;
356 /// All allocated UserValue instances.
357 SmallVector
<std::unique_ptr
<UserValue
>, 8> userValues
;
359 /// Map virtual register to eq class leader.
360 using VRMap
= DenseMap
<unsigned, UserValue
*>;
361 VRMap virtRegToEqClass
;
363 /// Map user variable to eq class leader.
364 using UVMap
= DenseMap
<const DILocalVariable
*, UserValue
*>;
367 /// Find or create a UserValue.
368 UserValue
*getUserValue(const DILocalVariable
*Var
, const DIExpression
*Expr
,
371 /// Find the EC leader for VirtReg or null.
372 UserValue
*lookupVirtReg(unsigned VirtReg
);
374 /// Add DBG_VALUE instruction to our maps.
376 /// \param MI DBG_VALUE instruction
377 /// \param Idx Last valid SLotIndex before instruction.
379 /// \returns True if the DBG_VALUE instruction should be deleted.
380 bool handleDebugValue(MachineInstr
&MI
, SlotIndex Idx
);
382 /// Collect and erase all DBG_VALUE instructions, adding a UserValue def
383 /// for each instruction.
385 /// \param mf MachineFunction to be scanned.
387 /// \returns True if any debug values were found.
388 bool collectDebugValues(MachineFunction
&mf
);
390 /// Compute the live intervals of all user values after collecting all
391 /// their def points.
392 void computeIntervals();
395 LDVImpl(LiveDebugVariables
*ps
) : pass(*ps
) {}
397 bool runOnMachineFunction(MachineFunction
&mf
);
399 /// Release all memory.
403 virtRegToEqClass
.clear();
405 // Make sure we call emitDebugValues if the machine function was modified.
406 assert((!ModifiedMF
|| EmitDone
) &&
407 "Dbg values are not emitted in LDV");
412 /// Map virtual register to an equivalence class.
413 void mapVirtReg(unsigned VirtReg
, UserValue
*EC
);
415 /// Replace all references to OldReg with NewRegs.
416 void splitRegister(unsigned OldReg
, ArrayRef
<unsigned> NewRegs
);
418 /// Recreate DBG_VALUE instruction from data structures.
419 void emitDebugValues(VirtRegMap
*VRM
);
421 void print(raw_ostream
&);
424 } // end anonymous namespace
426 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
427 static void printDebugLoc(const DebugLoc
&DL
, raw_ostream
&CommentOS
,
428 const LLVMContext
&Ctx
) {
432 auto *Scope
= cast
<DIScope
>(DL
.getScope());
433 // Omit the directory, because it's likely to be long and uninteresting.
434 CommentOS
<< Scope
->getFilename();
435 CommentOS
<< ':' << DL
.getLine();
436 if (DL
.getCol() != 0)
437 CommentOS
<< ':' << DL
.getCol();
439 DebugLoc InlinedAtDL
= DL
.getInlinedAt();
444 printDebugLoc(InlinedAtDL
, CommentOS
, Ctx
);
448 static void printExtendedName(raw_ostream
&OS
, const DILocalVariable
*V
,
449 const DILocation
*DL
) {
450 const LLVMContext
&Ctx
= V
->getContext();
451 StringRef Res
= V
->getName();
453 OS
<< Res
<< "," << V
->getLine();
454 if (auto *InlinedAt
= DL
->getInlinedAt()) {
455 if (DebugLoc InlinedAtDL
= InlinedAt
) {
457 printDebugLoc(InlinedAtDL
, OS
, Ctx
);
463 void UserValue::print(raw_ostream
&OS
, const TargetRegisterInfo
*TRI
) {
464 auto *DV
= cast
<DILocalVariable
>(Variable
);
466 printExtendedName(OS
, DV
, dl
);
469 for (LocMap::const_iterator I
= locInts
.begin(); I
.valid(); ++I
) {
470 OS
<< " [" << I
.start() << ';' << I
.stop() << "):";
471 if (I
.value().isUndef())
474 OS
<< I
.value().locNo();
475 if (I
.value().wasIndirect())
479 for (unsigned i
= 0, e
= locations
.size(); i
!= e
; ++i
) {
480 OS
<< " Loc" << i
<< '=';
481 locations
[i
].print(OS
, TRI
);
486 void LDVImpl::print(raw_ostream
&OS
) {
487 OS
<< "********** DEBUG VARIABLES **********\n";
488 for (unsigned i
= 0, e
= userValues
.size(); i
!= e
; ++i
)
489 userValues
[i
]->print(OS
, TRI
);
493 void UserValue::mapVirtRegs(LDVImpl
*LDV
) {
494 for (unsigned i
= 0, e
= locations
.size(); i
!= e
; ++i
)
495 if (locations
[i
].isReg() &&
496 TargetRegisterInfo::isVirtualRegister(locations
[i
].getReg()))
497 LDV
->mapVirtReg(locations
[i
].getReg(), this);
500 UserValue
*LDVImpl::getUserValue(const DILocalVariable
*Var
,
501 const DIExpression
*Expr
, const DebugLoc
&DL
) {
502 UserValue
*&Leader
= userVarMap
[Var
];
504 UserValue
*UV
= Leader
->getLeader();
506 for (; UV
; UV
= UV
->getNext())
507 if (UV
->match(Var
, Expr
, DL
->getInlinedAt()))
511 userValues
.push_back(
512 llvm::make_unique
<UserValue
>(Var
, Expr
, DL
, allocator
));
513 UserValue
*UV
= userValues
.back().get();
514 Leader
= UserValue::merge(Leader
, UV
);
518 void LDVImpl::mapVirtReg(unsigned VirtReg
, UserValue
*EC
) {
519 assert(TargetRegisterInfo::isVirtualRegister(VirtReg
) && "Only map VirtRegs");
520 UserValue
*&Leader
= virtRegToEqClass
[VirtReg
];
521 Leader
= UserValue::merge(Leader
, EC
);
524 UserValue
*LDVImpl::lookupVirtReg(unsigned VirtReg
) {
525 if (UserValue
*UV
= virtRegToEqClass
.lookup(VirtReg
))
526 return UV
->getLeader();
530 bool LDVImpl::handleDebugValue(MachineInstr
&MI
, SlotIndex Idx
) {
531 // DBG_VALUE loc, offset, variable
532 if (MI
.getNumOperands() != 4 ||
533 !(MI
.getOperand(1).isReg() || MI
.getOperand(1).isImm()) ||
534 !MI
.getOperand(2).isMetadata()) {
535 LLVM_DEBUG(dbgs() << "Can't handle " << MI
);
539 // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual
540 // register that hasn't been defined yet. If we do not remove those here, then
541 // the re-insertion of the DBG_VALUE instruction after register allocation
542 // will be incorrect.
543 // TODO: If earlier passes are corrected to generate sane debug information
544 // (and if the machine verifier is improved to catch this), then these checks
545 // could be removed or replaced by asserts.
546 bool Discard
= false;
547 if (MI
.getOperand(0).isReg() &&
548 TargetRegisterInfo::isVirtualRegister(MI
.getOperand(0).getReg())) {
549 const unsigned Reg
= MI
.getOperand(0).getReg();
550 if (!LIS
->hasInterval(Reg
)) {
551 // The DBG_VALUE is described by a virtual register that does not have a
552 // live interval. Discard the DBG_VALUE.
554 LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx
557 // The DBG_VALUE is only valid if either Reg is live out from Idx, or Reg
558 // is defined dead at Idx (where Idx is the slot index for the instruction
559 // preceeding the DBG_VALUE).
560 const LiveInterval
&LI
= LIS
->getInterval(Reg
);
561 LiveQueryResult LRQ
= LI
.Query(Idx
);
562 if (!LRQ
.valueOutOrDead()) {
563 // We have found a DBG_VALUE with the value in a virtual register that
564 // is not live. Discard the DBG_VALUE.
566 LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx
572 // Get or create the UserValue for (variable,offset) here.
573 bool IsIndirect
= MI
.getOperand(1).isImm();
575 assert(MI
.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
576 const DILocalVariable
*Var
= MI
.getDebugVariable();
577 const DIExpression
*Expr
= MI
.getDebugExpression();
579 getUserValue(Var
, Expr
, MI
.getDebugLoc());
581 UV
->addDef(Idx
, MI
.getOperand(0), IsIndirect
);
583 MachineOperand MO
= MachineOperand::CreateReg(0U, false);
585 UV
->addDef(Idx
, MO
, false);
590 bool LDVImpl::collectDebugValues(MachineFunction
&mf
) {
591 bool Changed
= false;
592 for (MachineFunction::iterator MFI
= mf
.begin(), MFE
= mf
.end(); MFI
!= MFE
;
594 MachineBasicBlock
*MBB
= &*MFI
;
595 for (MachineBasicBlock::iterator MBBI
= MBB
->begin(), MBBE
= MBB
->end();
597 // Use the first debug instruction in the sequence to get a SlotIndex
598 // for following consecutive debug instructions.
599 if (!MBBI
->isDebugInstr()) {
603 // Debug instructions has no slot index. Use the previous
604 // non-debug instruction's SlotIndex as its SlotIndex.
607 ? LIS
->getMBBStartIdx(MBB
)
608 : LIS
->getInstructionIndex(*std::prev(MBBI
)).getRegSlot();
609 // Handle consecutive debug instructions with the same slot index.
611 // Only handle DBG_VALUE in handleDebugValue(). Skip all other
612 // kinds of debug instructions.
613 if (MBBI
->isDebugValue() && handleDebugValue(*MBBI
, Idx
)) {
614 MBBI
= MBB
->erase(MBBI
);
618 } while (MBBI
!= MBBE
&& MBBI
->isDebugInstr());
624 void UserValue::extendDef(SlotIndex Idx
, DbgValueLocation Loc
, LiveRange
*LR
,
625 const VNInfo
*VNI
, SmallVectorImpl
<SlotIndex
> *Kills
,
626 LiveIntervals
&LIS
) {
627 SlotIndex Start
= Idx
;
628 MachineBasicBlock
*MBB
= LIS
.getMBBFromIndex(Start
);
629 SlotIndex Stop
= LIS
.getMBBEndIdx(MBB
);
630 LocMap::iterator I
= locInts
.find(Start
);
632 // Limit to VNI's live range.
635 LiveInterval::Segment
*Segment
= LR
->getSegmentContaining(Start
);
636 if (!Segment
|| Segment
->valno
!= VNI
) {
638 Kills
->push_back(Start
);
641 if (Segment
->end
< Stop
) {
647 // There could already be a short def at Start.
648 if (I
.valid() && I
.start() <= Start
) {
649 // Stop when meeting a different location or an already extended interval.
650 Start
= Start
.getNextSlot();
651 if (I
.value() != Loc
|| I
.stop() != Start
)
653 // This is a one-slot placeholder. Just skip it.
657 // Limited by the next def.
658 if (I
.valid() && I
.start() < Stop
) {
662 // Limited by VNI's live range.
663 else if (!ToEnd
&& Kills
)
664 Kills
->push_back(Stop
);
667 I
.insert(Start
, Stop
, Loc
);
670 void UserValue::addDefsFromCopies(
671 LiveInterval
*LI
, unsigned LocNo
, bool WasIndirect
,
672 const SmallVectorImpl
<SlotIndex
> &Kills
,
673 SmallVectorImpl
<std::pair
<SlotIndex
, DbgValueLocation
>> &NewDefs
,
674 MachineRegisterInfo
&MRI
, LiveIntervals
&LIS
) {
677 // Don't track copies from physregs, there are too many uses.
678 if (!TargetRegisterInfo::isVirtualRegister(LI
->reg
))
681 // Collect all the (vreg, valno) pairs that are copies of LI.
682 SmallVector
<std::pair
<LiveInterval
*, const VNInfo
*>, 8> CopyValues
;
683 for (MachineOperand
&MO
: MRI
.use_nodbg_operands(LI
->reg
)) {
684 MachineInstr
*MI
= MO
.getParent();
685 // Copies of the full value.
686 if (MO
.getSubReg() || !MI
->isCopy())
688 unsigned DstReg
= MI
->getOperand(0).getReg();
690 // Don't follow copies to physregs. These are usually setting up call
691 // arguments, and the argument registers are always call clobbered. We are
692 // better off in the source register which could be a callee-saved register,
693 // or it could be spilled.
694 if (!TargetRegisterInfo::isVirtualRegister(DstReg
))
697 // Is LocNo extended to reach this copy? If not, another def may be blocking
698 // it, or we are looking at a wrong value of LI.
699 SlotIndex Idx
= LIS
.getInstructionIndex(*MI
);
700 LocMap::iterator I
= locInts
.find(Idx
.getRegSlot(true));
701 if (!I
.valid() || I
.value().locNo() != LocNo
)
704 if (!LIS
.hasInterval(DstReg
))
706 LiveInterval
*DstLI
= &LIS
.getInterval(DstReg
);
707 const VNInfo
*DstVNI
= DstLI
->getVNInfoAt(Idx
.getRegSlot());
708 assert(DstVNI
&& DstVNI
->def
== Idx
.getRegSlot() && "Bad copy value");
709 CopyValues
.push_back(std::make_pair(DstLI
, DstVNI
));
712 if (CopyValues
.empty())
715 LLVM_DEBUG(dbgs() << "Got " << CopyValues
.size() << " copies of " << *LI
718 // Try to add defs of the copied values for each kill point.
719 for (unsigned i
= 0, e
= Kills
.size(); i
!= e
; ++i
) {
720 SlotIndex Idx
= Kills
[i
];
721 for (unsigned j
= 0, e
= CopyValues
.size(); j
!= e
; ++j
) {
722 LiveInterval
*DstLI
= CopyValues
[j
].first
;
723 const VNInfo
*DstVNI
= CopyValues
[j
].second
;
724 if (DstLI
->getVNInfoAt(Idx
) != DstVNI
)
726 // Check that there isn't already a def at Idx
727 LocMap::iterator I
= locInts
.find(Idx
);
728 if (I
.valid() && I
.start() <= Idx
)
730 LLVM_DEBUG(dbgs() << "Kill at " << Idx
<< " covered by valno #"
731 << DstVNI
->id
<< " in " << *DstLI
<< '\n');
732 MachineInstr
*CopyMI
= LIS
.getInstructionFromIndex(DstVNI
->def
);
733 assert(CopyMI
&& CopyMI
->isCopy() && "Bad copy value");
734 unsigned LocNo
= getLocationNo(CopyMI
->getOperand(0));
735 DbgValueLocation
NewLoc(LocNo
, WasIndirect
);
736 I
.insert(Idx
, Idx
.getNextSlot(), NewLoc
);
737 NewDefs
.push_back(std::make_pair(Idx
, NewLoc
));
743 void UserValue::computeIntervals(MachineRegisterInfo
&MRI
,
744 const TargetRegisterInfo
&TRI
,
745 LiveIntervals
&LIS
, LexicalScopes
&LS
) {
746 SmallVector
<std::pair
<SlotIndex
, DbgValueLocation
>, 16> Defs
;
748 // Collect all defs to be extended (Skipping undefs).
749 for (LocMap::const_iterator I
= locInts
.begin(); I
.valid(); ++I
)
750 if (!I
.value().isUndef())
751 Defs
.push_back(std::make_pair(I
.start(), I
.value()));
753 // Extend all defs, and possibly add new ones along the way.
754 for (unsigned i
= 0; i
!= Defs
.size(); ++i
) {
755 SlotIndex Idx
= Defs
[i
].first
;
756 DbgValueLocation Loc
= Defs
[i
].second
;
757 const MachineOperand
&LocMO
= locations
[Loc
.locNo()];
759 if (!LocMO
.isReg()) {
760 extendDef(Idx
, Loc
, nullptr, nullptr, nullptr, LIS
);
764 // Register locations are constrained to where the register value is live.
765 if (TargetRegisterInfo::isVirtualRegister(LocMO
.getReg())) {
766 LiveInterval
*LI
= nullptr;
767 const VNInfo
*VNI
= nullptr;
768 if (LIS
.hasInterval(LocMO
.getReg())) {
769 LI
= &LIS
.getInterval(LocMO
.getReg());
770 VNI
= LI
->getVNInfoAt(Idx
);
772 SmallVector
<SlotIndex
, 16> Kills
;
773 extendDef(Idx
, Loc
, LI
, VNI
, &Kills
, LIS
);
774 // FIXME: Handle sub-registers in addDefsFromCopies. The problem is that
775 // if the original location for example is %vreg0:sub_hi, and we find a
776 // full register copy in addDefsFromCopies (at the moment it only handles
777 // full register copies), then we must add the sub1 sub-register index to
778 // the new location. However, that is only possible if the new virtual
779 // register is of the same regclass (or if there is an equivalent
780 // sub-register in that regclass). For now, simply skip handling copies if
781 // a sub-register is involved.
782 if (LI
&& !LocMO
.getSubReg())
783 addDefsFromCopies(LI
, Loc
.locNo(), Loc
.wasIndirect(), Kills
, Defs
, MRI
,
788 // For physregs, we only mark the start slot idx. DwarfDebug will see it
789 // as if the DBG_VALUE is valid up until the end of the basic block, or
790 // the next def of the physical register. So we do not need to extend the
791 // range. It might actually happen that the DBG_VALUE is the last use of
792 // the physical register (e.g. if this is an unused input argument to a
796 // The computed intervals may extend beyond the range of the debug
797 // location's lexical scope. In this case, splitting of an interval
798 // can result in an interval outside of the scope being created,
799 // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
800 // this, trim the intervals to the lexical scope.
802 LexicalScope
*Scope
= LS
.findLexicalScope(dl
);
807 LocMap::iterator I
= locInts
.begin();
809 // Iterate over the lexical scope ranges. Each time round the loop
810 // we check the intervals for overlap with the end of the previous
811 // range and the start of the next. The first range is handled as
812 // a special case where there is no PrevEnd.
813 for (const InsnRange
&Range
: Scope
->getRanges()) {
814 SlotIndex RStart
= LIS
.getInstructionIndex(*Range
.first
);
815 SlotIndex REnd
= LIS
.getInstructionIndex(*Range
.second
);
817 // At the start of each iteration I has been advanced so that
818 // I.stop() >= PrevEnd. Check for overlap.
819 if (PrevEnd
&& I
.start() < PrevEnd
) {
820 SlotIndex IStop
= I
.stop();
821 DbgValueLocation Loc
= I
.value();
823 // Stop overlaps previous end - trim the end of the interval to
825 I
.setStopUnchecked(PrevEnd
);
828 // If the interval also overlaps the start of the "next" (i.e.
829 // current) range create a new interval for the remainder (which
830 // may be further trimmed).
832 I
.insert(RStart
, IStop
, Loc
);
835 // Advance I so that I.stop() >= RStart, and check for overlap.
840 if (I
.start() < RStart
) {
841 // Interval start overlaps range - trim to the scope range.
842 I
.setStartUnchecked(RStart
);
843 // Remember that this interval was trimmed.
844 trimmedDefs
.insert(RStart
);
847 // The end of a lexical scope range is the last instruction in the
848 // range. To convert to an interval we need the index of the
849 // instruction after it.
850 REnd
= REnd
.getNextIndex();
852 // Advance I to first interval outside current range.
860 // Check for overlap with end of final range.
861 if (PrevEnd
&& I
.start() < PrevEnd
)
862 I
.setStopUnchecked(PrevEnd
);
865 void LDVImpl::computeIntervals() {
869 for (unsigned i
= 0, e
= userValues
.size(); i
!= e
; ++i
) {
870 userValues
[i
]->computeIntervals(MF
->getRegInfo(), *TRI
, *LIS
, LS
);
871 userValues
[i
]->mapVirtRegs(this);
875 bool LDVImpl::runOnMachineFunction(MachineFunction
&mf
) {
878 LIS
= &pass
.getAnalysis
<LiveIntervals
>();
879 TRI
= mf
.getSubtarget().getRegisterInfo();
880 LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
881 << mf
.getName() << " **********\n");
883 bool Changed
= collectDebugValues(mf
);
885 LLVM_DEBUG(print(dbgs()));
886 ModifiedMF
= Changed
;
890 static void removeDebugValues(MachineFunction
&mf
) {
891 for (MachineBasicBlock
&MBB
: mf
) {
892 for (auto MBBI
= MBB
.begin(), MBBE
= MBB
.end(); MBBI
!= MBBE
; ) {
893 if (!MBBI
->isDebugValue()) {
897 MBBI
= MBB
.erase(MBBI
);
902 bool LiveDebugVariables::runOnMachineFunction(MachineFunction
&mf
) {
905 if (!mf
.getFunction().getSubprogram()) {
906 removeDebugValues(mf
);
910 pImpl
= new LDVImpl(this);
911 return static_cast<LDVImpl
*>(pImpl
)->runOnMachineFunction(mf
);
914 void LiveDebugVariables::releaseMemory() {
916 static_cast<LDVImpl
*>(pImpl
)->clear();
919 LiveDebugVariables::~LiveDebugVariables() {
921 delete static_cast<LDVImpl
*>(pImpl
);
924 //===----------------------------------------------------------------------===//
925 // Live Range Splitting
926 //===----------------------------------------------------------------------===//
929 UserValue::splitLocation(unsigned OldLocNo
, ArrayRef
<unsigned> NewRegs
,
930 LiveIntervals
& LIS
) {
932 dbgs() << "Splitting Loc" << OldLocNo
<< '\t';
933 print(dbgs(), nullptr);
935 bool DidChange
= false;
936 LocMap::iterator LocMapI
;
937 LocMapI
.setMap(locInts
);
938 for (unsigned i
= 0; i
!= NewRegs
.size(); ++i
) {
939 LiveInterval
*LI
= &LIS
.getInterval(NewRegs
[i
]);
943 // Don't allocate the new LocNo until it is needed.
944 unsigned NewLocNo
= UndefLocNo
;
946 // Iterate over the overlaps between locInts and LI.
947 LocMapI
.find(LI
->beginIndex());
948 if (!LocMapI
.valid())
950 LiveInterval::iterator LII
= LI
->advanceTo(LI
->begin(), LocMapI
.start());
951 LiveInterval::iterator LIE
= LI
->end();
952 while (LocMapI
.valid() && LII
!= LIE
) {
953 // At this point, we know that LocMapI.stop() > LII->start.
954 LII
= LI
->advanceTo(LII
, LocMapI
.start());
958 // Now LII->end > LocMapI.start(). Do we have an overlap?
959 if (LocMapI
.value().locNo() == OldLocNo
&& LII
->start
< LocMapI
.stop()) {
960 // Overlapping correct location. Allocate NewLocNo now.
961 if (NewLocNo
== UndefLocNo
) {
962 MachineOperand MO
= MachineOperand::CreateReg(LI
->reg
, false);
963 MO
.setSubReg(locations
[OldLocNo
].getSubReg());
964 NewLocNo
= getLocationNo(MO
);
968 SlotIndex LStart
= LocMapI
.start();
969 SlotIndex LStop
= LocMapI
.stop();
970 DbgValueLocation OldLoc
= LocMapI
.value();
972 // Trim LocMapI down to the LII overlap.
973 if (LStart
< LII
->start
)
974 LocMapI
.setStartUnchecked(LII
->start
);
975 if (LStop
> LII
->end
)
976 LocMapI
.setStopUnchecked(LII
->end
);
978 // Change the value in the overlap. This may trigger coalescing.
979 LocMapI
.setValue(OldLoc
.changeLocNo(NewLocNo
));
981 // Re-insert any removed OldLocNo ranges.
982 if (LStart
< LocMapI
.start()) {
983 LocMapI
.insert(LStart
, LocMapI
.start(), OldLoc
);
985 assert(LocMapI
.valid() && "Unexpected coalescing");
987 if (LStop
> LocMapI
.stop()) {
989 LocMapI
.insert(LII
->end
, LStop
, OldLoc
);
994 // Advance to the next overlap.
995 if (LII
->end
< LocMapI
.stop()) {
998 LocMapI
.advanceTo(LII
->start
);
1001 if (!LocMapI
.valid())
1003 LII
= LI
->advanceTo(LII
, LocMapI
.start());
1008 // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
1009 locations
.erase(locations
.begin() + OldLocNo
);
1010 LocMapI
.goToBegin();
1011 while (LocMapI
.valid()) {
1012 DbgValueLocation v
= LocMapI
.value();
1013 if (v
.locNo() == OldLocNo
) {
1014 LLVM_DEBUG(dbgs() << "Erasing [" << LocMapI
.start() << ';'
1015 << LocMapI
.stop() << ")\n");
1018 // Undef values always have location number UndefLocNo, so don't change
1019 // locNo in that case. See getLocationNo().
1020 if (!v
.isUndef() && v
.locNo() > OldLocNo
)
1021 LocMapI
.setValueUnchecked(v
.changeLocNo(v
.locNo() - 1));
1027 dbgs() << "Split result: \t";
1028 print(dbgs(), nullptr);
1034 UserValue::splitRegister(unsigned OldReg
, ArrayRef
<unsigned> NewRegs
,
1035 LiveIntervals
&LIS
) {
1036 bool DidChange
= false;
1037 // Split locations referring to OldReg. Iterate backwards so splitLocation can
1038 // safely erase unused locations.
1039 for (unsigned i
= locations
.size(); i
; --i
) {
1040 unsigned LocNo
= i
-1;
1041 const MachineOperand
*Loc
= &locations
[LocNo
];
1042 if (!Loc
->isReg() || Loc
->getReg() != OldReg
)
1044 DidChange
|= splitLocation(LocNo
, NewRegs
, LIS
);
1049 void LDVImpl::splitRegister(unsigned OldReg
, ArrayRef
<unsigned> NewRegs
) {
1050 bool DidChange
= false;
1051 for (UserValue
*UV
= lookupVirtReg(OldReg
); UV
; UV
= UV
->getNext())
1052 DidChange
|= UV
->splitRegister(OldReg
, NewRegs
, *LIS
);
1057 // Map all of the new virtual registers.
1058 UserValue
*UV
= lookupVirtReg(OldReg
);
1059 for (unsigned i
= 0; i
!= NewRegs
.size(); ++i
)
1060 mapVirtReg(NewRegs
[i
], UV
);
1063 void LiveDebugVariables::
1064 splitRegister(unsigned OldReg
, ArrayRef
<unsigned> NewRegs
, LiveIntervals
&LIS
) {
1066 static_cast<LDVImpl
*>(pImpl
)->splitRegister(OldReg
, NewRegs
);
1069 void UserValue::rewriteLocations(VirtRegMap
&VRM
, const MachineFunction
&MF
,
1070 const TargetInstrInfo
&TII
,
1071 const TargetRegisterInfo
&TRI
,
1072 SpillOffsetMap
&SpillOffsets
) {
1073 // Build a set of new locations with new numbers so we can coalesce our
1074 // IntervalMap if two vreg intervals collapse to the same physical location.
1075 // Use MapVector instead of SetVector because MapVector::insert returns the
1076 // position of the previously or newly inserted element. The boolean value
1077 // tracks if the location was produced by a spill.
1078 // FIXME: This will be problematic if we ever support direct and indirect
1079 // frame index locations, i.e. expressing both variables in memory and
1080 // 'int x, *px = &x'. The "spilled" bit must become part of the location.
1081 MapVector
<MachineOperand
, std::pair
<bool, unsigned>> NewLocations
;
1082 SmallVector
<unsigned, 4> LocNoMap(locations
.size());
1083 for (unsigned I
= 0, E
= locations
.size(); I
!= E
; ++I
) {
1084 bool Spilled
= false;
1085 unsigned SpillOffset
= 0;
1086 MachineOperand Loc
= locations
[I
];
1087 // Only virtual registers are rewritten.
1088 if (Loc
.isReg() && Loc
.getReg() &&
1089 TargetRegisterInfo::isVirtualRegister(Loc
.getReg())) {
1090 unsigned VirtReg
= Loc
.getReg();
1091 if (VRM
.isAssignedReg(VirtReg
) &&
1092 TargetRegisterInfo::isPhysicalRegister(VRM
.getPhys(VirtReg
))) {
1093 // This can create a %noreg operand in rare cases when the sub-register
1094 // index is no longer available. That means the user value is in a
1095 // non-existent sub-register, and %noreg is exactly what we want.
1096 Loc
.substPhysReg(VRM
.getPhys(VirtReg
), TRI
);
1097 } else if (VRM
.getStackSlot(VirtReg
) != VirtRegMap::NO_STACK_SLOT
) {
1098 // Retrieve the stack slot offset.
1100 const MachineRegisterInfo
&MRI
= MF
.getRegInfo();
1101 const TargetRegisterClass
*TRC
= MRI
.getRegClass(VirtReg
);
1102 bool Success
= TII
.getStackSlotRange(TRC
, Loc
.getSubReg(), SpillSize
,
1105 // FIXME: Invalidate the location if the offset couldn't be calculated.
1108 Loc
= MachineOperand::CreateFI(VRM
.getStackSlot(VirtReg
));
1116 // Insert this location if it doesn't already exist and record a mapping
1117 // from the old number to the new number.
1118 auto InsertResult
= NewLocations
.insert({Loc
, {Spilled
, SpillOffset
}});
1119 unsigned NewLocNo
= std::distance(NewLocations
.begin(), InsertResult
.first
);
1120 LocNoMap
[I
] = NewLocNo
;
1123 // Rewrite the locations and record the stack slot offsets for spills.
1125 SpillOffsets
.clear();
1126 for (auto &Pair
: NewLocations
) {
1128 unsigned SpillOffset
;
1129 std::tie(Spilled
, SpillOffset
) = Pair
.second
;
1130 locations
.push_back(Pair
.first
);
1132 unsigned NewLocNo
= std::distance(&*NewLocations
.begin(), &Pair
);
1133 SpillOffsets
[NewLocNo
] = SpillOffset
;
1137 // Update the interval map, but only coalesce left, since intervals to the
1138 // right use the old location numbers. This should merge two contiguous
1139 // DBG_VALUE intervals with different vregs that were allocated to the same
1140 // physical register.
1141 for (LocMap::iterator I
= locInts
.begin(); I
.valid(); ++I
) {
1142 DbgValueLocation Loc
= I
.value();
1143 // Undef values don't exist in locations (and thus not in LocNoMap either)
1144 // so skip over them. See getLocationNo().
1147 unsigned NewLocNo
= LocNoMap
[Loc
.locNo()];
1148 I
.setValueUnchecked(Loc
.changeLocNo(NewLocNo
));
1149 I
.setStart(I
.start());
1153 /// Find an iterator for inserting a DBG_VALUE instruction.
1154 static MachineBasicBlock::iterator
1155 findInsertLocation(MachineBasicBlock
*MBB
, SlotIndex Idx
,
1156 LiveIntervals
&LIS
) {
1157 SlotIndex Start
= LIS
.getMBBStartIdx(MBB
);
1158 Idx
= Idx
.getBaseIndex();
1160 // Try to find an insert location by going backwards from Idx.
1162 while (!(MI
= LIS
.getInstructionFromIndex(Idx
))) {
1163 // We've reached the beginning of MBB.
1165 MachineBasicBlock::iterator I
= MBB
->SkipPHIsLabelsAndDebug(MBB
->begin());
1168 Idx
= Idx
.getPrevIndex();
1171 // Don't insert anything after the first terminator, though.
1172 return MI
->isTerminator() ? MBB
->getFirstTerminator() :
1173 std::next(MachineBasicBlock::iterator(MI
));
1176 /// Find an iterator for inserting the next DBG_VALUE instruction
1177 /// (or end if no more insert locations found).
1178 static MachineBasicBlock::iterator
1179 findNextInsertLocation(MachineBasicBlock
*MBB
,
1180 MachineBasicBlock::iterator I
,
1181 SlotIndex StopIdx
, MachineOperand
&LocMO
,
1183 const TargetRegisterInfo
&TRI
) {
1185 return MBB
->instr_end();
1186 unsigned Reg
= LocMO
.getReg();
1188 // Find the next instruction in the MBB that define the register Reg.
1189 while (I
!= MBB
->end() && !I
->isTerminator()) {
1190 if (!LIS
.isNotInMIMap(*I
) &&
1191 SlotIndex::isEarlierEqualInstr(StopIdx
, LIS
.getInstructionIndex(*I
)))
1193 if (I
->definesRegister(Reg
, &TRI
))
1194 // The insert location is directly after the instruction/bundle.
1195 return std::next(I
);
1201 void UserValue::insertDebugValue(MachineBasicBlock
*MBB
, SlotIndex StartIdx
,
1202 SlotIndex StopIdx
, DbgValueLocation Loc
,
1203 bool Spilled
, unsigned SpillOffset
,
1204 LiveIntervals
&LIS
, const TargetInstrInfo
&TII
,
1205 const TargetRegisterInfo
&TRI
) {
1206 SlotIndex MBBEndIdx
= LIS
.getMBBEndIdx(&*MBB
);
1207 // Only search within the current MBB.
1208 StopIdx
= (MBBEndIdx
< StopIdx
) ? MBBEndIdx
: StopIdx
;
1209 MachineBasicBlock::iterator I
= findInsertLocation(MBB
, StartIdx
, LIS
);
1210 // Undef values don't exist in locations so create new "noreg" register MOs
1211 // for them. See getLocationNo().
1212 MachineOperand MO
= !Loc
.isUndef() ?
1213 locations
[Loc
.locNo()] :
1214 MachineOperand::CreateReg(/* Reg */ 0, /* isDef */ false, /* isImp */ false,
1215 /* isKill */ false, /* isDead */ false,
1216 /* isUndef */ false, /* isEarlyClobber */ false,
1217 /* SubReg */ 0, /* isDebug */ true);
1219 ++NumInsertedDebugValues
;
1221 assert(cast
<DILocalVariable
>(Variable
)
1222 ->isValidLocationForIntrinsic(getDebugLoc()) &&
1223 "Expected inlined-at fields to agree");
1225 // If the location was spilled, the new DBG_VALUE will be indirect. If the
1226 // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
1227 // that the original virtual register was a pointer. Also, add the stack slot
1228 // offset for the spilled register to the expression.
1229 const DIExpression
*Expr
= Expression
;
1230 bool IsIndirect
= Loc
.wasIndirect();
1232 auto Deref
= IsIndirect
? DIExpression::WithDeref
: DIExpression::NoDeref
;
1234 DIExpression::prepend(Expr
, DIExpression::NoDeref
, SpillOffset
, Deref
);
1238 assert((!Spilled
|| MO
.isFI()) && "a spilled location must be a frame index");
1241 BuildMI(*MBB
, I
, getDebugLoc(), TII
.get(TargetOpcode::DBG_VALUE
),
1242 IsIndirect
, MO
, Variable
, Expr
);
1244 // Continue and insert DBG_VALUES after every redefinition of register
1245 // associated with the debug value within the range
1246 I
= findNextInsertLocation(MBB
, I
, StopIdx
, MO
, LIS
, TRI
);
1247 } while (I
!= MBB
->end());
1250 void UserValue::emitDebugValues(VirtRegMap
*VRM
, LiveIntervals
&LIS
,
1251 const TargetInstrInfo
&TII
,
1252 const TargetRegisterInfo
&TRI
,
1253 const SpillOffsetMap
&SpillOffsets
) {
1254 MachineFunction::iterator MFEnd
= VRM
->getMachineFunction().end();
1256 for (LocMap::const_iterator I
= locInts
.begin(); I
.valid();) {
1257 SlotIndex Start
= I
.start();
1258 SlotIndex Stop
= I
.stop();
1259 DbgValueLocation Loc
= I
.value();
1261 !Loc
.isUndef() ? SpillOffsets
.find(Loc
.locNo()) : SpillOffsets
.end();
1262 bool Spilled
= SpillIt
!= SpillOffsets
.end();
1263 unsigned SpillOffset
= Spilled
? SpillIt
->second
: 0;
1265 // If the interval start was trimmed to the lexical scope insert the
1266 // DBG_VALUE at the previous index (otherwise it appears after the
1267 // first instruction in the range).
1268 if (trimmedDefs
.count(Start
))
1269 Start
= Start
.getPrevIndex();
1271 LLVM_DEBUG(dbgs() << "\t[" << Start
<< ';' << Stop
<< "):" << Loc
.locNo());
1272 MachineFunction::iterator MBB
= LIS
.getMBBFromIndex(Start
)->getIterator();
1273 SlotIndex MBBEnd
= LIS
.getMBBEndIdx(&*MBB
);
1275 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB
) << '-' << MBBEnd
);
1276 insertDebugValue(&*MBB
, Start
, Stop
, Loc
, Spilled
, SpillOffset
, LIS
, TII
,
1278 // This interval may span multiple basic blocks.
1279 // Insert a DBG_VALUE into each one.
1280 while (Stop
> MBBEnd
) {
1281 // Move to the next block.
1285 MBBEnd
= LIS
.getMBBEndIdx(&*MBB
);
1286 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB
) << '-' << MBBEnd
);
1287 insertDebugValue(&*MBB
, Start
, Stop
, Loc
, Spilled
, SpillOffset
, LIS
, TII
,
1290 LLVM_DEBUG(dbgs() << '\n');
1298 void LDVImpl::emitDebugValues(VirtRegMap
*VRM
) {
1299 LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
1302 const TargetInstrInfo
*TII
= MF
->getSubtarget().getInstrInfo();
1303 SpillOffsetMap SpillOffsets
;
1304 for (unsigned i
= 0, e
= userValues
.size(); i
!= e
; ++i
) {
1305 LLVM_DEBUG(userValues
[i
]->print(dbgs(), TRI
));
1306 userValues
[i
]->rewriteLocations(*VRM
, *MF
, *TII
, *TRI
, SpillOffsets
);
1307 userValues
[i
]->emitDebugValues(VRM
, *LIS
, *TII
, *TRI
, SpillOffsets
);
1312 void LiveDebugVariables::emitDebugValues(VirtRegMap
*VRM
) {
1314 static_cast<LDVImpl
*>(pImpl
)->emitDebugValues(VRM
);
1317 bool LiveDebugVariables::doInitialization(Module
&M
) {
1318 return Pass::doInitialization(M
);
1321 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1322 LLVM_DUMP_METHOD
void LiveDebugVariables::dump() const {
1324 static_cast<LDVImpl
*>(pImpl
)->print(dbgs());