1//===- LiveDebugVariables.cpp - Tracking debug info variables -------------===// 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 file implements the LiveDebugVariables analysis. 11// Remove all DBG_VALUE instructions referencing virtual registers and replace 12// them with a data structure tracking where live user variables are kept - in a 13// virtual register or in a stack slot. 15// Allow the data structure to be updated during register allocation when values 16// are moved between registers and stack slots. Finally emit new DBG_VALUE 17// instructions after register allocation is complete. 19//===----------------------------------------------------------------------===// 49#include "llvm/Config/llvm-config.h" 69#define DEBUG_TYPE "livedebugvars" 75STATISTIC(NumInsertedDebugValues,
"Number of DBG_VALUEs inserted");
76STATISTIC(NumInsertedDebugLabels,
"Number of DBG_LABELs inserted");
81"Debug Variable Analysis",
false,
false)
104/// Describes a debug variable value by location number and expression along 105/// with some flags about the original usage of the location. 106classDbgVariableValue {
110 : WasIndirect(WasIndirect), WasList(WasList),
Expression(&Expr) {
111assert(!(WasIndirect && WasList) &&
112"DBG_VALUE_LISTs should not be indirect.");
114for (
unsigned LocNo : NewLocs) {
115auto It =
find(LocNoVec, LocNo);
116if (It == LocNoVec.
end())
119// Loc duplicates an element in LocNos; replace references to Op 120// with references to the duplicating element. 121unsigned OpIdx = LocNoVec.
size();
122unsigned DuplicatingIdx = std::distance(LocNoVec.
begin(), It);
127// FIXME: Debug values referencing 64+ unique machine locations are rare and 128// currently unsupported for performance reasons. If we can verify that 129// performance is acceptable for such debug values, we can increase the 130// bit-width of LocNoCount to 14 to enable up to 16384 unique machine 131// locations. We will also need to verify that this does not cause issues 132// with LiveDebugVariables' use of IntervalMap. 133if (LocNoVec.
size() < 64) {
134 LocNoCount = LocNoVec.
size();
136 LocNos = std::make_unique<unsigned[]>(LocNoCount);
137 std::copy(LocNoVec.
begin(), LocNoVec.
end(), loc_nos_begin());
141"locations, dropping...\n");
143// Turn this into an undef debug value list; right now, the simplest form 144// of this is an expression with one arg, and an undef debug operand. 146 DIExpression::get(Expr.
getContext(), {dwarf::DW_OP_LLVM_arg, 0});
150 FragmentInfoOpt->SizeInBits);
151 LocNos = std::make_unique<unsigned[]>(LocNoCount);
156 DbgVariableValue() : LocNoCount(0), WasIndirect(
false), WasList(
false) {}
157 DbgVariableValue(
const DbgVariableValue &
Other)
158 : LocNoCount(
Other.LocNoCount), WasIndirect(
Other.getWasIndirect()),
160if (
Other.getLocNoCount()) {
161 LocNos.reset(
newunsigned[
Other.getLocNoCount()]);
162 std::copy(
Other.loc_nos_begin(),
Other.loc_nos_end(), loc_nos_begin());
166 DbgVariableValue &operator=(
const DbgVariableValue &
Other) {
169if (
Other.getLocNoCount()) {
170 LocNos.reset(
newunsigned[
Other.getLocNoCount()]);
171 std::copy(
Other.loc_nos_begin(),
Other.loc_nos_end(), loc_nos_begin());
175 LocNoCount =
Other.getLocNoCount();
176 WasIndirect =
Other.getWasIndirect();
177 WasList =
Other.getWasList();
183uint8_t getLocNoCount()
const{
return LocNoCount; }
184bool containsLocNo(
unsigned LocNo)
const{
187bool getWasIndirect()
const{
return WasIndirect; }
188bool getWasList()
const{
return WasList; }
191 DbgVariableValue decrementLocNosAfterPivot(
unsigned Pivot)
const{
193for (
unsigned LocNo : loc_nos())
196return DbgVariableValue(NewLocNos, WasIndirect, WasList, *
Expression);
201for (
unsigned LocNo : loc_nos())
202// Undef values don't exist in locations (and thus not in LocNoMap 203// either) so skip over them. See getLocationNo(). 205return DbgVariableValue(NewLocNos, WasIndirect, WasList, *
Expression);
208 DbgVariableValue changeLocNo(
unsigned OldLocNo,
unsigned NewLocNo)
const{
210 NewLocNos.
assign(loc_nos_begin(), loc_nos_end());
211auto OldLocIt =
find(NewLocNos, OldLocNo);
212assert(OldLocIt != NewLocNos.
end() &&
"Old location must be present.");
213 *OldLocIt = NewLocNo;
214return DbgVariableValue(NewLocNos, WasIndirect, WasList, *
Expression);
217bool hasLocNoGreaterThan(
unsigned LocNo)
const{
219 [LocNo](
unsigned ThisLocNo) {
return ThisLocNo > LocNo; });
223for (
constunsigned &Loc : loc_nos())
224OS << (&Loc == loc_nos_begin() ?
" " :
", ") << Loc;
228const DbgVariableValue &
RHS) {
229if (std::tie(
LHS.LocNoCount,
LHS.WasIndirect,
LHS.WasList,
231 std::tie(
RHS.LocNoCount,
RHS.WasIndirect,
RHS.WasList,
RHS.Expression))
233return std::equal(
LHS.loc_nos_begin(),
LHS.loc_nos_end(),
238const DbgVariableValue &
RHS) {
242unsigned *loc_nos_begin() {
return LocNos.get(); }
243constunsigned *loc_nos_begin()
const{
return LocNos.get(); }
244unsigned *loc_nos_end() {
return LocNos.get() + LocNoCount; }
245constunsigned *loc_nos_end()
const{
return LocNos.get() + LocNoCount; }
251// IntervalMap requires the value object to be very small, to the extent 252// that we do not have enough room for an std::vector. Using a C-style array 253// (with a unique_ptr wrapper for convenience) allows us to optimize for this 254// specific case by packing the array size into only 6 bits (it is highly 255// unlikely that any debug value will need 64+ locations). 256 std::unique_ptr<unsigned[]> LocNos;
264/// Map of where a user value is live to that value. 267/// Map of stack slot offsets for spilled locations. 268/// Non-spilled locations are not added to the map. 271/// Cache to save the location where it can be used as the starting 272/// position as input for calling MachineBasicBlock::SkipPHIsLabelsAndDebug. 273/// This is to prevent MachineBasicBlock::SkipPHIsLabelsAndDebug from 274/// repeatedly searching the same set of PHIs/Labels/Debug instructions 275/// if it is called many times for the same block. 281/// A user value is a part of a debug info user variable. 283/// A DBG_VALUE instruction notes that (a sub-register of) a virtual register 284/// holds part of a user variable. The part is identified by a byte offset. 286/// UserValues are grouped into equivalence classes for easier searching. Two 287/// user values are related if they are held by the same virtual register. The 288/// equivalence class is the transitive closure of that relation. 292constDILocalVariable *Variable;
///< The debug info variable we are part of. 293 /// The part of the variable we describe. 294const std::optional<DIExpression::FragmentInfo> Fragment;
295DebugLoc dl;
///< The debug location for the variable. This is 296 ///< used by dwarf writer to find lexical scope. 297 UserValue *leader;
///< Equivalence class leader. 298 UserValue *next =
nullptr;
///< Next value in equivalence class, or null. 300 /// Numbered locations referenced by locmap. 303 /// Map of slot indices where this value is live. 306 /// Set of interval start indexes that have been trimmed to the 310 /// Insert a DBG_VALUE into MBB at Idx for DbgValue. 319 /// Replace OldLocNo ranges with NewRegs ranges where NewRegs 320 /// is live. Returns true if any changes were made. 325 /// Create a new UserValue. 327 std::optional<DIExpression::FragmentInfo> Fragment,
DebugLoc L,
329 : Variable(var), Fragment(Fragment), dl(std::move(L)), leader(
this),
332 /// Get the leader of this value's equivalence class. 333 UserValue *getLeader() {
334 UserValue *l = leader;
335while (l != l->leader)
340 /// Return the next UserValue in the equivalence class. 341 UserValue *getNext()
const{
return next; }
343 /// Merge equivalence classes. 344static UserValue *
merge(UserValue *L1, UserValue *L2) {
345 L2 = L2->getLeader();
348 L1 = L1->getLeader();
351// Splice L2 before L1's members. 363 /// Return the location number that matches Loc. 365 /// For undef values we always return location number UndefLocNo without 366 /// inserting anything in locations. Since locations is a vector and the 367 /// location number is the position in the vector and UndefLocNo is ~0, 368 /// we would need a very big vector to put the value at the right position. 373// For register locations we dont care about use/def and other flags. 374for (
unsigned i = 0, e = locations.
size(); i != e; ++i)
375if (locations[i].
isReg() &&
377 locations[i].getSubReg() == LocMO.
getSubReg())
380for (
unsigned i = 0, e = locations.
size(); i != e; ++i)
384// We are storing a MachineOperand outside a MachineInstr. 385 locations.
back().clearParent();
386// Don't store def operands. 387if (locations.
back().isReg()) {
388if (locations.
back().isDef())
389 locations.
back().setIsDead(
false);
390 locations.
back().setIsUse();
392return locations.
size() - 1;
395 /// Remove (recycle) a location number. If \p LocNo still is used by the 396 /// locInts nothing is done. 397void removeLocationIfUnused(
unsigned LocNo) {
398// Bail out if LocNo still is used. 400const DbgVariableValue &
DbgValue =
I.value();
404// Remove the entry in the locations vector, and adjust all references to 405// location numbers above the removed entry. 408const DbgVariableValue &
DbgValue =
I.value();
409if (
DbgValue.hasLocNoGreaterThan(LocNo))
410I.setValueUnchecked(
DbgValue.decrementLocNosAfterPivot(LocNo));
414 /// Ensure that all virtual register locations are mapped. 417 /// Add a definition point to this user value. 423 DbgVariableValue
DbgValue(Locs, IsIndirect, IsList, Expr);
424// Add a singular (Idx,Idx) -> value mapping. 426if (!
I.valid() ||
I.start() !=
Idx)
429// A later DBG_VALUE at the same SlotIndex overrides the old location. 433 /// Extend the current definition as far as possible down. 435 /// Stop when meeting an existing def or when leaving the live 436 /// range of VNI. End points where VNI is no longer live are added to Kills. 438 /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a 439 /// data-flow analysis to propagate them beyond basic block boundaries. 441 /// \param Idx Starting point for the definition. 442 /// \param DbgValue value to propagate. 443 /// \param LiveIntervalInfo For each location number key in this map, 444 /// restricts liveness to where the LiveRange has the value equal to the\ 446 /// \param [out] Kills Append end points of VNI's live range to Kills. 447 /// \param LIS Live intervals analysis. 450SmallDenseMap<
unsigned, std::pair<LiveRange *, const VNInfo *>>
455 /// The value in LI may be copies to other registers. Determine if 456 /// any of the copies are available at the kill points, and add defs if 459 /// \param DbgValue Location number of LI->reg, and DIExpression. 460 /// \param LocIntervals Scan for copies of the value for each location in the 461 /// corresponding LiveInterval->reg. 462 /// \param KilledAt The point where the range of DbgValue could be extended. 463 /// \param [in,out] NewDefs Append (Idx, DbgValue) of inserted defs here. 464void addDefsFromCopies(
471 /// Compute the live intervals of all locations after collecting all their 476 /// Replace OldReg ranges with NewRegs ranges where NewRegs is 477 /// live. Returns true if any changes were made. 481 /// Rewrite virtual register locations according to the provided virtual 482 /// register map. Record the stack slot offsets for the locations that 489 /// Recreate DBG_VALUE instruction from data structures. 496 /// Return DebugLoc of this UserValue. 502/// A user label is a part of a debug info user label. 504constDILabel *Label;
///< The debug info label we are part of. 505DebugLoc dl;
///< The debug location for the label. This is 506 ///< used by dwarf writer to find lexical scope. 507SlotIndex loc;
///< Slot used by the debug label. 509 /// Insert a DBG_LABEL into MBB at Idx. 515 /// Create a new UserLabel. 517 : Label(label), dl(std::move(L)), loc(
Idx) {}
519 /// Does this UserLabel match the parameters? 522return Label == L && dl->getInlinedAt() == IA && loc ==
Index;
525 /// Recreate DBG_LABEL instruction from data structures. 529 /// Return DebugLoc of this UserLabel. 535}
// end anonymous namespace 539/// Implementation of the LiveDebugVariables pass. 551 /// Position and VReg of a PHI instruction during register allocation. 553SlotIndex SI;
/// Slot where this PHI occurs. 554Register Reg;
/// VReg this PHI occurs in. 555unsignedSubReg;
/// Qualifiying subregister for Reg. 558 /// Map from debug instruction number to PHI position during allocation. 559 std::map<unsigned, PHIValPos> PHIValToPos;
560 /// Index of, for each VReg, which debug instruction numbers and corresponding 561 /// PHIs are sensitive to splitting. Each VReg may have multiple PHI defs, 562 /// at different positions. 565 /// Record for any debug instructions unlinked from their blocks during 566 /// regalloc. Stores the instr and it's location, so that they can be 567 /// re-inserted after regalloc is over. 570SlotIndexIdx;
///< Slot position where MI should be re-inserted. 574 /// Collection of stored debug instructions, preserved until after regalloc. 577 /// Whether emitDebugValues is called. 580 /// Whether the machine function is modified during the pass. 581bool ModifiedMF =
false;
583 /// All allocated UserValue instances. 586 /// All allocated UserLabel instances. 589 /// Map virtual register to eq class leader. 591VRMap virtRegToEqClass;
593 /// Map to find existing UserValue instances. 597 /// Find or create a UserValue. 599 std::optional<DIExpression::FragmentInfo> Fragment,
602 /// Find the EC leader for VirtReg or null. 603 UserValue *lookupVirtReg(
Register VirtReg);
605 /// Add DBG_VALUE instruction to our maps. 607 /// \param MI DBG_VALUE instruction 608 /// \param Idx Last valid SLotIndex before instruction. 610 /// \returns True if the DBG_VALUE instruction should be deleted. 613 /// Track variable location debug instructions while using the instruction 614 /// referencing implementation. Such debug instructions do not need to be 615 /// updated during regalloc because they identify instructions rather than 616 /// register locations. However, they needs to be removed from the 617 /// MachineFunction during regalloc, then re-inserted later, to avoid 618 /// disrupting the allocator. 620 /// \param MI Any DBG_VALUE / DBG_INSTR_REF / DBG_PHI instruction 621 /// \param Idx Last valid SlotIndex before instruction 623 /// \returns Iterator to continue processing from after unlinking. 626 /// Add DBG_LABEL instruction to UserLabel. 628 /// \param MI DBG_LABEL instruction 629 /// \param Idx Last valid SlotIndex before instruction. 631 /// \returns True if the DBG_LABEL instruction should be deleted. 634 /// Collect and erase all DBG_VALUE instructions, adding a UserValue def 635 /// for each instruction. 637 /// \param mf MachineFunction to be scanned. 638 /// \param InstrRef Whether to operate in instruction referencing mode. If 639 /// true, most of LiveDebugVariables doesn't run. 641 /// \returns True if any debug values were found. 644 /// Compute the live intervals of all user values after collecting all 645 /// their def points. 646void computeIntervals();
653 /// Release all memory. 658 StashedDebugInstrs.
clear();
661 virtRegToEqClass.
clear();
663// Make sure we call emitDebugValues if the machine function was modified. 664assert((!ModifiedMF || EmitDone) &&
665"Dbg values are not emitted in LDV");
670 /// Map virtual register to an equivalence class. 673 /// Replace any PHI referring to OldReg with its corresponding NewReg, if 677 /// Replace all references to OldReg with NewRegs. 680 /// Recreate DBG_VALUE instruction from data structures. 693auto *Scope = cast<DIScope>(
DL.getScope());
694// Omit the directory, because it's likely to be long and uninteresting. 695 CommentOS << Scope->getFilename();
696 CommentOS <<
':' <<
DL.getLine();
698 CommentOS <<
':' <<
DL.getCol();
714if (
constauto *V = dyn_cast<const DILocalVariable>(
Node)) {
717 }
elseif (
constauto *L = dyn_cast<const DILabel>(
Node)) {
723OS << Res <<
"," << Line;
724auto *InlinedAt =
DL ?
DL->getInlinedAt() :
nullptr;
726if (
DebugLoc InlinedAtDL = InlinedAt) {
740OS <<
" [" <<
I.start() <<
';' <<
I.stop() <<
"):";
741if (
I.value().isUndef())
744I.value().printLocNos(
OS);
745if (
I.value().getWasIndirect())
747elseif (
I.value().getWasList())
751for (
unsigned i = 0, e = locations.size(); i != e; ++i) {
752OS <<
" Loc" << i <<
'=';
753 locations[i].print(
OS,
TRI);
768OS <<
"********** DEBUG VARIABLES **********\n";
769for (
auto &userValue : userValues)
770 userValue->print(
OS,
TRI);
771OS <<
"********** DEBUG LABELS **********\n";
772for (
auto &userLabel : userLabels)
773 userLabel->print(
OS,
TRI);
778if (MO.isReg() && MO.getReg().isVirtual())
782UserValue *LiveDebugVariables::LDVImpl::getUserValue(
784 std::optional<DIExpression::FragmentInfo> Fragment,
constDebugLoc &
DL) {
785// FIXME: Handle partially overlapping fragments. See 786// https://reviews.llvm.org/D70121#1849741. 788 UserValue *&UV = userVarMap[
ID];
790 userValues.push_back(
791 std::make_unique<UserValue>(Var, Fragment,
DL,
allocator));
792 UV = userValues.back().get();
799 UserValue *&Leader = virtRegToEqClass[VirtReg];
800 Leader = UserValue::merge(Leader, EC);
803UserValue *LiveDebugVariables::LDVImpl::lookupVirtReg(
Register VirtReg) {
804if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
805return UV->getLeader();
809bool LiveDebugVariables::LDVImpl::handleDebugValue(
MachineInstr &
MI,
811// DBG_VALUE loc, offset, variable, expr 812// DBG_VALUE_LIST variable, expr, locs... 813if (!
MI.isDebugValue()) {
817if (!
MI.getDebugVariableOp().isMetadata()) {
818LLVM_DEBUG(
dbgs() <<
"Can't handle DBG_VALUE* with invalid variable: " 822if (
MI.isNonListDebugValue() &&
823 (
MI.getNumOperands() != 4 ||
824 !(
MI.getDebugOffset().isImm() ||
MI.getDebugOffset().isReg()))) {
829// Detect invalid DBG_VALUE instructions, with a debug-use of a virtual 830// register that hasn't been defined yet. If we do not remove those here, then 831// the re-insertion of the DBG_VALUE instruction after register allocation 835if (
Op.isReg() &&
Op.getReg().isVirtual()) {
837if (!LIS->hasInterval(Reg)) {
838// The DBG_VALUE is described by a virtual register that does not have a 839// live interval. Discard the DBG_VALUE. 844// The DBG_VALUE is only valid if either Reg is live out from Idx, or 845// Reg is defined dead at Idx (where Idx is the slot index for the 846// instruction preceding the DBG_VALUE). 850// We have found a DBG_VALUE with the value in a virtual register that 851// is not live. Discard the DBG_VALUE. 860// Get or create the UserValue for (variable,offset) here. 861bool IsIndirect =
MI.isDebugOffsetImm();
863assert(
MI.getDebugOffset().getImm() == 0 &&
864"DBG_VALUE with nonzero offset");
865bool IsList =
MI.isDebugValueList();
872MI.debug_operands().end()),
873 IsIndirect, IsList, *Expr);
877// We should still pass a list the same size as MI.debug_operands() even if 878// all MOs are undef, so that DbgVariableValue can correctly adjust the 879// expression while removing the duplicated undefs. 881 UV->addDef(
Idx, UndefMOs,
false, IsList, *Expr);
888assert(
MI.isDebugValueLike() ||
MI.isDebugPHI());
890// In instruction referencing mode, there should be no DBG_VALUE instructions 891// that refer to virtual registers. They might still refer to constants. 892if (
MI.isDebugValueLike())
895 return MO.isReg() && MO.getReg().isVirtual();
897"MIs should not refer to Virtual Registers in InstrRef mode.");
899// Unlink the instruction, store it in the debug instructions collection. 900auto NextInst = std::next(
MI.getIterator());
901auto *
MBB =
MI.getParent();
902MI.removeFromParent();
903 StashedDebugInstrs.push_back({&
MI,
Idx,
MBB});
907bool LiveDebugVariables::LDVImpl::handleDebugLabel(
MachineInstr &
MI,
910if (
MI.getNumOperands() != 1 || !
MI.getOperand(0).isMetadata()) {
915// Get or create the UserLabel for label here. 919for (
autoconst &L : userLabels) {
920if (
L->matches(Label,
DL->getInlinedAt(),
Idx)) {
926 userLabels.push_back(std::make_unique<UserLabel>(Label,
DL,
Idx));
931bool LiveDebugVariables::LDVImpl::collectDebugValues(
MachineFunction &mf,
937// Use the first debug instruction in the sequence to get a SlotIndex 938// for following consecutive debug instructions. 939if (!
MBBI->isDebugOrPseudoInstr()) {
943// Debug instructions has no slot index. Use the previous 944// non-debug instruction's SlotIndex as its SlotIndex. 947 ? LIS->getMBBStartIdx(&
MBB)
948 : LIS->getInstructionIndex(*std::prev(
MBBI)).getRegSlot();
949// Handle consecutive debug instructions with the same slot index. 951// In instruction referencing mode, pass each instr to handleDebugInstr 952// to be unlinked. Ignore DBG_VALUE_LISTs -- they refer to vregs, and 953// need to go through the normal live interval splitting process. 954if (InstrRef && (
MBBI->isNonListDebugValue() ||
MBBI->isDebugPHI() ||
955MBBI->isDebugRef())) {
958// In normal debug mode, use the dedicated DBG_VALUE / DBG_LABEL handler 959// to track things through register allocation, and erase the instr. 960 }
elseif ((
MBBI->isDebugValue() && handleDebugValue(*
MBBI,
Idx)) ||
961 (
MBBI->isDebugLabel() && handleDebugLabel(*
MBBI,
Idx))) {
966 }
while (
MBBI != MBBE &&
MBBI->isDebugOrPseudoInstr());
972void UserValue::extendDef(
974SmallDenseMap<
unsigned, std::pair<LiveRange *, const VNInfo *>>
983// Limit to the intersection of the VNIs' live ranges. 984for (
auto &LII : LiveIntervalInfo) {
986assert(LR && LII.second.second &&
"Missing range info for Idx.");
988assert(Segment && Segment->
valno == LII.second.second &&
989"Invalid VNInfo for Idx given?");
990if (Segment->
end < Stop) {
992 Kills = {Stop, {LII.first}};
993 }
elseif (Segment->
end == Stop && Kills) {
994// If multiple locations end at the same place, track all of them in 996 Kills->second.push_back(LII.first);
1000// There could already be a short def at Start. 1001if (
I.valid() &&
I.start() <= Start) {
1002// Stop when meeting a different location or an already extended interval. 1003 Start = Start.getNextSlot();
1004if (
I.value() !=
DbgValue ||
I.stop() != Start) {
1005// Clear `Kills`, as we have a new def available. 1006 Kills = std::nullopt;
1009// This is a one-slot placeholder. Just skip it. 1013// Limited by the next def. 1014if (
I.valid() &&
I.start() < Stop) {
1016// Clear `Kills`, as we have a new def available. 1017 Kills = std::nullopt;
1021 DbgVariableValue ExtDbgValue(
DbgValue);
1022I.insert(Start, Stop, std::move(ExtDbgValue));
1026void UserValue::addDefsFromCopies(
1032// Don't track copies from physregs, there are too many uses. 1034 [](
auto LocI) {
return !LocI.second->reg().isVirtual(); }))
1037// Collect all the (vreg, valno) pairs that are copies of LI. 1041for (
auto &LocInterval : LocIntervals) {
1042unsigned LocNo = LocInterval.first;
1046// Copies of the full value. 1051// Don't follow copies to physregs. These are usually setting up call 1052// arguments, and the argument registers are always call clobbered. We are 1053// better off in the source register which could be a callee-saved 1054// register, or it could be spilled. 1058// Is the value extended to reach this copy? If not, another def may be 1059// blocking it, or we are looking at a wrong value of LI. 1069assert(DstVNI && DstVNI->
def ==
Idx.getRegSlot() &&
"Bad copy value");
1070 CopyValues[LocNo].push_back(std::make_pair(DstLI, DstVNI));
1074if (CopyValues.
empty())
1078for (
auto &LocInterval : LocIntervals)
1079LLVM_DEBUG(
dbgs() <<
"Got " << CopyValues[LocInterval.first].size()
1080 <<
" copies of " << *LocInterval.second <<
'\n');
1083// Try to add defs of the copied values for the kill point. Check that there 1084// isn't already a def at Idx. 1086if (
I.valid() &&
I.start() <= KilledAt)
1088 DbgVariableValue NewValue(
DbgValue);
1089for (
auto &LocInterval : LocIntervals) {
1090unsigned LocNo = LocInterval.first;
1091bool FoundCopy =
false;
1092for (
auto &LIAndVNI : CopyValues[LocNo]) {
1094constVNInfo *DstVNI = LIAndVNI.second;
1097LLVM_DEBUG(
dbgs() <<
"Kill at " << KilledAt <<
" covered by valno #" 1098 << DstVNI->
id <<
" in " << *DstLI <<
'\n');
1101unsigned NewLocNo = getLocationNo(CopyMI->
getOperand(0));
1102 NewValue = NewValue.changeLocNo(LocNo, NewLocNo);
1106// If there are any killed locations we can't find a copy for, we can't 1107// extend the variable value. 1112 NewDefs.push_back(std::make_pair(KilledAt, NewValue));
1120// Collect all defs to be extended (Skipping undefs). 1122if (!
I.value().isUndef())
1123 Defs.
push_back(std::make_pair(
I.start(),
I.value()));
1125// Extend all defs, and possibly add new ones along the way. 1126for (
unsigned i = 0; i != Defs.
size(); ++i) {
1128 DbgVariableValue
DbgValue = Defs[i].second;
1131bool ShouldExtendDef =
false;
1132for (
unsigned LocNo :
DbgValue.loc_nos()) {
1135 ShouldExtendDef |= !LocMO.
isReg();
1138 ShouldExtendDef =
true;
1140constVNInfo *VNI =
nullptr;
1146 LIs[LocNo] = {LI, VNI};
1148if (ShouldExtendDef) {
1149 std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> Kills;
1154bool AnySubreg =
false;
1155for (
unsigned LocNo : Kills->second) {
1162 KilledLocIntervals.
push_back({LocNo, LI});
1165// FIXME: Handle sub-registers in addDefsFromCopies. The problem is that 1166// if the original location for example is %vreg0:sub_hi, and we find a 1167// full register copy in addDefsFromCopies (at the moment it only 1168// handles full register copies), then we must add the sub1 sub-register 1169// index to the new location. However, that is only possible if the new 1170// virtual register is of the same regclass (or if there is an 1171// equivalent sub-register in that regclass). For now, simply skip 1172// handling copies if a sub-register is involved. 1174 addDefsFromCopies(
DbgValue, KilledLocIntervals, Kills->first, Defs,
1179// For physregs, we only mark the start slot idx. DwarfDebug will see it 1180// as if the DBG_VALUE is valid up until the end of the basic block, or 1181// the next def of the physical register. So we do not need to extend the 1182// range. It might actually happen that the DBG_VALUE is the last use of 1183// the physical register (e.g. if this is an unused input argument to a 1187// The computed intervals may extend beyond the range of the debug 1188// location's lexical scope. In this case, splitting of an interval 1189// can result in an interval outside of the scope being created, 1190// causing extra unnecessary DBG_VALUEs to be emitted. To prevent 1191// this, trim the intervals to the lexical scope in the case of inlined 1192// variables, since heavy inlining may cause production of dramatically big 1193// number of DBG_VALUEs to be generated. 1194if (!dl.getInlinedAt())
1204// Iterate over the lexical scope ranges. Each time round the loop 1205// we check the intervals for overlap with the end of the previous 1206// range and the start of the next. The first range is handled as 1207// a special case where there is no PrevEnd. 1212// Variable locations at the first instruction of a block should be 1213// based on the block's SlotIndex, not the first instruction's index. 1214if (
Range.first ==
Range.first->getParent()->begin())
1217// At the start of each iteration I has been advanced so that 1218// I.stop() >= PrevEnd. Check for overlap. 1219if (PrevEnd &&
I.start() < PrevEnd) {
1223// Stop overlaps previous end - trim the end of the interval to 1225I.setStopUnchecked(PrevEnd);
1228// If the interval also overlaps the start of the "next" (i.e. 1229// current) range create a new interval for the remainder (which 1230// may be further trimmed). 1235// Advance I so that I.stop() >= RStart, and check for overlap. 1240if (
I.start() < RStart) {
1241// Interval start overlaps range - trim to the scope range. 1242I.setStartUnchecked(RStart);
1243// Remember that this interval was trimmed. 1244 trimmedDefs.insert(RStart);
1247// The end of a lexical scope range is the last instruction in the 1248// range. To convert to an interval we need the index of the 1249// instruction after it. 1252// Advance I to first interval outside current range. 1260// Check for overlap with end of final range. 1261if (PrevEnd &&
I.start() < PrevEnd)
1262I.setStopUnchecked(PrevEnd);
1265void LiveDebugVariables::LDVImpl::computeIntervals() {
1269for (
constauto &UV : userValues) {
1270 UV->computeIntervals(MF->getRegInfo(), *
TRI, *LIS, LS);
1271 UV->mapVirtRegs(
this);
1281 << mf.
getName() <<
" **********\n");
1283bool Changed = collectDebugValues(mf, InstrRef);
1287// Collect the set of VReg / SlotIndexs where PHIs occur; index the sensitive 1288// VRegs too, for when we're notified of a range split. 1290for (
constauto &PHIIt : MF->DebugPHIPositions) {
1294unsignedSubReg = Position.SubReg;
1296 PHIValPos VP = {SI, Reg,
SubReg};
1297 PHIValToPos.insert(std::make_pair(PHIIt.first, VP));
1298 RegToPHIIdx[Reg].push_back(PHIIt.first);
1301 ModifiedMF = Changed;
1308if (
MI.isDebugInstr())
1315auto *LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
1317 Impl = std::make_unique<LiveDebugVariables>();
1318 Impl->analyze(mf, LIS);
1331 LDV.analyze(MF, LIS);
1352// Some architectures split the register allocation into multiple phases based 1353// on register classes. This requires preserving analyses between the phases 1355return !PAC.preservedWhenStateless();
1368// Have we been asked to track variable locations using instruction 1371 PImpl->runOnMachineFunction(MF, InstrRef);
1374//===----------------------------------------------------------------------===// 1375// Live Range Splitting 1376//===----------------------------------------------------------------------===// 1382dbgs() <<
"Splitting Loc" << OldLocNo <<
'\t';
1385bool DidChange =
false;
1393// Don't allocate the new LocNo until it is needed. 1396// Iterate over the overlaps between locInts and LI. 1398if (!LocMapI.
valid())
1402while (LocMapI.
valid() && LII != LIE) {
1403// At this point, we know that LocMapI.stop() > LII->start. 1408// Now LII->end > LocMapI.start(). Do we have an overlap? 1409if (LocMapI.
value().containsLocNo(OldLocNo) &&
1410 LII->start < LocMapI.
stop()) {
1411// Overlapping correct location. Allocate NewLocNo now. 1414 MO.
setSubReg(locations[OldLocNo].getSubReg());
1415 NewLocNo = getLocationNo(MO);
1421 DbgVariableValue OldDbgValue = LocMapI.
value();
1423// Trim LocMapI down to the LII overlap. 1424if (LStart < LII->start)
1426if (LStop > LII->end)
1429// Change the value in the overlap. This may trigger coalescing. 1430 LocMapI.
setValue(OldDbgValue.changeLocNo(OldLocNo, NewLocNo));
1432// Re-insert any removed OldDbgValue ranges. 1433if (LStart < LocMapI.
start()) {
1434 LocMapI.
insert(LStart, LocMapI.
start(), OldDbgValue);
1438if (LStop > LocMapI.
stop()) {
1440 LocMapI.
insert(LII->end, LStop, OldDbgValue);
1445// Advance to the next overlap. 1446if (LII->end < LocMapI.
stop()) {
1452if (!LocMapI.
valid())
1459// Finally, remove OldLocNo unless it is still used by some interval in the 1460// locInts map. One case when OldLocNo still is in use is when the register 1461// has been spilled. In such situations the spilled register is kept as a 1462// location until rewriteLocations is called (VirtRegMap is mapping the old 1463// register to the spill slot). So for a while we can have locations that map 1464// to virtual registers that have been removed from both the MachineFunction 1465// and from LiveIntervals. 1467// We may also just be using the location for a value with a different 1469 removeLocationIfUnused(OldLocNo);
1472dbgs() <<
"Split result: \t";
1481bool DidChange =
false;
1482// Split locations referring to OldReg. Iterate backwards so splitLocation can 1483// safely erase unused locations. 1484for (
unsigned i = locations.size(); i ; --i) {
1485unsigned LocNo = i-1;
1489 DidChange |= splitLocation(LocNo, NewRegs, LIS);
1496auto RegIt = RegToPHIIdx.find(OldReg);
1497if (RegIt == RegToPHIIdx.end())
1500 std::vector<std::pair<Register, unsigned>> NewRegIdxes;
1501// Iterate over all the debug instruction numbers affected by this split. 1502for (
unsigned InstrID : RegIt->second) {
1503auto PHIIt = PHIValToPos.find(InstrID);
1504assert(PHIIt != PHIValToPos.end());
1506assert(OldReg == PHIIt->second.Reg);
1508// Find the new register that covers this position. 1509for (
auto NewReg : NewRegs) {
1511auto LII = LI.
find(Slot);
1512if (LII != LI.
end() && LII->start <= Slot) {
1513// This new register covers this PHI position, record this for indexing. 1514 NewRegIdxes.push_back(std::make_pair(NewReg, InstrID));
1515// Record that this value lives in a different VReg now. 1516 PHIIt->second.Reg = NewReg;
1521// If we do not find a new register covering this PHI, then register 1522// allocation has dropped its location, for example because it's not live. 1523// The old VReg will not be mapped to a physreg, and the instruction 1524// number will have been optimized out. 1527// Re-create register index using the new register numbers. 1528 RegToPHIIdx.erase(RegIt);
1529for (
auto &RegAndInstr : NewRegIdxes)
1530 RegToPHIIdx[RegAndInstr.first].push_back(RegAndInstr.second);
1535// Consider whether this split range affects any PHI locations. 1536 splitPHIRegister(OldReg, NewRegs);
1538// Check whether any intervals mapped by a DBG_VALUE were split and need 1540bool DidChange =
false;
1541for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
1542 DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
1547// Map all of the new virtual registers. 1548 UserValue *UV = lookupVirtReg(OldReg);
1550 mapVirtReg(NewReg, UV);
1556 PImpl->splitRegister(OldReg, NewRegs);
1563// Build a set of new locations with new numbers so we can coalesce our 1564// IntervalMap if two vreg intervals collapse to the same physical location. 1565// Use MapVector instead of SetVector because MapVector::insert returns the 1566// position of the previously or newly inserted element. The boolean value 1567// tracks if the location was produced by a spill. 1568// FIXME: This will be problematic if we ever support direct and indirect 1569// frame index locations, i.e. expressing both variables in memory and 1570// 'int x, *px = &x'. The "spilled" bit must become part of the location. 1573for (
unsignedI = 0, E = locations.size();
I != E; ++
I) {
1575unsigned SpillOffset = 0;
1577// Only virtual registers are rewritten. 1581// This can create a %noreg operand in rare cases when the sub-register 1582// index is no longer available. That means the user value is in a 1583// non-existent sub-register, and %noreg is exactly what we want. 1586// Retrieve the stack slot offset. 1593// FIXME: Invalidate the location if the offset couldn't be calculated. 1604// Insert this location if it doesn't already exist and record a mapping 1605// from the old number to the new number. 1606auto InsertResult = NewLocations.
insert({Loc, {Spilled, SpillOffset}});
1607unsigned NewLocNo = std::distance(NewLocations.
begin(), InsertResult.first);
1608 LocNoMap[
I] = NewLocNo;
1611// Rewrite the locations and record the stack slot offsets for spills. 1613 SpillOffsets.
clear();
1614for (
auto &Pair : NewLocations) {
1616unsigned SpillOffset;
1617 std::tie(Spilled, SpillOffset) = Pair.second;
1618 locations.push_back(Pair.first);
1620unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair);
1621 SpillOffsets[NewLocNo] = SpillOffset;
1625// Update the interval map, but only coalesce left, since intervals to the 1626// right use the old location numbers. This should merge two contiguous 1627// DBG_VALUE intervals with different vregs that were allocated to the same 1628// physical register. 1630I.setValueUnchecked(
I.value().remapLocNos(LocNoMap));
1631I.setStart(
I.start());
1635/// Find an iterator for inserting a DBG_VALUE instruction. 1642// Try to find an insert location by going backwards from Idx. 1645// We've reached the beginning of MBB. 1647// Retrieve the last PHI/Label/Debug location found when calling 1648// SkipPHIsLabelsAndDebug last time. Start searching from there. 1650// Note the iterator kept in BBSkipInstsMap is one step back based 1651// on the iterator returned by SkipPHIsLabelsAndDebug last time. 1652// One exception is when SkipPHIsLabelsAndDebug returns MBB->begin(), 1653// BBSkipInstsMap won't save it. This is to consider the case that 1654// new instructions may be inserted at the beginning of MBB after 1655// last call of SkipPHIsLabelsAndDebug. If we save MBB->begin() in 1656// BBSkipInstsMap, after new non-phi/non-label/non-debug instructions 1657// are inserted at the beginning of the MBB, the iterator in 1658// BBSkipInstsMap won't point to the beginning of the MBB anymore. 1659// Therefore The next search in SkipPHIsLabelsAndDebug will skip those 1660// newly added instructions and that is unwanted. 1662auto MapIt = BBSkipInstsMap.
find(
MBB);
1663if (MapIt == BBSkipInstsMap.
end())
1666 BeginIt = std::next(MapIt->second);
1669 BBSkipInstsMap[
MBB] = std::prev(
I);
1675// Don't insert anything after the first terminator, though. 1681/// Find an iterator for inserting the next DBG_VALUE instruction 1682/// (or end if no more insert locations found). 1694// Find the next instruction in the MBB that define the register Reg. 1695while (
I !=
MBB->
end() && !
I->isTerminator()) {
1700returnI->definesRegister(Reg, &
TRI);
1702// The insert location is directly after the instruction/bundle. 1717// Only search within the current MBB. 1718 StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx;
1721// Undef values don't exist in locations so create new "noreg" register MOs 1722// for them. See getLocationNo(). 1727/* Reg */ 0,
/* isDef */false,
/* isImp */false,
1728/* isKill */false,
/* isDead */false,
1729/* isUndef */false,
/* isEarlyClobber */false,
1730/* SubReg */ 0,
/* isDebug */true));
1732for (
unsigned LocNo :
DbgValue.loc_nos())
1736 ++NumInsertedDebugValues;
1738assert(cast<DILocalVariable>(Variable)
1740"Expected inlined-at fields to agree");
1742// If the location was spilled, the new DBG_VALUE will be indirect. If the 1743// original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate 1744// that the original virtual register was a pointer. Also, add the stack slot 1745// offset for the spilled register to the expression. 1747bool IsIndirect =
DbgValue.getWasIndirect();
1749for (
unsignedI = 0, E = LocSpills.
size();
I != E; ++
I) {
1765assert((!LocSpills[
I] || MOs[
I].isFI()) &&
1766"a spilled location must be a frame index");
1769unsigned DbgValueOpcode =
1770 IsList ? TargetOpcode::DBG_VALUE_LIST : TargetOpcode::DBG_VALUE;
1775// Continue and insert DBG_VALUES after every redefinition of a register 1776// associated with the debug value within the range 1786 ++NumInsertedDebugLabels;
1805for (
unsigned LocNo :
DbgValue.loc_nos()) {
1808bool Spilled = SpillIt != SpillOffsets.
end();
1810 LocSpillOffsets.
push_back(Spilled ? SpillIt->second : 0);
1813// If the interval start was trimmed to the lexical scope insert the 1814// DBG_VALUE at the previous index (otherwise it appears after the 1815// first instruction in the range). 1816if (trimmedDefs.count(Start))
1817 Start = Start.getPrevIndex();
1819LLVM_DEBUG(
auto &dbg =
dbgs(); dbg <<
"\t[" << Start <<
';' << Stop <<
"):";
1825 insertDebugValue(&*
MBB, Start, Stop,
DbgValue, SpilledLocs, LocSpillOffsets,
1826 LIS,
TII,
TRI, BBSkipInstsMap);
1827// This interval may span multiple basic blocks. 1828// Insert a DBG_VALUE into each one. 1829while (Stop > MBBEnd) {
1830// Move to the next block. 1836 insertDebugValue(&*
MBB, Start, Stop,
DbgValue, SpilledLocs,
1837 LocSpillOffsets, LIS,
TII,
TRI, BBSkipInstsMap);
1853 insertDebugLabel(&*
MBB, loc, LIS,
TII, BBSkipInstsMap);
1859LLVM_DEBUG(
dbgs() <<
"********** EMITTING LIVE DEBUG VARIABLES **********\n");
1866for (
auto &userValue : userValues) {
1868 userValue->rewriteLocations(*VRM, *MF, *
TII, *
TRI, SpillOffsets);
1869 userValue->emitDebugValues(VRM, *LIS, *
TII, *
TRI, SpillOffsets,
1872LLVM_DEBUG(
dbgs() <<
"********** EMITTING LIVE DEBUG LABELS **********\n");
1873for (
auto &userLabel : userLabels) {
1875 userLabel->emitDebugLabel(*LIS, *
TII, BBSkipInstsMap);
1878LLVM_DEBUG(
dbgs() <<
"********** EMITTING DEBUG PHIS **********\n");
1881for (
auto &It : PHIValToPos) {
1882// For each ex-PHI, identify its physreg location or stack slot, and emit 1884unsigned InstNum = It.first;
1885auto Slot = It.second.SI;
1887unsignedSubReg = It.second.SubReg;
1891unsigned PhysReg = VRM->
getPhys(Reg);
1893 PhysReg =
TRI->getSubReg(PhysReg,
SubReg);
1896TII->get(TargetOpcode::DBG_PHI));
1897 Builder.addReg(PhysReg);
1898 Builder.addImm(InstNum);
1902unsigned SpillSize, SpillOffset;
1904unsigned regSizeInBits =
TRI->getRegSizeInBits(*TRC);
1906 regSizeInBits =
TRI->getSubRegIdxSize(
SubReg);
1908// Test whether this location is legal with the given subreg. If the 1909// subregister has a nonzero offset, drop this location, it's too complex 1910// to describe. (TODO: future work). 1912TII->getStackSlotRange(TRC,
SubReg, SpillSize, SpillOffset, *MF);
1914if (
Success && SpillOffset == 0) {
1916TII->get(TargetOpcode::DBG_PHI));
1918 Builder.addImm(InstNum);
1919// Record how large the original value is. The stack slot might be 1920// merged and altered during optimisation, but we will want to know how 1921// large the value is, at this DBG_PHI. 1922 Builder.addImm(regSizeInBits);
1927 <<
" has nonzero offset\n";
1930// If there was no mapping for a value ID, it's optimized out. Create no 1931// DBG_PHI, and any variables using this value will become optimized out. 1935LLVM_DEBUG(
dbgs() <<
"********** EMITTING INSTR REFERENCES **********\n");
1937// Re-insert any debug instrs back in the position they were. We must 1938// re-insert in the same order to ensure that debug instructions don't swap, 1939// which could re-order assignments. Do so in a batch -- once we find the 1940// insert position, insert all instructions at the same SlotIdx. They are 1941// guaranteed to appear in-sequence in StashedDebugInstrs because we insert 1943for (
auto *StashIt = StashedDebugInstrs.begin();
1944 StashIt != StashedDebugInstrs.end(); ++StashIt) {
1949auto EmitInstsHere = [
this, &StashIt,
MBB,
Idx,
1951// Insert this debug instruction. 1954// Look at subsequent stashed debug instructions: if they're at the same 1955// index, insert those too. 1956auto NextItem = std::next(StashIt);
1957while (NextItem != StashedDebugInstrs.end() && NextItem->Idx ==
Idx) {
1958assert(NextItem->MBB ==
MBB &&
"Instrs with same slot index should be" 1959"in the same block");
1962 NextItem = std::next(StashIt);
1966// Start block index: find the first non-debug instr in the block, and 1968if (
Idx == Slots->getMBBStartIdx(
MBB)) {
1971 EmitInstsHere(InsertPos);
1976// Insert at the end of any debug instructions. 1977auto PostDebug = std::next(Pos->getIterator());
1979 EmitInstsHere(PostDebug);
1981// Insert position disappeared; walk forwards through slots until we 1985 Pos = Slots->getInstructionFromIndex(
Idx);
1987 EmitInstsHere(Pos->getIterator());
1992// We have reached the end of the block and didn't find anywhere to 1993// insert! It's not safe to discard any debug instructions; place them 1994// in front of the first terminator, or in front of end(). 1997 EmitInstsHere(TermIt);
2003 BBSkipInstsMap.
clear();
2008 PImpl->emitDebugValues(VRM);
2011#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) unsigned const MachineRegisterInfo * MRI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
static ManagedStatic< cl::opt< bool, true >, CreateDebug > Debug
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
std::optional< std::vector< StOtherPiece > > Other
const HexagonInstrInfo * TII
This file implements a coalescing interval map for small objects.
static void printExtendedName(raw_ostream &OS, const DINode *Node, const DILocation *DL)
static MachineBasicBlock::iterator findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx, LiveIntervals &LIS, BlockSkipInstsMap &BBSkipInstsMap)
Find an iterator for inserting a DBG_VALUE instruction.
static MachineBasicBlock::iterator findNextInsertLocation(MachineBasicBlock *MBB, MachineBasicBlock::iterator I, SlotIndex StopIdx, ArrayRef< MachineOperand > LocMOs, LiveIntervals &LIS, const TargetRegisterInfo &TRI)
Find an iterator for inserting the next DBG_VALUE instruction (or end if no more insert locations fou...
static cl::opt< bool > EnableLDV("live-debug-variables", cl::init(true), cl::desc("Enable the live debug variables pass"), cl::Hidden)
static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS, const LLVMContext &Ctx)
static void removeDebugInstrs(MachineFunction &mf)
static LoopDeletionResult merge(LoopDeletionResult A, LoopDeletionResult B)
static DebugLoc getDebugLoc(MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
Return the first found DebugLoc that has a DILocation, given a range of instructions.
static bool isUndef(const MachineInstr &MI)
unsigned const TargetRegisterInfo * TRI
This file implements a map that provides insertion order iteration.
static unsigned getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
static bool isReg(const MCInst &MI, unsigned OpNo)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Class recording the (high level) value of a variable.
API to communicate dependencies between analyses during invalidation.
A container for analyses that lazily runs them and caches their results.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
static void appendOffset(SmallVectorImpl< uint64_t > &Ops, int64_t Offset)
Append Ops with operations to apply the Offset.
static DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
static std::optional< FragmentInfo > getFragmentInfo(expr_op_iterator Start, expr_op_iterator End)
Retrieve the details of this fragment expression.
static DIExpression * replaceArg(const DIExpression *Expr, uint64_t OldArg, uint64_t NewArg)
Create a copy of Expr with each instance of DW_OP_LLVM_arg, \p OldArg replaced with DW_OP_LLVM_arg,...
static std::optional< DIExpression * > createFragmentExpression(const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits)
Create a DIExpression to describe one part of an aggregate variable that is fragmented across multipl...
static DIExpression * prepend(const DIExpression *Expr, uint8_t Flags, int64_t Offset=0)
Prepend DIExpr with a deref and offset operation and optionally turn it into a stack value or/and an ...
Tagged DWARF-like metadata node.
This class represents an Operation in the Expression.
Identifies a unique instance of a variable.
iterator find(const_arg_type_t< KeyT > Val)
Class representing an expression and its matching format.
DISubprogram * getSubprogram() const
Get the attached subprogram.
void setMap(const IntervalMap &m)
setMap - Change the map iterated over.
void advanceTo(KeyT x)
advanceTo - Move to the first interval with stop >= x, or end().
const KeyT & stop() const
stop - Return the end of the current interval.
bool valid() const
valid - Return true if the current position is valid, false for end().
const KeyT & start() const
start - Return the beginning of the current interval.
const ValT & value() const
value - Return the mapped value at the current interval.
void find(KeyT x)
find - Move to the first interval with stop >= x, or end().
void insert(KeyT a, KeyT b, ValT y)
insert - Insert mapping [a;b] -> y before the current position.
void setValue(ValT x)
setValue - Change the mapped value of the current interval.
void setStartUnchecked(KeyT a)
setStartUnchecked - Move the start of the current interval without checking for coalescing or overlap...
void setStopUnchecked(KeyT b)
setStopUnchecked - Move the end of the current interval without checking for coalescing or overlaps.
const_iterator begin() const
typename Sizer::Allocator Allocator
const_iterator find(KeyT x) const
find - Return an iterator pointing to the first interval ending at or after x, or end().
This is an important class for using LLVM in a threaded context.
LexicalScope - This class is used to track scope information.
LexicalScopes - This class provides interface to collect and use lexical scoping information from mac...
Result run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LiveDebugVariablesWrapperLegacy()
bool runOnMachineFunction(MachineFunction &) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
LDVImpl(LiveIntervals *LIS)
void print(raw_ostream &)
void splitRegister(Register OldReg, ArrayRef< Register > NewRegs)
Replace all references to OldReg with NewRegs.
bool runOnMachineFunction(MachineFunction &mf, bool InstrRef)
void mapVirtReg(Register VirtReg, UserValue *EC)
Map virtual register to an equivalence class.
void clear()
Release all memory.
void emitDebugValues(VirtRegMap *VRM)
Recreate DBG_VALUE instruction from data structures.
void splitPHIRegister(Register OldReg, ArrayRef< Register > NewRegs)
Replace any PHI referring to OldReg with its corresponding NewReg, if present.
void dump() const
dump - Print data structures to dbgs().
void splitRegister(Register OldReg, ArrayRef< Register > NewRegs, LiveIntervals &LIS)
splitRegister - Move any user variables in OldReg to the live ranges in NewRegs where they are live.
LiveDebugVariables()
Implementation of the LiveDebugVariables pass.
void print(raw_ostream &OS) const
void analyze(MachineFunction &MF, LiveIntervals *LIS)
void emitDebugValues(VirtRegMap *VRM)
emitDebugValues - Emit new DBG_VALUE instructions reflecting the changes that happened during registe...
bool invalidate(MachineFunction &MF, const PreservedAnalyses &PA, MachineFunctionAnalysisManager::Invalidator &Inv)
LiveInterval - This class represents the liveness of a register, or stack slot.
bool hasInterval(Register Reg) const
SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const
Return the first index in the given basic block.
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
SlotIndexes * getSlotIndexes() const
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Return the last index in the given basic block.
LiveInterval & getInterval(Register Reg)
bool isNotInMIMap(const MachineInstr &Instr) const
Returns true if the specified machine instr has been removed or was never entered in the map.
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
Result of a LiveRange query.
VNInfo * valueOutOrDead() const
Returns the value alive at the end of the instruction, if any.
This class represents the liveness of a register, stack slot, etc.
const Segment * getSegmentContaining(SlotIndex Idx) const
Return the segment that contains the specified index, or null if there is none.
iterator advanceTo(iterator I, SlotIndex Pos)
advanceTo - Advance the specified iterator to point to the Segment containing the specified position,...
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
SlotIndex beginIndex() const
beginIndex - Return the lowest numbered slot covered.
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
iterator find(SlotIndex Pos)
find - Return an iterator pointing to the first segment that ends after Pos, or end().
LLVMContext & getContext() const
An RAII based helper class to modify MachineFunctionProperties when running pass.
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
iterator SkipPHIsLabelsAndDebug(iterator I, Register Reg=Register(), bool SkipPseudoOp=true)
Return the first instruction in MBB after I that is not a PHI, label or debug.
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
instr_iterator instr_end()
instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
Analysis pass which computes a MachineDominatorTree.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Location of a PHI instruction that is also a debug-info variable value, for the duration of register ...
bool useDebugInstrRef() const
Returns true if the function's variable locations are tracked with instruction referencing.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
DenseMap< unsigned, DebugPHIRegallocPos > DebugPHIPositions
Map of debug instruction numbers to the position of their PHI instructions during register allocation...
const MachineInstrBuilder & addMetadata(const MDNode *MD) const
Representation of each machine instruction.
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void setReg(Register Reg)
Change the register this operand corresponds to.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
void substPhysReg(MCRegister Reg, const TargetRegisterInfo &)
substPhysReg - Substitute the current register with the physical register Reg, taking any existing Su...
void setIsDebug(bool Val=true)
Register getReg() const
getReg - Returns the register number.
bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
static MachineOperand CreateFI(int Idx)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
This class implements a map that also provides access to all stored values in a deterministic order.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Wrapper class representing virtual and physical registers.
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
SlotIndex - An opaque wrapper around machine indexes.
SlotIndex getNextIndex() const
Returns the next index.
static bool isEarlierEqualInstr(SlotIndex A, SlotIndex B)
Return true if A refers to the same instruction as B or an earlier one.
SlotIndex getNextSlot() const
Returns the next slot in the index list.
SlotIndex getMBBStartIdx(unsigned Num) const
Returns the first index in the given basic block number.
SlotIndex getIndexBefore(const MachineInstr &MI) const
getIndexBefore - Returns the index of the last indexed instruction before MI, or the start index of i...
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
iterator erase(const_iterator CI)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
constexpr bool empty() const
empty - Check if the string is empty.
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
virtual const TargetInstrInfo * getInstrInfo() const
VNInfo - Value Number Information.
unsigned id
The ID number of this value.
SlotIndex def
The index of the defining instruction.
int getStackSlot(Register virtReg) const
returns the stack slot mapped to the specified virtual register
MachineFunction & getMachineFunction() const
MCRegister getPhys(Register virtReg) const
returns the physical register mapped to the specified virtual register
bool hasPhys(Register virtReg) const
returns true if the specified virtual register is mapped to a physical register
bool isAssignedReg(Register virtReg) const
returns true if the specified virtual register is not mapped to a stack slot or rematerialized.
static constexpr int NO_STACK_SLOT
self_iterator getIterator()
This class implements an extremely fast bulk output stream that can only output to a stream.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Reg
All possible values of the reg field in the ModR/M byte.
initializer< Ty > init(const Ty &Val)
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
This is an optimization pass for GlobalISel generic memory operations.
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
bool operator!=(uint64_t V1, const APInt &V2)
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
IterT skipDebugInstructionsForward(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
void initializeLiveDebugVariablesWrapperLegacyPass(PassRegistry &)
std::pair< const MachineInstr *, const MachineInstr * > InsnRange
InsnRange - This is used to track range of instructions with identical lexical scope.
Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
A special type used by analysis passes to provide an address that identifies that particular analysis...
This represents a simple continuous liveness interval for a value.