1 //===- LiveDebugValues.cpp - Tracking Debug Value MIs ---------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 /// This pass implements a data flow analysis that propagates debug location
10 /// information by inserting additional DBG_VALUE insts into the machine
11 /// instruction stream. Before running, each DBG_VALUE inst corresponds to a
12 /// source assignment of a variable. Afterwards, a DBG_VALUE inst specifies a
13 /// variable location for the current basic block (see SourceLevelDebugging.rst).
15 /// This is a separate pass from DbgValueHistoryCalculator to facilitate
16 /// testing and improve modularity.
18 /// Each variable location is represented by a VarLoc object that identifies the
19 /// source variable, its current machine-location, and the DBG_VALUE inst that
20 /// specifies the location. Each VarLoc is indexed in the (function-scope)
21 /// VarLocMap, giving each VarLoc a unique index. Rather than operate directly
22 /// on machine locations, the dataflow analysis in this pass identifies
23 /// locations by their index in the VarLocMap, meaning all the variable
24 /// locations in a block can be described by a sparse vector of VarLocMap
27 //===----------------------------------------------------------------------===//
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/PostOrderIterator.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/SparseBitVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/UniqueVector.h"
37 #include "llvm/CodeGen/LexicalScopes.h"
38 #include "llvm/CodeGen/MachineBasicBlock.h"
39 #include "llvm/CodeGen/MachineFrameInfo.h"
40 #include "llvm/CodeGen/MachineFunction.h"
41 #include "llvm/CodeGen/MachineFunctionPass.h"
42 #include "llvm/CodeGen/MachineInstr.h"
43 #include "llvm/CodeGen/MachineInstrBuilder.h"
44 #include "llvm/CodeGen/MachineMemOperand.h"
45 #include "llvm/CodeGen/MachineOperand.h"
46 #include "llvm/CodeGen/PseudoSourceValue.h"
47 #include "llvm/CodeGen/RegisterScavenging.h"
48 #include "llvm/CodeGen/TargetFrameLowering.h"
49 #include "llvm/CodeGen/TargetInstrInfo.h"
50 #include "llvm/CodeGen/TargetLowering.h"
51 #include "llvm/CodeGen/TargetPassConfig.h"
52 #include "llvm/CodeGen/TargetRegisterInfo.h"
53 #include "llvm/CodeGen/TargetSubtargetInfo.h"
54 #include "llvm/Config/llvm-config.h"
55 #include "llvm/IR/DIBuilder.h"
56 #include "llvm/IR/DebugInfoMetadata.h"
57 #include "llvm/IR/DebugLoc.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/IR/Module.h"
60 #include "llvm/MC/MCRegisterInfo.h"
61 #include "llvm/Pass.h"
62 #include "llvm/Support/Casting.h"
63 #include "llvm/Support/Compiler.h"
64 #include "llvm/Support/Debug.h"
65 #include "llvm/Support/raw_ostream.h"
77 #define DEBUG_TYPE "livedebugvalues"
79 STATISTIC(NumInserted
, "Number of DBG_VALUE instructions inserted");
80 STATISTIC(NumRemoved
, "Number of DBG_VALUE instructions removed");
82 // If @MI is a DBG_VALUE with debug value described by a defined
83 // register, returns the number of this register. In the other case, returns 0.
84 static Register
isDbgValueDescribedByReg(const MachineInstr
&MI
) {
85 assert(MI
.isDebugValue() && "expected a DBG_VALUE");
86 assert(MI
.getNumOperands() == 4 && "malformed DBG_VALUE");
87 // If location of variable is described using a register (directly
88 // or indirectly), this register is always a first operand.
89 return MI
.getOperand(0).isReg() ? MI
.getOperand(0).getReg() : Register();
94 class LiveDebugValues
: public MachineFunctionPass
{
96 const TargetRegisterInfo
*TRI
;
97 const TargetInstrInfo
*TII
;
98 const TargetFrameLowering
*TFI
;
99 BitVector CalleeSavedRegs
;
102 enum struct TransferKind
{ TransferCopy
, TransferSpill
, TransferRestore
};
104 /// Keeps track of lexical scopes associated with a user value's source
106 class UserValueScopes
{
109 SmallPtrSet
<const MachineBasicBlock
*, 4> LBlocks
;
112 UserValueScopes(DebugLoc D
, LexicalScopes
&L
) : DL(std::move(D
)), LS(L
) {}
114 /// Return true if current scope dominates at least one machine
115 /// instruction in a given machine basic block.
116 bool dominates(MachineBasicBlock
*MBB
) {
118 LS
.getMachineBasicBlocks(DL
, LBlocks
);
119 return LBlocks
.count(MBB
) != 0 || LS
.dominates(DL
, MBB
);
123 using FragmentInfo
= DIExpression::FragmentInfo
;
124 using OptFragmentInfo
= Optional
<DIExpression::FragmentInfo
>;
126 /// Storage for identifying a potentially inlined instance of a variable,
127 /// or a fragment thereof.
128 class DebugVariable
{
129 const DILocalVariable
*Variable
;
130 OptFragmentInfo Fragment
;
131 const DILocation
*InlinedAt
;
133 /// Fragment that will overlap all other fragments. Used as default when
134 /// caller demands a fragment.
135 static const FragmentInfo DefaultFragment
;
138 DebugVariable(const DILocalVariable
*Var
, OptFragmentInfo
&&FragmentInfo
,
139 const DILocation
*InlinedAt
)
140 : Variable(Var
), Fragment(FragmentInfo
), InlinedAt(InlinedAt
) {}
142 DebugVariable(const DILocalVariable
*Var
, OptFragmentInfo
&FragmentInfo
,
143 const DILocation
*InlinedAt
)
144 : Variable(Var
), Fragment(FragmentInfo
), InlinedAt(InlinedAt
) {}
146 DebugVariable(const DILocalVariable
*Var
, const DIExpression
*DIExpr
,
147 const DILocation
*InlinedAt
)
148 : DebugVariable(Var
, DIExpr
->getFragmentInfo(), InlinedAt
) {}
150 DebugVariable(const MachineInstr
&MI
)
151 : DebugVariable(MI
.getDebugVariable(),
152 MI
.getDebugExpression()->getFragmentInfo(),
153 MI
.getDebugLoc()->getInlinedAt()) {}
155 const DILocalVariable
*getVar() const { return Variable
; }
156 const OptFragmentInfo
&getFragment() const { return Fragment
; }
157 const DILocation
*getInlinedAt() const { return InlinedAt
; }
159 const FragmentInfo
getFragmentDefault() const {
160 return Fragment
.getValueOr(DefaultFragment
);
163 static bool isFragmentDefault(FragmentInfo
&F
) {
164 return F
== DefaultFragment
;
167 bool operator==(const DebugVariable
&Other
) const {
168 return std::tie(Variable
, Fragment
, InlinedAt
) ==
169 std::tie(Other
.Variable
, Other
.Fragment
, Other
.InlinedAt
);
172 bool operator<(const DebugVariable
&Other
) const {
173 return std::tie(Variable
, Fragment
, InlinedAt
) <
174 std::tie(Other
.Variable
, Other
.Fragment
, Other
.InlinedAt
);
178 friend struct llvm::DenseMapInfo
<DebugVariable
>;
180 /// A pair of debug variable and value location.
182 // The location at which a spilled variable resides. It consists of a
183 // register and an offset.
187 bool operator==(const SpillLoc
&Other
) const {
188 return SpillBase
== Other
.SpillBase
&& SpillOffset
== Other
.SpillOffset
;
192 const DebugVariable Var
;
193 const MachineInstr
&MI
; ///< Only used for cloning a new DBG_VALUE.
194 mutable UserValueScopes UVS
;
201 } Kind
= InvalidKind
;
203 /// The value location. Stored separately to avoid repeatedly
204 /// extracting it from MI.
207 SpillLoc SpillLocation
;
210 const ConstantFP
*FPImm
;
211 const ConstantInt
*CImm
;
214 VarLoc(const MachineInstr
&MI
, LexicalScopes
&LS
,
215 VarLocKind K
= InvalidKind
)
216 : Var(MI
), MI(MI
), UVS(MI
.getDebugLoc(), LS
){
217 static_assert((sizeof(Loc
) == sizeof(uint64_t)),
218 "hash does not cover all members of Loc");
219 assert(MI
.isDebugValue() && "not a DBG_VALUE");
220 assert(MI
.getNumOperands() == 4 && "malformed DBG_VALUE");
221 if (int RegNo
= isDbgValueDescribedByReg(MI
)) {
222 Kind
= MI
.isDebugEntryValue() ? EntryValueKind
: RegisterKind
;
224 } else if (MI
.getOperand(0).isImm()) {
225 Kind
= ImmediateKind
;
226 Loc
.Immediate
= MI
.getOperand(0).getImm();
227 } else if (MI
.getOperand(0).isFPImm()) {
228 Kind
= ImmediateKind
;
229 Loc
.FPImm
= MI
.getOperand(0).getFPImm();
230 } else if (MI
.getOperand(0).isCImm()) {
231 Kind
= ImmediateKind
;
232 Loc
.CImm
= MI
.getOperand(0).getCImm();
234 assert((Kind
!= ImmediateKind
|| !MI
.isDebugEntryValue()) &&
235 "entry values must be register locations");
238 /// The constructor for spill locations.
239 VarLoc(const MachineInstr
&MI
, unsigned SpillBase
, int SpillOffset
,
240 LexicalScopes
&LS
, const MachineInstr
&OrigMI
)
241 : Var(MI
), MI(OrigMI
), UVS(MI
.getDebugLoc(), LS
) {
242 assert(MI
.isDebugValue() && "not a DBG_VALUE");
243 assert(MI
.getNumOperands() == 4 && "malformed DBG_VALUE");
245 Loc
.SpillLocation
= {SpillBase
, SpillOffset
};
248 // Is the Loc field a constant or constant object?
249 bool isConstant() const { return Kind
== ImmediateKind
; }
251 /// If this variable is described by a register, return it,
252 /// otherwise return 0.
253 unsigned isDescribedByReg() const {
254 if (Kind
== RegisterKind
)
259 /// Determine whether the lexical scope of this value's debug location
261 bool dominates(MachineBasicBlock
&MBB
) const { return UVS
.dominates(&MBB
); }
263 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
264 LLVM_DUMP_METHOD
void dump() const { MI
.dump(); }
267 bool operator==(const VarLoc
&Other
) const {
268 return Kind
== Other
.Kind
&& Var
== Other
.Var
&&
269 Loc
.Hash
== Other
.Loc
.Hash
;
272 /// This operator guarantees that VarLocs are sorted by Variable first.
273 bool operator<(const VarLoc
&Other
) const {
274 return std::tie(Var
, Kind
, Loc
.Hash
) <
275 std::tie(Other
.Var
, Other
.Kind
, Other
.Loc
.Hash
);
279 using DebugParamMap
= SmallDenseMap
<const DILocalVariable
*, MachineInstr
*>;
280 using VarLocMap
= UniqueVector
<VarLoc
>;
281 using VarLocSet
= SparseBitVector
<>;
282 using VarLocInMBB
= SmallDenseMap
<const MachineBasicBlock
*, VarLocSet
>;
283 struct TransferDebugPair
{
284 MachineInstr
*TransferInst
;
285 MachineInstr
*DebugInst
;
287 using TransferMap
= SmallVector
<TransferDebugPair
, 4>;
289 // Types for recording sets of variable fragments that overlap. For a given
290 // local variable, we record all other fragments of that variable that could
291 // overlap it, to reduce search time.
292 using FragmentOfVar
=
293 std::pair
<const DILocalVariable
*, DIExpression::FragmentInfo
>;
295 DenseMap
<FragmentOfVar
, SmallVector
<DIExpression::FragmentInfo
, 1>>;
297 // Helper while building OverlapMap, a map of all fragments seen for a given
299 using VarToFragments
=
300 DenseMap
<const DILocalVariable
*, SmallSet
<FragmentInfo
, 4>>;
302 /// This holds the working set of currently open ranges. For fast
303 /// access, this is done both as a set of VarLocIDs, and a map of
304 /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
305 /// previous open ranges for the same variable.
306 class OpenRangesSet
{
308 SmallDenseMap
<DebugVariable
, unsigned, 8> Vars
;
309 OverlapMap
&OverlappingFragments
;
312 OpenRangesSet(OverlapMap
&_OLapMap
) : OverlappingFragments(_OLapMap
) {}
314 const VarLocSet
&getVarLocs() const { return VarLocs
; }
316 /// Terminate all open ranges for Var by removing it from the set.
317 void erase(DebugVariable Var
);
319 /// Terminate all open ranges listed in \c KillSet by removing
320 /// them from the set.
321 void erase(const VarLocSet
&KillSet
, const VarLocMap
&VarLocIDs
) {
322 VarLocs
.intersectWithComplement(KillSet
);
323 for (unsigned ID
: KillSet
)
324 Vars
.erase(VarLocIDs
[ID
].Var
);
327 /// Insert a new range into the set.
328 void insert(unsigned VarLocID
, DebugVariable Var
) {
329 VarLocs
.set(VarLocID
);
330 Vars
.insert({Var
, VarLocID
});
333 /// Insert a set of ranges.
334 void insertFromLocSet(const VarLocSet
&ToLoad
, const VarLocMap
&Map
) {
335 for (unsigned Id
: ToLoad
) {
336 const VarLoc
&Var
= Map
[Id
];
347 /// Return whether the set is empty or not.
349 assert(Vars
.empty() == VarLocs
.empty() && "open ranges are inconsistent");
350 return VarLocs
.empty();
354 bool isSpillInstruction(const MachineInstr
&MI
, MachineFunction
*MF
,
356 /// If a given instruction is identified as a spill, return the spill location
357 /// and set \p Reg to the spilled register.
358 Optional
<VarLoc::SpillLoc
> isRestoreInstruction(const MachineInstr
&MI
,
361 /// Given a spill instruction, extract the register and offset used to
362 /// address the spill location in a target independent way.
363 VarLoc::SpillLoc
extractSpillBaseRegAndOffset(const MachineInstr
&MI
);
364 void insertTransferDebugPair(MachineInstr
&MI
, OpenRangesSet
&OpenRanges
,
365 TransferMap
&Transfers
, VarLocMap
&VarLocIDs
,
366 unsigned OldVarID
, TransferKind Kind
,
367 unsigned NewReg
= 0);
369 void transferDebugValue(const MachineInstr
&MI
, OpenRangesSet
&OpenRanges
,
370 VarLocMap
&VarLocIDs
);
371 void transferSpillOrRestoreInst(MachineInstr
&MI
, OpenRangesSet
&OpenRanges
,
372 VarLocMap
&VarLocIDs
, TransferMap
&Transfers
);
373 void emitEntryValues(MachineInstr
&MI
, OpenRangesSet
&OpenRanges
,
374 VarLocMap
&VarLocIDs
, TransferMap
&Transfers
,
375 DebugParamMap
&DebugEntryVals
,
376 SparseBitVector
<> &KillSet
);
377 void transferRegisterCopy(MachineInstr
&MI
, OpenRangesSet
&OpenRanges
,
378 VarLocMap
&VarLocIDs
, TransferMap
&Transfers
);
379 void transferRegisterDef(MachineInstr
&MI
, OpenRangesSet
&OpenRanges
,
380 VarLocMap
&VarLocIDs
, TransferMap
&Transfers
,
381 DebugParamMap
&DebugEntryVals
);
382 bool transferTerminator(MachineBasicBlock
*MBB
, OpenRangesSet
&OpenRanges
,
383 VarLocInMBB
&OutLocs
, const VarLocMap
&VarLocIDs
);
385 void process(MachineInstr
&MI
, OpenRangesSet
&OpenRanges
,
386 VarLocInMBB
&OutLocs
, VarLocMap
&VarLocIDs
,
387 TransferMap
&Transfers
, DebugParamMap
&DebugEntryVals
,
388 bool transferChanges
, OverlapMap
&OverlapFragments
,
389 VarToFragments
&SeenFragments
);
391 void accumulateFragmentMap(MachineInstr
&MI
, VarToFragments
&SeenFragments
,
392 OverlapMap
&OLapMap
);
394 bool join(MachineBasicBlock
&MBB
, VarLocInMBB
&OutLocs
, VarLocInMBB
&InLocs
,
395 const VarLocMap
&VarLocIDs
,
396 SmallPtrSet
<const MachineBasicBlock
*, 16> &Visited
,
397 SmallPtrSetImpl
<const MachineBasicBlock
*> &ArtificialBlocks
,
398 VarLocInMBB
&PendingInLocs
);
400 /// Create DBG_VALUE insts for inlocs that have been propagated but
401 /// had their instruction creation deferred.
402 void flushPendingLocs(VarLocInMBB
&PendingInLocs
, VarLocMap
&VarLocIDs
);
404 bool ExtendRanges(MachineFunction
&MF
);
409 /// Default construct and initialize the pass.
412 /// Tell the pass manager which passes we depend on and what
413 /// information we preserve.
414 void getAnalysisUsage(AnalysisUsage
&AU
) const override
;
416 MachineFunctionProperties
getRequiredProperties() const override
{
417 return MachineFunctionProperties().set(
418 MachineFunctionProperties::Property::NoVRegs
);
421 /// Print to ostream with a message.
422 void printVarLocInMBB(const MachineFunction
&MF
, const VarLocInMBB
&V
,
423 const VarLocMap
&VarLocIDs
, const char *msg
,
424 raw_ostream
&Out
) const;
426 /// Calculate the liveness information for the given machine function.
427 bool runOnMachineFunction(MachineFunction
&MF
) override
;
430 } // end anonymous namespace
434 template <> struct DenseMapInfo
<LiveDebugValues::DebugVariable
> {
435 using DV
= LiveDebugValues::DebugVariable
;
436 using OptFragmentInfo
= LiveDebugValues::OptFragmentInfo
;
437 using FragmentInfo
= LiveDebugValues::FragmentInfo
;
439 // Empty key: no key should be generated that has no DILocalVariable.
440 static inline DV
getEmptyKey() {
441 return DV(nullptr, OptFragmentInfo(), nullptr);
444 // Difference in tombstone is that the Optional is meaningful
445 static inline DV
getTombstoneKey() {
446 return DV(nullptr, OptFragmentInfo({0, 0}), nullptr);
449 static unsigned getHashValue(const DV
&D
) {
451 const OptFragmentInfo
&Fragment
= D
.getFragment();
453 HV
= DenseMapInfo
<FragmentInfo
>::getHashValue(*Fragment
);
455 return hash_combine(D
.getVar(), HV
, D
.getInlinedAt());
458 static bool isEqual(const DV
&A
, const DV
&B
) { return A
== B
; }
463 //===----------------------------------------------------------------------===//
465 //===----------------------------------------------------------------------===//
467 const DIExpression::FragmentInfo
468 LiveDebugValues::DebugVariable::DefaultFragment
= {
469 std::numeric_limits
<uint64_t>::max(),
470 std::numeric_limits
<uint64_t>::min()};
472 char LiveDebugValues::ID
= 0;
474 char &llvm::LiveDebugValuesID
= LiveDebugValues::ID
;
476 INITIALIZE_PASS(LiveDebugValues
, DEBUG_TYPE
, "Live DEBUG_VALUE analysis",
479 /// Default construct and initialize the pass.
480 LiveDebugValues::LiveDebugValues() : MachineFunctionPass(ID
) {
481 initializeLiveDebugValuesPass(*PassRegistry::getPassRegistry());
484 /// Tell the pass manager which passes we depend on and what information we
486 void LiveDebugValues::getAnalysisUsage(AnalysisUsage
&AU
) const {
487 AU
.setPreservesCFG();
488 MachineFunctionPass::getAnalysisUsage(AU
);
491 /// Erase a variable from the set of open ranges, and additionally erase any
492 /// fragments that may overlap it.
493 void LiveDebugValues::OpenRangesSet::erase(DebugVariable Var
) {
495 auto DoErase
= [this](DebugVariable VarToErase
) {
496 auto It
= Vars
.find(VarToErase
);
497 if (It
!= Vars
.end()) {
498 unsigned ID
= It
->second
;
504 // Erase the variable/fragment that ends here.
507 // Extract the fragment. Interpret an empty fragment as one that covers all
509 FragmentInfo ThisFragment
= Var
.getFragmentDefault();
511 // There may be fragments that overlap the designated fragment. Look them up
512 // in the pre-computed overlap map, and erase them too.
513 auto MapIt
= OverlappingFragments
.find({Var
.getVar(), ThisFragment
});
514 if (MapIt
!= OverlappingFragments
.end()) {
515 for (auto Fragment
: MapIt
->second
) {
516 LiveDebugValues::OptFragmentInfo FragmentHolder
;
517 if (!DebugVariable::isFragmentDefault(Fragment
))
518 FragmentHolder
= LiveDebugValues::OptFragmentInfo(Fragment
);
519 DoErase({Var
.getVar(), FragmentHolder
, Var
.getInlinedAt()});
524 //===----------------------------------------------------------------------===//
525 // Debug Range Extension Implementation
526 //===----------------------------------------------------------------------===//
529 void LiveDebugValues::printVarLocInMBB(const MachineFunction
&MF
,
530 const VarLocInMBB
&V
,
531 const VarLocMap
&VarLocIDs
,
533 raw_ostream
&Out
) const {
534 Out
<< '\n' << msg
<< '\n';
535 for (const MachineBasicBlock
&BB
: MF
) {
536 const VarLocSet
&L
= V
.lookup(&BB
);
539 Out
<< "MBB: " << BB
.getNumber() << ":\n";
540 for (unsigned VLL
: L
) {
541 const VarLoc
&VL
= VarLocIDs
[VLL
];
542 Out
<< " Var: " << VL
.Var
.getVar()->getName();
551 LiveDebugValues::VarLoc::SpillLoc
552 LiveDebugValues::extractSpillBaseRegAndOffset(const MachineInstr
&MI
) {
553 assert(MI
.hasOneMemOperand() &&
554 "Spill instruction does not have exactly one memory operand?");
555 auto MMOI
= MI
.memoperands_begin();
556 const PseudoSourceValue
*PVal
= (*MMOI
)->getPseudoValue();
557 assert(PVal
->kind() == PseudoSourceValue::FixedStack
&&
558 "Inconsistent memory operand in spill instruction");
559 int FI
= cast
<FixedStackPseudoSourceValue
>(PVal
)->getFrameIndex();
560 const MachineBasicBlock
*MBB
= MI
.getParent();
562 int Offset
= TFI
->getFrameIndexReference(*MBB
->getParent(), FI
, Reg
);
563 return {Reg
, Offset
};
566 /// End all previous ranges related to @MI and start a new range from @MI
567 /// if it is a DBG_VALUE instr.
568 void LiveDebugValues::transferDebugValue(const MachineInstr
&MI
,
569 OpenRangesSet
&OpenRanges
,
570 VarLocMap
&VarLocIDs
) {
571 if (!MI
.isDebugValue())
573 const DILocalVariable
*Var
= MI
.getDebugVariable();
574 const DIExpression
*Expr
= MI
.getDebugExpression();
575 const DILocation
*DebugLoc
= MI
.getDebugLoc();
576 const DILocation
*InlinedAt
= DebugLoc
->getInlinedAt();
577 assert(Var
->isValidLocationForIntrinsic(DebugLoc
) &&
578 "Expected inlined-at fields to agree");
580 // End all previous ranges of Var.
581 DebugVariable
V(Var
, Expr
, InlinedAt
);
584 // Add the VarLoc to OpenRanges from this DBG_VALUE.
586 if (isDbgValueDescribedByReg(MI
) || MI
.getOperand(0).isImm() ||
587 MI
.getOperand(0).isFPImm() || MI
.getOperand(0).isCImm()) {
588 // Use normal VarLoc constructor for registers and immediates.
590 ID
= VarLocIDs
.insert(VL
);
591 OpenRanges
.insert(ID
, VL
.Var
);
592 } else if (MI
.hasOneMemOperand()) {
593 llvm_unreachable("DBG_VALUE with mem operand encountered after regalloc?");
595 // This must be an undefined location. We should leave OpenRanges closed.
596 assert(MI
.getOperand(0).isReg() && MI
.getOperand(0).getReg() == 0 &&
597 "Unexpected non-undef DBG_VALUE encountered");
601 void LiveDebugValues::emitEntryValues(MachineInstr
&MI
,
602 OpenRangesSet
&OpenRanges
,
603 VarLocMap
&VarLocIDs
,
604 TransferMap
&Transfers
,
605 DebugParamMap
&DebugEntryVals
,
606 SparseBitVector
<> &KillSet
) {
607 MachineFunction
*MF
= MI
.getParent()->getParent();
608 for (unsigned ID
: KillSet
) {
609 if (!VarLocIDs
[ID
].Var
.getVar()->isParameter())
612 const MachineInstr
*CurrDebugInstr
= &VarLocIDs
[ID
].MI
;
614 // If parameter's DBG_VALUE is not in the map that means we can't
615 // generate parameter's entry value.
616 if (!DebugEntryVals
.count(CurrDebugInstr
->getDebugVariable()))
619 auto ParamDebugInstr
= DebugEntryVals
[CurrDebugInstr
->getDebugVariable()];
620 DIExpression
*NewExpr
= DIExpression::prepend(
621 ParamDebugInstr
->getDebugExpression(), DIExpression::EntryValue
);
622 MachineInstr
*EntryValDbgMI
=
623 BuildMI(*MF
, ParamDebugInstr
->getDebugLoc(), ParamDebugInstr
->getDesc(),
624 ParamDebugInstr
->isIndirectDebugValue(),
625 ParamDebugInstr
->getOperand(0).getReg(),
626 ParamDebugInstr
->getDebugVariable(), NewExpr
);
628 if (ParamDebugInstr
->isIndirectDebugValue())
629 EntryValDbgMI
->getOperand(1).setImm(
630 ParamDebugInstr
->getOperand(1).getImm());
632 Transfers
.push_back({&MI
, EntryValDbgMI
});
633 VarLoc
VL(*EntryValDbgMI
, LS
);
634 unsigned EntryValLocID
= VarLocIDs
.insert(VL
);
635 OpenRanges
.insert(EntryValLocID
, VL
.Var
);
639 /// Create new TransferDebugPair and insert it in \p Transfers. The VarLoc
640 /// with \p OldVarID should be deleted form \p OpenRanges and replaced with
641 /// new VarLoc. If \p NewReg is different than default zero value then the
642 /// new location will be register location created by the copy like instruction,
643 /// otherwise it is variable's location on the stack.
644 void LiveDebugValues::insertTransferDebugPair(
645 MachineInstr
&MI
, OpenRangesSet
&OpenRanges
, TransferMap
&Transfers
,
646 VarLocMap
&VarLocIDs
, unsigned OldVarID
, TransferKind Kind
,
648 const MachineInstr
*DebugInstr
= &VarLocIDs
[OldVarID
].MI
;
649 MachineFunction
*MF
= MI
.getParent()->getParent();
650 MachineInstr
*NewDebugInstr
;
652 auto ProcessVarLoc
= [&MI
, &OpenRanges
, &Transfers
, &DebugInstr
,
653 &VarLocIDs
](VarLoc
&VL
, MachineInstr
*NewDebugInstr
) {
654 unsigned LocId
= VarLocIDs
.insert(VL
);
656 // Close this variable's previous location range.
657 DebugVariable
V(*DebugInstr
);
660 OpenRanges
.insert(LocId
, VL
.Var
);
661 // The newly created DBG_VALUE instruction NewDebugInstr must be inserted
662 // after MI. Keep track of the pairing.
663 TransferDebugPair MIP
= {&MI
, NewDebugInstr
};
664 Transfers
.push_back(MIP
);
667 // End all previous ranges of Var.
668 OpenRanges
.erase(VarLocIDs
[OldVarID
].Var
);
670 case TransferKind::TransferCopy
: {
672 "No register supplied when handling a copy of a debug value");
673 // Create a DBG_VALUE instruction to describe the Var in its new
674 // register location.
675 NewDebugInstr
= BuildMI(
676 *MF
, DebugInstr
->getDebugLoc(), DebugInstr
->getDesc(),
677 DebugInstr
->isIndirectDebugValue(), NewReg
,
678 DebugInstr
->getDebugVariable(), DebugInstr
->getDebugExpression());
679 if (DebugInstr
->isIndirectDebugValue())
680 NewDebugInstr
->getOperand(1).setImm(DebugInstr
->getOperand(1).getImm());
681 VarLoc
VL(*NewDebugInstr
, LS
);
682 ProcessVarLoc(VL
, NewDebugInstr
);
683 LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for register copy: ";
684 NewDebugInstr
->print(dbgs(), /*IsStandalone*/false,
685 /*SkipOpers*/false, /*SkipDebugLoc*/false,
686 /*AddNewLine*/true, TII
));
689 case TransferKind::TransferSpill
: {
690 // Create a DBG_VALUE instruction to describe the Var in its spilled
692 VarLoc::SpillLoc SpillLocation
= extractSpillBaseRegAndOffset(MI
);
693 auto *SpillExpr
= DIExpression::prepend(DebugInstr
->getDebugExpression(),
694 DIExpression::ApplyOffset
,
695 SpillLocation
.SpillOffset
);
696 NewDebugInstr
= BuildMI(
697 *MF
, DebugInstr
->getDebugLoc(), DebugInstr
->getDesc(), true,
698 SpillLocation
.SpillBase
, DebugInstr
->getDebugVariable(), SpillExpr
);
699 VarLoc
VL(*NewDebugInstr
, SpillLocation
.SpillBase
,
700 SpillLocation
.SpillOffset
, LS
, *DebugInstr
);
701 ProcessVarLoc(VL
, NewDebugInstr
);
702 LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for spill: ";
703 NewDebugInstr
->print(dbgs(), /*IsStandalone*/false,
704 /*SkipOpers*/false, /*SkipDebugLoc*/false,
705 /*AddNewLine*/true, TII
));
708 case TransferKind::TransferRestore
: {
710 "No register supplied when handling a restore of a debug value");
711 MachineFunction
*MF
= MI
.getMF();
712 DIBuilder
DIB(*const_cast<Function
&>(MF
->getFunction()).getParent());
713 // DebugInstr refers to the pre-spill location, therefore we can reuse
715 NewDebugInstr
= BuildMI(
716 *MF
, DebugInstr
->getDebugLoc(), DebugInstr
->getDesc(), false, NewReg
,
717 DebugInstr
->getDebugVariable(), DebugInstr
->getDebugExpression());
718 VarLoc
VL(*NewDebugInstr
, LS
);
719 ProcessVarLoc(VL
, NewDebugInstr
);
720 LLVM_DEBUG(dbgs() << "Creating DBG_VALUE inst for register restore: ";
721 NewDebugInstr
->print(dbgs(), /*IsStandalone*/false,
722 /*SkipOpers*/false, /*SkipDebugLoc*/false,
723 /*AddNewLine*/true, TII
));
727 llvm_unreachable("Invalid transfer kind");
730 /// A definition of a register may mark the end of a range.
731 void LiveDebugValues::transferRegisterDef(
732 MachineInstr
&MI
, OpenRangesSet
&OpenRanges
, VarLocMap
&VarLocIDs
,
733 TransferMap
&Transfers
, DebugParamMap
&DebugEntryVals
) {
734 MachineFunction
*MF
= MI
.getMF();
735 const TargetLowering
*TLI
= MF
->getSubtarget().getTargetLowering();
736 unsigned SP
= TLI
->getStackPointerRegisterToSaveRestore();
737 SparseBitVector
<> KillSet
;
738 for (const MachineOperand
&MO
: MI
.operands()) {
739 // Determine whether the operand is a register def. Assume that call
740 // instructions never clobber SP, because some backends (e.g., AArch64)
741 // never list SP in the regmask.
742 if (MO
.isReg() && MO
.isDef() && MO
.getReg() &&
743 Register::isPhysicalRegister(MO
.getReg()) &&
744 !(MI
.isCall() && MO
.getReg() == SP
)) {
745 // Remove ranges of all aliased registers.
746 for (MCRegAliasIterator
RAI(MO
.getReg(), TRI
, true); RAI
.isValid(); ++RAI
)
747 for (unsigned ID
: OpenRanges
.getVarLocs())
748 if (VarLocIDs
[ID
].isDescribedByReg() == *RAI
)
750 } else if (MO
.isRegMask()) {
751 // Remove ranges of all clobbered registers. Register masks don't usually
752 // list SP as preserved. While the debug info may be off for an
753 // instruction or two around callee-cleanup calls, transferring the
754 // DEBUG_VALUE across the call is still a better user experience.
755 for (unsigned ID
: OpenRanges
.getVarLocs()) {
756 unsigned Reg
= VarLocIDs
[ID
].isDescribedByReg();
757 if (Reg
&& Reg
!= SP
&& MO
.clobbersPhysReg(Reg
))
762 OpenRanges
.erase(KillSet
, VarLocIDs
);
764 if (auto *TPC
= getAnalysisIfAvailable
<TargetPassConfig
>()) {
765 auto &TM
= TPC
->getTM
<TargetMachine
>();
766 if (TM
.Options
.EnableDebugEntryValues
)
767 emitEntryValues(MI
, OpenRanges
, VarLocIDs
, Transfers
, DebugEntryVals
,
772 /// Decide if @MI is a spill instruction and return true if it is. We use 2
773 /// criteria to make this decision:
774 /// - Is this instruction a store to a spill slot?
775 /// - Is there a register operand that is both used and killed?
776 /// TODO: Store optimization can fold spills into other stores (including
777 /// other spills). We do not handle this yet (more than one memory operand).
778 bool LiveDebugValues::isSpillInstruction(const MachineInstr
&MI
,
779 MachineFunction
*MF
, unsigned &Reg
) {
780 SmallVector
<const MachineMemOperand
*, 1> Accesses
;
782 // TODO: Handle multiple stores folded into one.
783 if (!MI
.hasOneMemOperand())
786 if (!MI
.getSpillSize(TII
) && !MI
.getFoldedSpillSize(TII
))
787 return false; // This is not a spill instruction, since no valid size was
788 // returned from either function.
790 auto isKilledReg
= [&](const MachineOperand MO
, unsigned &Reg
) {
791 if (!MO
.isReg() || !MO
.isUse()) {
799 for (const MachineOperand
&MO
: MI
.operands()) {
800 // In a spill instruction generated by the InlineSpiller the spilled
801 // register has its kill flag set.
802 if (isKilledReg(MO
, Reg
))
805 // Check whether next instruction kills the spilled register.
806 // FIXME: Current solution does not cover search for killed register in
807 // bundles and instructions further down the chain.
808 auto NextI
= std::next(MI
.getIterator());
809 // Skip next instruction that points to basic block end iterator.
810 if (MI
.getParent()->end() == NextI
)
813 for (const MachineOperand
&MONext
: NextI
->operands()) {
814 // Return true if we came across the register from the
815 // previous spill instruction that is killed in NextI.
816 if (isKilledReg(MONext
, RegNext
) && RegNext
== Reg
)
821 // Return false if we didn't find spilled register.
825 Optional
<LiveDebugValues::VarLoc::SpillLoc
>
826 LiveDebugValues::isRestoreInstruction(const MachineInstr
&MI
,
827 MachineFunction
*MF
, unsigned &Reg
) {
828 if (!MI
.hasOneMemOperand())
831 // FIXME: Handle folded restore instructions with more than one memory
833 if (MI
.getRestoreSize(TII
)) {
834 Reg
= MI
.getOperand(0).getReg();
835 return extractSpillBaseRegAndOffset(MI
);
840 /// A spilled register may indicate that we have to end the current range of
841 /// a variable and create a new one for the spill location.
842 /// A restored register may indicate the reverse situation.
843 /// We don't want to insert any instructions in process(), so we just create
844 /// the DBG_VALUE without inserting it and keep track of it in \p Transfers.
845 /// It will be inserted into the BB when we're done iterating over the
847 void LiveDebugValues::transferSpillOrRestoreInst(MachineInstr
&MI
,
848 OpenRangesSet
&OpenRanges
,
849 VarLocMap
&VarLocIDs
,
850 TransferMap
&Transfers
) {
851 MachineFunction
*MF
= MI
.getMF();
854 Optional
<VarLoc::SpillLoc
> Loc
;
856 LLVM_DEBUG(dbgs() << "Examining instruction: "; MI
.dump(););
858 if (isSpillInstruction(MI
, MF
, Reg
)) {
859 TKind
= TransferKind::TransferSpill
;
860 LLVM_DEBUG(dbgs() << "Recognized as spill: "; MI
.dump(););
861 LLVM_DEBUG(dbgs() << "Register: " << Reg
<< " " << printReg(Reg
, TRI
)
864 if (!(Loc
= isRestoreInstruction(MI
, MF
, Reg
)))
866 TKind
= TransferKind::TransferRestore
;
867 LLVM_DEBUG(dbgs() << "Recognized as restore: "; MI
.dump(););
868 LLVM_DEBUG(dbgs() << "Register: " << Reg
<< " " << printReg(Reg
, TRI
)
871 // Check if the register or spill location is the location of a debug value.
872 for (unsigned ID
: OpenRanges
.getVarLocs()) {
873 if (TKind
== TransferKind::TransferSpill
&&
874 VarLocIDs
[ID
].isDescribedByReg() == Reg
) {
875 LLVM_DEBUG(dbgs() << "Spilling Register " << printReg(Reg
, TRI
) << '('
876 << VarLocIDs
[ID
].Var
.getVar()->getName() << ")\n");
877 } else if (TKind
== TransferKind::TransferRestore
&&
878 VarLocIDs
[ID
].Loc
.SpillLocation
== *Loc
) {
879 LLVM_DEBUG(dbgs() << "Restoring Register " << printReg(Reg
, TRI
) << '('
880 << VarLocIDs
[ID
].Var
.getVar()->getName() << ")\n");
883 insertTransferDebugPair(MI
, OpenRanges
, Transfers
, VarLocIDs
, ID
, TKind
,
889 /// If \p MI is a register copy instruction, that copies a previously tracked
890 /// value from one register to another register that is callee saved, we
891 /// create new DBG_VALUE instruction described with copy destination register.
892 void LiveDebugValues::transferRegisterCopy(MachineInstr
&MI
,
893 OpenRangesSet
&OpenRanges
,
894 VarLocMap
&VarLocIDs
,
895 TransferMap
&Transfers
) {
896 const MachineOperand
*SrcRegOp
, *DestRegOp
;
898 if (!TII
->isCopyInstr(MI
, SrcRegOp
, DestRegOp
) || !SrcRegOp
->isKill() ||
902 auto isCalleSavedReg
= [&](unsigned Reg
) {
903 for (MCRegAliasIterator
RAI(Reg
, TRI
, true); RAI
.isValid(); ++RAI
)
904 if (CalleeSavedRegs
.test(*RAI
))
909 Register SrcReg
= SrcRegOp
->getReg();
910 Register DestReg
= DestRegOp
->getReg();
912 // We want to recognize instructions where destination register is callee
913 // saved register. If register that could be clobbered by the call is
914 // included, there would be a great chance that it is going to be clobbered
915 // soon. It is more likely that previous register location, which is callee
916 // saved, is going to stay unclobbered longer, even if it is killed.
917 if (!isCalleSavedReg(DestReg
))
920 for (unsigned ID
: OpenRanges
.getVarLocs()) {
921 if (VarLocIDs
[ID
].isDescribedByReg() == SrcReg
) {
922 insertTransferDebugPair(MI
, OpenRanges
, Transfers
, VarLocIDs
, ID
,
923 TransferKind::TransferCopy
, DestReg
);
929 /// Terminate all open ranges at the end of the current basic block.
930 bool LiveDebugValues::transferTerminator(MachineBasicBlock
*CurMBB
,
931 OpenRangesSet
&OpenRanges
,
932 VarLocInMBB
&OutLocs
,
933 const VarLocMap
&VarLocIDs
) {
934 bool Changed
= false;
936 if (OpenRanges
.empty())
939 LLVM_DEBUG(for (unsigned ID
940 : OpenRanges
.getVarLocs()) {
941 // Copy OpenRanges to OutLocs, if not already present.
942 dbgs() << "Add to OutLocs in MBB #" << CurMBB
->getNumber() << ": ";
943 VarLocIDs
[ID
].dump();
945 VarLocSet
&VLS
= OutLocs
[CurMBB
];
946 Changed
= VLS
!= OpenRanges
.getVarLocs();
947 // New OutLocs set may be different due to spill, restore or register
948 // copy instruction processing.
950 VLS
= OpenRanges
.getVarLocs();
955 /// Accumulate a mapping between each DILocalVariable fragment and other
956 /// fragments of that DILocalVariable which overlap. This reduces work during
957 /// the data-flow stage from "Find any overlapping fragments" to "Check if the
958 /// known-to-overlap fragments are present".
959 /// \param MI A previously unprocessed DEBUG_VALUE instruction to analyze for
961 /// \param SeenFragments Map from DILocalVariable to all fragments of that
962 /// Variable which are known to exist.
963 /// \param OverlappingFragments The overlap map being constructed, from one
964 /// Var/Fragment pair to a vector of fragments known to overlap.
965 void LiveDebugValues::accumulateFragmentMap(MachineInstr
&MI
,
966 VarToFragments
&SeenFragments
,
967 OverlapMap
&OverlappingFragments
) {
968 DebugVariable
MIVar(MI
);
969 FragmentInfo ThisFragment
= MIVar
.getFragmentDefault();
971 // If this is the first sighting of this variable, then we are guaranteed
972 // there are currently no overlapping fragments either. Initialize the set
973 // of seen fragments, record no overlaps for the current one, and return.
974 auto SeenIt
= SeenFragments
.find(MIVar
.getVar());
975 if (SeenIt
== SeenFragments
.end()) {
976 SmallSet
<FragmentInfo
, 4> OneFragment
;
977 OneFragment
.insert(ThisFragment
);
978 SeenFragments
.insert({MIVar
.getVar(), OneFragment
});
980 OverlappingFragments
.insert({{MIVar
.getVar(), ThisFragment
}, {}});
984 // If this particular Variable/Fragment pair already exists in the overlap
985 // map, it has already been accounted for.
987 OverlappingFragments
.insert({{MIVar
.getVar(), ThisFragment
}, {}});
988 if (!IsInOLapMap
.second
)
991 auto &ThisFragmentsOverlaps
= IsInOLapMap
.first
->second
;
992 auto &AllSeenFragments
= SeenIt
->second
;
994 // Otherwise, examine all other seen fragments for this variable, with "this"
995 // fragment being a previously unseen fragment. Record any pair of
996 // overlapping fragments.
997 for (auto &ASeenFragment
: AllSeenFragments
) {
998 // Does this previously seen fragment overlap?
999 if (DIExpression::fragmentsOverlap(ThisFragment
, ASeenFragment
)) {
1000 // Yes: Mark the current fragment as being overlapped.
1001 ThisFragmentsOverlaps
.push_back(ASeenFragment
);
1002 // Mark the previously seen fragment as being overlapped by the current
1004 auto ASeenFragmentsOverlaps
=
1005 OverlappingFragments
.find({MIVar
.getVar(), ASeenFragment
});
1006 assert(ASeenFragmentsOverlaps
!= OverlappingFragments
.end() &&
1007 "Previously seen var fragment has no vector of overlaps");
1008 ASeenFragmentsOverlaps
->second
.push_back(ThisFragment
);
1012 AllSeenFragments
.insert(ThisFragment
);
1015 /// This routine creates OpenRanges and OutLocs.
1016 void LiveDebugValues::process(MachineInstr
&MI
, OpenRangesSet
&OpenRanges
,
1017 VarLocInMBB
&OutLocs
, VarLocMap
&VarLocIDs
,
1018 TransferMap
&Transfers
, DebugParamMap
&DebugEntryVals
,
1019 bool transferChanges
,
1020 OverlapMap
&OverlapFragments
,
1021 VarToFragments
&SeenFragments
) {
1022 transferDebugValue(MI
, OpenRanges
, VarLocIDs
);
1023 transferRegisterDef(MI
, OpenRanges
, VarLocIDs
, Transfers
,
1025 if (transferChanges
) {
1026 transferRegisterCopy(MI
, OpenRanges
, VarLocIDs
, Transfers
);
1027 transferSpillOrRestoreInst(MI
, OpenRanges
, VarLocIDs
, Transfers
);
1029 // Build up a map of overlapping fragments on the first run through.
1030 if (MI
.isDebugValue())
1031 accumulateFragmentMap(MI
, SeenFragments
, OverlapFragments
);
1035 /// This routine joins the analysis results of all incoming edges in @MBB by
1036 /// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
1037 /// source variable in all the predecessors of @MBB reside in the same location.
1038 bool LiveDebugValues::join(
1039 MachineBasicBlock
&MBB
, VarLocInMBB
&OutLocs
, VarLocInMBB
&InLocs
,
1040 const VarLocMap
&VarLocIDs
,
1041 SmallPtrSet
<const MachineBasicBlock
*, 16> &Visited
,
1042 SmallPtrSetImpl
<const MachineBasicBlock
*> &ArtificialBlocks
,
1043 VarLocInMBB
&PendingInLocs
) {
1044 LLVM_DEBUG(dbgs() << "join MBB: " << MBB
.getNumber() << "\n");
1045 bool Changed
= false;
1047 VarLocSet InLocsT
; // Temporary incoming locations.
1049 // For all predecessors of this MBB, find the set of VarLocs that
1052 for (auto p
: MBB
.predecessors()) {
1053 // Ignore unvisited predecessor blocks. As we are processing
1054 // the blocks in reverse post-order any unvisited block can
1055 // be considered to not remove any incoming values.
1056 if (!Visited
.count(p
)) {
1057 LLVM_DEBUG(dbgs() << " ignoring unvisited pred MBB: " << p
->getNumber()
1061 auto OL
= OutLocs
.find(p
);
1062 // Join is null in case of empty OutLocs from any of the pred.
1063 if (OL
== OutLocs
.end())
1066 // Just copy over the Out locs to incoming locs for the first visited
1067 // predecessor, and for all other predecessors join the Out locs.
1069 InLocsT
= OL
->second
;
1071 InLocsT
&= OL
->second
;
1074 if (!InLocsT
.empty()) {
1075 for (auto ID
: InLocsT
)
1076 dbgs() << " gathered candidate incoming var: "
1077 << VarLocIDs
[ID
].Var
.getVar()->getName() << "\n";
1084 // Filter out DBG_VALUES that are out of scope.
1086 bool IsArtificial
= ArtificialBlocks
.count(&MBB
);
1087 if (!IsArtificial
) {
1088 for (auto ID
: InLocsT
) {
1089 if (!VarLocIDs
[ID
].dominates(MBB
)) {
1092 auto Name
= VarLocIDs
[ID
].Var
.getVar()->getName();
1093 dbgs() << " killing " << Name
<< ", it doesn't dominate MBB\n";
1098 InLocsT
.intersectWithComplement(KillSet
);
1100 // As we are processing blocks in reverse post-order we
1101 // should have processed at least one predecessor, unless it
1102 // is the entry block which has no predecessor.
1103 assert((NumVisited
|| MBB
.pred_empty()) &&
1104 "Should have processed at least one predecessor");
1106 VarLocSet
&ILS
= InLocs
[&MBB
];
1107 VarLocSet
&Pending
= PendingInLocs
[&MBB
];
1109 // New locations will have DBG_VALUE insts inserted at the start of the
1110 // block, after location propagation has finished. Record the insertions
1111 // that we need to perform in the Pending set.
1112 VarLocSet Diff
= InLocsT
;
1113 Diff
.intersectWithComplement(ILS
);
1114 for (auto ID
: Diff
) {
1121 // We may have lost locations by learning about a predecessor that either
1122 // loses or moves a variable. Find any locations in ILS that are not in the
1123 // new in-locations, and delete those.
1124 VarLocSet Removed
= ILS
;
1125 Removed
.intersectWithComplement(InLocsT
);
1126 for (auto ID
: Removed
) {
1136 void LiveDebugValues::flushPendingLocs(VarLocInMBB
&PendingInLocs
,
1137 VarLocMap
&VarLocIDs
) {
1138 // PendingInLocs records all locations propagated into blocks, which have
1139 // not had DBG_VALUE insts created. Go through and create those insts now.
1140 for (auto &Iter
: PendingInLocs
) {
1141 // Map is keyed on a constant pointer, unwrap it so we can insert insts.
1142 auto &MBB
= const_cast<MachineBasicBlock
&>(*Iter
.first
);
1143 VarLocSet
&Pending
= Iter
.second
;
1145 for (unsigned ID
: Pending
) {
1146 // The ID location is live-in to MBB -- work out what kind of machine
1147 // location it is and create a DBG_VALUE.
1148 const VarLoc
&DiffIt
= VarLocIDs
[ID
];
1149 const MachineInstr
*DebugInstr
= &DiffIt
.MI
;
1150 MachineInstr
*MI
= nullptr;
1152 if (DiffIt
.isConstant()) {
1153 MachineOperand
MO(DebugInstr
->getOperand(0));
1154 MI
= BuildMI(MBB
, MBB
.instr_begin(), DebugInstr
->getDebugLoc(),
1155 DebugInstr
->getDesc(), false, MO
,
1156 DebugInstr
->getDebugVariable(),
1157 DebugInstr
->getDebugExpression());
1159 auto *DebugExpr
= DebugInstr
->getDebugExpression();
1160 Register Reg
= DebugInstr
->getOperand(0).getReg();
1161 bool IsIndirect
= DebugInstr
->isIndirectDebugValue();
1163 if (DiffIt
.Kind
== VarLoc::SpillLocKind
) {
1164 // This is is a spilt location; DebugInstr refers to the unspilt
1165 // location. We need to rebuild the spilt location expression and
1166 // point the DBG_VALUE at the frame register.
1167 DebugExpr
= DIExpression::prepend(
1168 DebugInstr
->getDebugExpression(), DIExpression::ApplyOffset
,
1169 DiffIt
.Loc
.SpillLocation
.SpillOffset
);
1170 Reg
= TRI
->getFrameRegister(*DebugInstr
->getMF());
1174 MI
= BuildMI(MBB
, MBB
.instr_begin(), DebugInstr
->getDebugLoc(),
1175 DebugInstr
->getDesc(), IsIndirect
, Reg
,
1176 DebugInstr
->getDebugVariable(), DebugExpr
);
1178 LLVM_DEBUG(dbgs() << "Inserted: "; MI
->dump(););
1183 /// Calculate the liveness information for the given machine function and
1184 /// extend ranges across basic blocks.
1185 bool LiveDebugValues::ExtendRanges(MachineFunction
&MF
) {
1186 LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
1188 bool Changed
= false;
1189 bool OLChanged
= false;
1190 bool MBBJoined
= false;
1192 VarLocMap VarLocIDs
; // Map VarLoc<>unique ID for use in bitvectors.
1193 OverlapMap OverlapFragments
; // Map of overlapping variable fragments
1194 OpenRangesSet
OpenRanges(OverlapFragments
);
1195 // Ranges that are open until end of bb.
1196 VarLocInMBB OutLocs
; // Ranges that exist beyond bb.
1197 VarLocInMBB InLocs
; // Ranges that are incoming after joining.
1198 TransferMap Transfers
; // DBG_VALUEs associated with spills.
1199 VarLocInMBB PendingInLocs
; // Ranges that are incoming after joining, but
1200 // that we have deferred creating DBG_VALUE insts
1203 VarToFragments SeenFragments
;
1205 // Blocks which are artificial, i.e. blocks which exclusively contain
1206 // instructions without locations, or with line 0 locations.
1207 SmallPtrSet
<const MachineBasicBlock
*, 16> ArtificialBlocks
;
1209 DenseMap
<unsigned int, MachineBasicBlock
*> OrderToBB
;
1210 DenseMap
<MachineBasicBlock
*, unsigned int> BBToOrder
;
1211 std::priority_queue
<unsigned int, std::vector
<unsigned int>,
1212 std::greater
<unsigned int>>
1214 std::priority_queue
<unsigned int, std::vector
<unsigned int>,
1215 std::greater
<unsigned int>>
1218 enum : bool { dontTransferChanges
= false, transferChanges
= true };
1220 // Besides parameter's modification, check whether a DBG_VALUE is inlined
1221 // in order to deduce whether the variable that it tracks comes from
1222 // a different function. If that is the case we can't track its entry value.
1223 auto IsUnmodifiedFuncParam
= [&](const MachineInstr
&MI
) {
1224 auto *DIVar
= MI
.getDebugVariable();
1225 return DIVar
->isParameter() && DIVar
->isNotModified() &&
1226 !MI
.getDebugLoc()->getInlinedAt();
1229 const TargetLowering
*TLI
= MF
.getSubtarget().getTargetLowering();
1230 unsigned SP
= TLI
->getStackPointerRegisterToSaveRestore();
1231 Register FP
= TRI
->getFrameRegister(MF
);
1232 auto IsRegOtherThanSPAndFP
= [&](const MachineOperand
&Op
) -> bool {
1233 return Op
.isReg() && Op
.getReg() != SP
&& Op
.getReg() != FP
;
1236 // Working set of currently collected debug variables mapped to DBG_VALUEs
1237 // representing candidates for production of debug entry values.
1238 DebugParamMap DebugEntryVals
;
1240 MachineBasicBlock
&First_MBB
= *(MF
.begin());
1241 // Only in the case of entry MBB collect DBG_VALUEs representing
1242 // function parameters in order to generate debug entry values for them.
1243 // Currently, we generate debug entry values only for parameters that are
1244 // unmodified throughout the function and located in a register.
1245 // TODO: Add support for parameters that are described as fragments.
1246 // TODO: Add support for modified arguments that can be expressed
1247 // by using its entry value.
1248 // TODO: Add support for local variables that are expressed in terms of
1249 // parameters entry values.
1250 for (auto &MI
: First_MBB
)
1251 if (MI
.isDebugValue() && IsUnmodifiedFuncParam(MI
) &&
1252 !MI
.isIndirectDebugValue() && IsRegOtherThanSPAndFP(MI
.getOperand(0)) &&
1253 !DebugEntryVals
.count(MI
.getDebugVariable()) &&
1254 !MI
.getDebugExpression()->isFragment())
1255 DebugEntryVals
[MI
.getDebugVariable()] = &MI
;
1257 // Initialize every mbb with OutLocs.
1258 // We are not looking at any spill instructions during the initial pass
1259 // over the BBs. The LiveDebugVariables pass has already created DBG_VALUE
1260 // instructions for spills of registers that are known to be user variables
1261 // within the BB in which the spill occurs.
1262 for (auto &MBB
: MF
) {
1263 for (auto &MI
: MBB
) {
1264 process(MI
, OpenRanges
, OutLocs
, VarLocIDs
, Transfers
, DebugEntryVals
,
1265 dontTransferChanges
, OverlapFragments
, SeenFragments
);
1267 transferTerminator(&MBB
, OpenRanges
, OutLocs
, VarLocIDs
);
1268 // Add any entry DBG_VALUE instructions necessitated by parameter
1270 for (auto &TR
: Transfers
) {
1271 MBB
.insertAfter(MachineBasicBlock::iterator(*TR
.TransferInst
),
1276 // Initialize pending inlocs.
1277 PendingInLocs
[&MBB
] = VarLocSet();
1280 auto hasNonArtificialLocation
= [](const MachineInstr
&MI
) -> bool {
1281 if (const DebugLoc
&DL
= MI
.getDebugLoc())
1282 return DL
.getLine() != 0;
1285 for (auto &MBB
: MF
)
1286 if (none_of(MBB
.instrs(), hasNonArtificialLocation
))
1287 ArtificialBlocks
.insert(&MBB
);
1289 LLVM_DEBUG(printVarLocInMBB(MF
, OutLocs
, VarLocIDs
,
1290 "OutLocs after initialization", dbgs()));
1292 ReversePostOrderTraversal
<MachineFunction
*> RPOT(&MF
);
1293 unsigned int RPONumber
= 0;
1294 for (auto RI
= RPOT
.begin(), RE
= RPOT
.end(); RI
!= RE
; ++RI
) {
1295 OrderToBB
[RPONumber
] = *RI
;
1296 BBToOrder
[*RI
] = RPONumber
;
1297 Worklist
.push(RPONumber
);
1300 // This is a standard "union of predecessor outs" dataflow problem.
1301 // To solve it, we perform join() and process() using the two worklist method
1302 // until the ranges converge.
1303 // Ranges have converged when both worklists are empty.
1304 SmallPtrSet
<const MachineBasicBlock
*, 16> Visited
;
1305 while (!Worklist
.empty() || !Pending
.empty()) {
1306 // We track what is on the pending worklist to avoid inserting the same
1307 // thing twice. We could avoid this with a custom priority queue, but this
1308 // is probably not worth it.
1309 SmallPtrSet
<MachineBasicBlock
*, 16> OnPending
;
1310 LLVM_DEBUG(dbgs() << "Processing Worklist\n");
1311 while (!Worklist
.empty()) {
1312 MachineBasicBlock
*MBB
= OrderToBB
[Worklist
.top()];
1314 MBBJoined
= join(*MBB
, OutLocs
, InLocs
, VarLocIDs
, Visited
,
1315 ArtificialBlocks
, PendingInLocs
);
1316 Visited
.insert(MBB
);
1320 // Now that we have started to extend ranges across BBs we need to
1321 // examine spill instructions to see whether they spill registers that
1322 // correspond to user variables.
1323 // First load any pending inlocs.
1324 OpenRanges
.insertFromLocSet(PendingInLocs
[MBB
], VarLocIDs
);
1325 for (auto &MI
: *MBB
)
1326 process(MI
, OpenRanges
, OutLocs
, VarLocIDs
, Transfers
,
1327 DebugEntryVals
, transferChanges
, OverlapFragments
,
1329 OLChanged
|= transferTerminator(MBB
, OpenRanges
, OutLocs
, VarLocIDs
);
1331 // Add any DBG_VALUE instructions necessitated by spills.
1332 for (auto &TR
: Transfers
)
1333 MBB
->insertAfter(MachineBasicBlock::iterator(*TR
.TransferInst
),
1337 LLVM_DEBUG(printVarLocInMBB(MF
, OutLocs
, VarLocIDs
,
1338 "OutLocs after propagating", dbgs()));
1339 LLVM_DEBUG(printVarLocInMBB(MF
, InLocs
, VarLocIDs
,
1340 "InLocs after propagating", dbgs()));
1344 for (auto s
: MBB
->successors())
1345 if (OnPending
.insert(s
).second
) {
1346 Pending
.push(BBToOrder
[s
]);
1351 Worklist
.swap(Pending
);
1352 // At this point, pending must be empty, since it was just the empty
1354 assert(Pending
.empty() && "Pending should be empty");
1357 // Deferred inlocs will not have had any DBG_VALUE insts created; do
1359 flushPendingLocs(PendingInLocs
, VarLocIDs
);
1361 LLVM_DEBUG(printVarLocInMBB(MF
, OutLocs
, VarLocIDs
, "Final OutLocs", dbgs()));
1362 LLVM_DEBUG(printVarLocInMBB(MF
, InLocs
, VarLocIDs
, "Final InLocs", dbgs()));
1366 bool LiveDebugValues::runOnMachineFunction(MachineFunction
&MF
) {
1367 if (!MF
.getFunction().getSubprogram())
1368 // LiveDebugValues will already have removed all DBG_VALUEs.
1371 // Skip functions from NoDebug compilation units.
1372 if (MF
.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
1373 DICompileUnit::NoDebug
)
1376 TRI
= MF
.getSubtarget().getRegisterInfo();
1377 TII
= MF
.getSubtarget().getInstrInfo();
1378 TFI
= MF
.getSubtarget().getFrameLowering();
1379 TFI
->determineCalleeSaves(MF
, CalleeSavedRegs
,
1380 std::make_unique
<RegScavenger
>().get());
1383 bool Changed
= ExtendRanges(MF
);