42#include <unordered_map>
45#define DEBUG_TYPE "debug-ata"
47STATISTIC(NumDefsScanned,
"Number of dbg locs that get scanned for removal");
48STATISTIC(NumDefsRemoved,
"Number of dbg locs removed");
49STATISTIC(NumWedgesScanned,
"Number of dbg wedges scanned");
50STATISTIC(NumWedgesChanged,
"Number of dbg wedges changed");
54 cl::desc(
"Maximum num basic blocks before debug info dropped"),
75 return Wrapped::getHashValue(
static_cast<unsigned>(Val));
94 friend FunctionVarLocs;
98 std::unordered_map<VarLocInsertPt, SmallVector<VarLocInfo>> VarLocsBeforeInst;
107 return static_cast<VariableID>(Variables.insert(V));
112 return Variables[
static_cast<unsigned>(ID)];
118 auto R = VarLocsBeforeInst.find(Before);
119 if (R == VarLocsBeforeInst.end())
126 VarLocsBeforeInst[Before] = std::move(Wedge);
135 VarLoc.
DL = std::move(
DL);
137 SingleLocVars.emplace_back(VarLoc);
146 VarLoc.
DL = std::move(
DL);
148 VarLocsBeforeInst[Before].emplace_back(VarLoc);
155 unsigned Counter = -1;
156 OS <<
"=== Variables ===\n";
163 OS <<
"[" << Counter <<
"] " << V.getVariable()->getName();
164 if (
auto F = V.getFragment())
165 OS <<
" bits [" <<
F->OffsetInBits <<
", "
166 <<
F->OffsetInBits +
F->SizeInBits <<
")";
167 if (
const auto *IA = V.getInlinedAt())
168 OS <<
" inlined-at " << *IA;
173 OS <<
"DEF Var=[" << (
unsigned)
Loc.VariableID <<
"]"
174 <<
" Expr=" << *
Loc.Expr <<
" Values=(";
175 for (
auto *
Op :
Loc.Values.location_ops()) {
176 errs() <<
Op->getName() <<
" ";
182 OS <<
"=== Single location vars ===\n";
189 OS <<
"=== In-line variable defs ===";
191 OS <<
"\n" << BB.getName() <<
":\n";
203 for (
const auto &VarLoc : Builder.SingleLocVars)
204 VarLocRecords.emplace_back(VarLoc);
206 SingleVarLocEnd = VarLocRecords.size();
212 for (
auto &
P : Builder.VarLocsBeforeInst) {
218 unsigned BlockStart = VarLocRecords.size();
225 auto It = Builder.VarLocsBeforeInst.find(&DVR);
226 if (It == Builder.VarLocsBeforeInst.end())
229 VarLocRecords.emplace_back(VarLoc);
232 VarLocRecords.emplace_back(VarLoc);
233 unsigned BlockEnd = VarLocRecords.size();
235 if (BlockEnd != BlockStart)
236 VarLocsBeforeInst[
I] = {BlockStart, BlockEnd};
240 assert(Variables.empty() &&
"Expect clear before init");
243 Variables.reserve(Builder.Variables.size() + 1);
244 Variables.push_back(
DebugVariable(
nullptr, std::nullopt,
nullptr));
245 Variables.append(Builder.Variables.begin(), Builder.Variables.end());
250 VarLocRecords.clear();
251 VarLocsBeforeInst.clear();
259static std::pair<Value *, DIExpression *>
262 APInt OffsetInBytes(
DL.getTypeSizeInBits(Start->getType()),
false);
264 Start->stripAndAccumulateInBoundsConstantOffsets(
DL, OffsetInBytes);
278static std::optional<int64_t>
283 unsigned ExpectedDerefIdx = 0;
285 if (NumElements > 2 && Elements[0] == dwarf::DW_OP_plus_uconst) {
287 ExpectedDerefIdx = 2;
288 }
else if (NumElements > 3 && Elements[0] == dwarf::DW_OP_constu) {
289 ExpectedDerefIdx = 3;
290 if (Elements[2] == dwarf::DW_OP_plus)
292 else if (Elements[2] == dwarf::DW_OP_minus)
299 if (ExpectedDerefIdx >= NumElements)
304 if (Elements[ExpectedDerefIdx] != dwarf::DW_OP_deref)
308 if (NumElements == ExpectedDerefIdx + 1)
310 unsigned ExpectedFragFirstIdx = ExpectedDerefIdx + 1;
311 unsigned ExpectedFragFinalIdx = ExpectedFragFirstIdx + 2;
312 if (NumElements == ExpectedFragFinalIdx + 1 &&
350 std::priority_queue<unsigned, std::vector<unsigned>, std::greater<unsigned>>
355 explicit RPOWorklist(
unsigned NumBlocks,
bool InsertAll =
false)
356 : InQueue(NumBlocks, InsertAll) {
358 for (
unsigned RPO = 0; RPO < NumBlocks; ++RPO)
362 bool empty()
const {
return Queue.empty(); }
366 bool insert(
unsigned RPO) {
367 if (InQueue.
test(RPO))
375 unsigned RPO = Queue.top();
381 void swap(RPOWorklist &
Other) {
382 Queue.swap(
Other.Queue);
389class BlockLivenessTracker {
390 static constexpr unsigned UnboundedReads =
391 std::numeric_limits<unsigned>::max();
398 void computeCanRevisit(
const RPOToBlockMap &OrderToBB,
unsigned NumBlocks) {
400 for (
unsigned RPO = 0; RPO < NumBlocks; ++RPO) {
402 unsigned SuccRPO = BBToOrder.
lookup(Succ);
403 if (SuccRPO <= RPO && !CanRevisit.
test(SuccRPO)) {
404 CanRevisit.
set(SuccRPO);
409 while (!Worklist.
empty()) {
412 unsigned SuccRPO = BBToOrder.
lookup(Succ);
413 if (!CanRevisit.
test(SuccRPO)) {
414 CanRevisit.
set(SuccRPO);
422 unsigned NumBlocks) {
423 for (
unsigned RPO = 0; RPO < NumBlocks; ++RPO) {
425 if (CanRevisit.
test(BBToOrder.
lookup(Succ))) {
426 RemainingReads[RPO] = UnboundedReads;
429 ++RemainingReads[RPO];
437 : BBToOrder(BBToOrder), CanRevisit(OrderToBB.
size()),
438 RemainingReads(OrderToBB.
size()) {
439 unsigned NumBlocks = OrderToBB.
size();
440 computeCanRevisit(OrderToBB, NumBlocks);
441 computeRemainingReads(OrderToBB, NumBlocks);
444 bool canRevisit(
unsigned RPO)
const {
return CanRevisit.
test(RPO); }
447 return canRevisit(BBToOrder.
lookup(&BB));
452 bool markVisited(
const BasicBlock *BB) {
return Visited.
insert(BB).second; }
454 bool hasRemainingReads(
unsigned RPO)
const {
return RemainingReads[RPO] > 0; }
456 bool hasRemainingReads(
const BasicBlock &BB)
const {
457 return hasRemainingReads(BBToOrder.
lookup(&BB));
463 return RemainingReads[BBToOrder.
lookup(
Pred)] == 1;
468 template <
typename LiveOutMapTy>
469 void retireVisitedPreds(
const BasicBlock &BB, LiveOutMapTy &LiveOut) {
471 if (!isVisited(
Pred))
474 if (RemainingReads[PredRPO] != UnboundedReads &&
475 --RemainingReads[PredRPO] == 0)
481void enqueueSuccessors(
const BasicBlock &BB,
unsigned RPO,
483 RPOWorklist &Pending) {
485 <<
" has new OutLocs, add succs to worklist: [ ");
487 unsigned SuccRPO = BBToOrder.
lookup(Succ);
488 RPOWorklist &
Target = SuccRPO > RPO ? Worklist : Pending;
489 if (
Target.insert(SuccRPO))
513class MemLocFragmentFill {
517 bool CoalesceAdjacentFragments;
524 OffsetInBitsTy, BaseAddress,
527 FragsInMemMap::Allocator IntervalMapAlloc;
540 unsigned OffsetInBits;
553 static bool intervalMapsAreEqual(
const FragsInMemMap &
A,
554 const FragsInMemMap &
B) {
555 auto AIt =
A.begin(), AEnd =
A.end();
556 auto BIt =
B.begin(), BEnd =
B.end();
557 for (; AIt != AEnd; ++AIt, ++BIt) {
560 if (AIt.start() != BIt.start() || AIt.stop() != BIt.stop())
569 static bool varFragMapsAreEqual(
const VarFragMap &
A,
const VarFragMap &
B) {
570 if (
A.size() !=
B.size())
572 for (
const auto &APair :
A) {
573 auto BIt =
B.find(APair.first);
576 if (!intervalMapsAreEqual(APair.second, BIt->second))
583 std::string
toString(
unsigned BaseID) {
585 return Bases[BaseID].getVariableLocationOp(0)->getName().str();
591 std::string
toString(FragsInMemMap::const_iterator It,
bool Newline =
true) {
593 std::stringstream S(
String);
595 S <<
"[" << It.start() <<
", " << It.stop()
598 S <<
"invalid iterator (end)";
605 FragsInMemMap meetFragments(
const FragsInMemMap &
A,
const FragsInMemMap &
B) {
606 FragsInMemMap Result(IntervalMapAlloc);
607 for (
auto AIt =
A.begin(), AEnd =
A.end(); AIt != AEnd; ++AIt) {
614 if (!
B.overlaps(AIt.start(), AIt.stop()))
618 auto FirstOverlap =
B.find(AIt.start());
619 assert(FirstOverlap !=
B.end());
620 bool IntersectStart = FirstOverlap.start() < AIt.start();
622 <<
", IntersectStart: " << IntersectStart <<
"\n");
625 auto LastOverlap =
B.find(AIt.stop());
627 LastOverlap !=
B.end() && LastOverlap.start() < AIt.stop();
629 <<
", IntersectEnd: " << IntersectEnd <<
"\n");
632 if (IntersectStart && IntersectEnd && FirstOverlap == LastOverlap) {
640 if (*AIt && *AIt == *FirstOverlap)
641 Result.insert(AIt.start(), AIt.stop(), *AIt);
649 auto Next = FirstOverlap;
650 if (IntersectStart) {
653 if (*AIt && *AIt == *FirstOverlap)
654 Result.insert(AIt.start(), FirstOverlap.stop(), *AIt);
664 if (*AIt && *AIt == *LastOverlap)
665 Result.insert(LastOverlap.start(), AIt.stop(), *AIt);
674 while (
Next !=
B.end() &&
Next.start() < AIt.stop() &&
675 Next.stop() <= AIt.stop()) {
677 <<
"- insert intersection of a and " <<
toString(
Next));
678 if (*AIt && *AIt == *
Next)
688 void meetVars(VarFragMap &
A,
const VarFragMap &
B) {
692 A.remove_if([&](
auto &Entry) {
693 auto BIt =
B.find(Entry.first);
697 <<
Aggregates[Entry.first].first->getName() <<
"\n");
698 Entry.second = meetFragments(Entry.second, BIt->second);
703 bool meet(
const BasicBlock &BB,
const BlockLivenessTracker &Liveness,
704 VarFragMap &LiveSet) {
707 bool SingleVisit = !Liveness.canRevisit(BB);
711 bool FirstMeet =
true;
718 if (!Liveness.isVisited(
Pred))
721 auto PredLiveOut = LiveOut.
find(
Pred);
726 if (SingleVisit && Liveness.canMoveLiveOut(
Pred))
727 BBLiveIn = std::move(PredLiveOut->second);
729 BBLiveIn = PredLiveOut->second;
734 meetVars(BBLiveIn, PredLiveOut->second);
740 if (BBLiveIn.size() == 0)
745 LiveSet = std::move(BBLiveIn);
750 auto [CurrentLiveInEntry, Inserted] = LiveIn.
try_emplace(&BB);
754 CurrentLiveInEntry->second = BBLiveIn;
755 LiveSet = std::move(BBLiveIn);
761 if (!varFragMapsAreEqual(BBLiveIn, CurrentLiveInEntry->second)) {
763 CurrentLiveInEntry->second = BBLiveIn;
764 LiveSet = std::move(BBLiveIn);
773 unsigned StartBit,
unsigned EndBit,
unsigned Base,
775 assert(StartBit < EndBit &&
"Cannot create fragment of size <= 0");
780 Loc.OffsetInBits = StartBit;
781 Loc.SizeInBits = EndBit - StartBit;
782 assert(
Base &&
"Expected a non-zero ID for Base address");
785 BBInsertBeforeMap[&BB][Before].push_back(
Loc);
787 <<
" bits [" << StartBit <<
", " << EndBit <<
")\n");
795 unsigned StartBit,
unsigned EndBit,
unsigned Base,
797 if (!CoalesceAdjacentFragments)
804 auto CoalescedFrag = FragMap.find(StartBit);
806 if (CoalescedFrag.start() == StartBit && CoalescedFrag.stop() == EndBit)
809 LLVM_DEBUG(
dbgs() <<
"- Insert loc for bits " << CoalescedFrag.start()
810 <<
" to " << CoalescedFrag.stop() <<
"\n");
811 insertMemLoc(BB, Before, Var, CoalescedFrag.start(), CoalescedFrag.stop(),
816 VarFragMap &LiveSet) {
833 StartBit = Frag->OffsetInBits;
834 EndBit = StartBit + Frag->SizeInBits;
849 const unsigned Base =
850 DerefOffsetInBytes && *DerefOffsetInBytes * 8 == StartBit
854 << StartBit <<
", " << EndBit <<
"): " <<
toString(
Base)
861 auto FragIt = LiveSet.find(Var);
864 if (FragIt == LiveSet.end()) {
866 auto P = LiveSet.try_emplace(Var, FragsInMemMap(IntervalMapAlloc));
867 assert(
P.second &&
"Var already in map?");
869 P.first->second.insert(StartBit, EndBit,
Base);
874 FragsInMemMap &FragMap = FragIt->second;
877 if (!FragMap.overlaps(StartBit, EndBit)) {
879 FragMap.insert(StartBit, EndBit,
Base);
880 coalesceFragments(BB, Before, Var, StartBit, EndBit,
Base, VarLoc.
DL,
887 auto FirstOverlap = FragMap.find(StartBit);
888 assert(FirstOverlap != FragMap.end());
889 bool IntersectStart = FirstOverlap.start() < StartBit;
892 auto LastOverlap = FragMap.find(EndBit);
893 bool IntersectEnd = LastOverlap.valid() && LastOverlap.start() < EndBit;
896 if (IntersectStart && IntersectEnd && FirstOverlap == LastOverlap) {
897 LLVM_DEBUG(
dbgs() <<
"- Intersect single interval @ both ends\n");
905 auto EndBitOfOverlap = FirstOverlap.stop();
906 unsigned OverlapValue = FirstOverlap.value();
909 FirstOverlap.setStop(StartBit);
910 insertMemLoc(BB, Before, Var, FirstOverlap.start(), StartBit,
911 OverlapValue, VarLoc.
DL);
914 FragMap.insert(EndBit, EndBitOfOverlap, OverlapValue);
915 insertMemLoc(BB, Before, Var, EndBit, EndBitOfOverlap, OverlapValue,
919 FragMap.insert(StartBit, EndBit,
Base);
929 if (IntersectStart) {
932 FirstOverlap.setStop(StartBit);
933 insertMemLoc(BB, Before, Var, FirstOverlap.start(), StartBit,
934 *FirstOverlap, VarLoc.
DL);
943 LastOverlap.setStart(EndBit);
944 insertMemLoc(BB, Before, Var, EndBit, LastOverlap.stop(), *LastOverlap,
960 auto It = FirstOverlap;
963 while (It.valid() && It.start() >= StartBit && It.stop() <= EndBit) {
968 assert(!FragMap.overlaps(StartBit, EndBit));
970 FragMap.insert(StartBit, EndBit,
Base);
973 coalesceFragments(BB, Before, Var, StartBit, EndBit,
Base, VarLoc.
DL,
979 void process(
BasicBlock &BB, VarFragMap &LiveSet) {
980 BBInsertBeforeMap[&BB].
clear();
983 if (
const auto *Locs = FnVarLocs->
getWedge(&DVR)) {
985 addDef(
Loc, &DVR, *
I.getParent(), LiveSet);
989 if (
const auto *Locs = FnVarLocs->
getWedge(&
I)) {
991 addDef(
Loc, &
I, *
I.getParent(), LiveSet);
999 bool updateLiveOut(
const BasicBlock &BB,
const BlockLivenessTracker &Liveness,
1000 VarFragMap &&LiveSet) {
1001 if (!Liveness.hasRemainingReads(BB))
1003 if (!Liveness.canRevisit(BB)) {
1004 LiveOut[&BB] = std::move(LiveSet);
1008 auto [OutIt, OutInserted] = LiveOut.
try_emplace(&BB);
1009 if (!OutInserted && varFragMapsAreEqual(OutIt->second, LiveSet))
1011 OutIt->second = std::move(LiveSet);
1018 bool CoalesceAdjacentFragments)
1019 : Fn(Fn), VarsWithStackSlot(VarsWithStackSlot),
1020 CoalesceAdjacentFragments(CoalesceAdjacentFragments) {}
1046 this->FnVarLocs = FnVarLocs;
1054 unsigned RPONumber = 0;
1056 OrderToBB[RPONumber] = BB;
1057 BBToOrder[BB] = RPONumber;
1061 BlockLivenessTracker Liveness(OrderToBB, BBToOrder);
1062 unsigned NumBlocks = OrderToBB.
size();
1063 RPOWorklist Worklist(NumBlocks,
true);
1064 RPOWorklist Pending(NumBlocks);
1075 while (!Worklist.empty() || !Pending.empty()) {
1077 while (!Worklist.empty()) {
1078 unsigned RPO = Worklist.pop();
1082 bool InChanged = meet(*BB, Liveness, LiveSet);
1083 if (!Liveness.canRevisit(RPO))
1084 Liveness.retireVisitedPreds(*BB, LiveOut);
1086 InChanged |= Liveness.markVisited(BB);
1089 << BB->
getName() <<
" has new InLocs, process it\n");
1091 process(*BB, LiveSet);
1092 if (updateLiveOut(*BB, Liveness, std::move(LiveSet)))
1093 enqueueSuccessors(*BB, RPO, BBToOrder, Worklist, Pending);
1096 Worklist.swap(Pending);
1099 assert(Pending.empty() &&
"Pending should be empty");
1105 for (
auto &Pair : BBInsertBeforeMap) {
1106 InsertMap &Map = Pair.second;
1107 for (
auto &Pair : Map) {
1108 auto InsertBefore = Pair.first;
1109 assert(InsertBefore &&
"should never be null");
1110 auto FragMemLocs = Pair.second;
1113 for (
auto &FragMemLoc : FragMemLocs) {
1115 if (FragMemLoc.SizeInBits !=
1116 *
Aggregates[FragMemLoc.Var].first->getSizeInBits())
1118 Expr, FragMemLoc.OffsetInBits, FragMemLoc.SizeInBits);
1120 FragMemLoc.OffsetInBits / 8);
1122 FragMemLoc.DL.getInlinedAt());
1123 FnVarLocs->
addVarLoc(InsertBefore, Var, Expr, FragMemLoc.DL,
1124 Bases[FragMemLoc.Base]);
1134class AssignmentTrackingLowering {
1159 enum class LocKind { Mem, Val,
None };
1183 bool isSameSourceAssignment(
const Assignment &
Other)
const {
1189 static const char *
LUT[] = {
"Known",
"NoneOrPhi"};
1204 assert((!Source || Source->isDbgAssign()) &&
1205 "Cannot make an assignment from a non-assign DbgVariableRecord");
1206 return Assignment(
Known, ID, Source);
1208 static Assignment makeFromMemDef(
DIAssignID *ID) {
1209 return Assignment(
Known, ID);
1211 static Assignment makeNoneOrPhi() {
return Assignment(NoneOrPhi,
nullptr); }
1213 Assignment() :
Status(NoneOrPhi), ID(
nullptr) {}
1228 using UntaggedStoreAssignmentMap =
1231 using UnknownStoreAssignmentMap =
1233 using EscapingCallVarsMap =
1240 unsigned TrackedVariablesVectorSize = 0;
1245 UntaggedStoreAssignmentMap UntaggedStoreVars;
1248 UnknownStoreAssignmentMap UnknownStoreVars;
1252 EscapingCallVarsMap EscapingCallVars;
1256 InstInsertMap InsertBeforeMap;
1264 static bool mapsAreEqual(
const BitVector &Mask,
const AssignmentMap &
A,
1265 const AssignmentMap &
B) {
1267 return A[VarID].isSameSourceAssignment(B[VarID]);
1279 AssignmentMap StackHomeValue;
1281 AssignmentMap DebugValue;
1295 enum AssignmentKind { Stack,
Debug };
1296 const AssignmentMap &getAssignmentMap(AssignmentKind Kind)
const {
1299 return StackHomeValue;
1305 AssignmentMap &getAssignmentMap(AssignmentKind Kind) {
1306 return const_cast<AssignmentMap &
>(
1307 const_cast<const BlockInfo *
>(
this)->getAssignmentMap(Kind));
1310 bool isVariableTracked(
VariableID Var)
const {
1311 return VariableIDsInBlock[
static_cast<unsigned>(Var)];
1314 const Assignment &getAssignment(AssignmentKind Kind,
VariableID Var)
const {
1315 assert(isVariableTracked(Var) &&
"Var not tracked in block");
1316 return getAssignmentMap(Kind)[
static_cast<unsigned>(Var)];
1320 assert(isVariableTracked(Var) &&
"Var not tracked in block");
1321 return LiveLoc[
static_cast<unsigned>(Var)];
1327 VariableIDsInBlock.
set(
static_cast<unsigned>(Var));
1328 LiveLoc[
static_cast<unsigned>(Var)] =
K;
1334 void setAssignment(AssignmentKind Kind,
VariableID Var,
1335 const Assignment &AV) {
1336 VariableIDsInBlock.
set(
static_cast<unsigned>(Var));
1337 getAssignmentMap(Kind)[
static_cast<unsigned>(Var)] = AV;
1343 bool hasAssignment(AssignmentKind Kind,
VariableID Var,
1344 const Assignment &AV)
const {
1345 if (!isVariableTracked(Var))
1347 return AV.isSameSourceAssignment(getAssignment(Kind, Var));
1353 return VariableIDsInBlock ==
Other.VariableIDsInBlock &&
1354 LiveLoc ==
Other.LiveLoc &&
1355 mapsAreEqual(VariableIDsInBlock, StackHomeValue,
1356 Other.StackHomeValue) &&
1357 mapsAreEqual(VariableIDsInBlock, DebugValue,
Other.DebugValue);
1361 return LiveLoc.size() == DebugValue.size() &&
1362 LiveLoc.size() == StackHomeValue.size();
1366 void init(
int NumVars) {
1367 StackHomeValue.clear();
1370 VariableIDsInBlock =
BitVector(NumVars);
1371 StackHomeValue.insert(StackHomeValue.begin(), NumVars,
1372 Assignment::makeNoneOrPhi());
1373 DebugValue.insert(DebugValue.begin(), NumVars,
1374 Assignment::makeNoneOrPhi());
1375 LiveLoc.
insert(LiveLoc.
begin(), NumVars, LocKind::None);
1379 template <
typename ElmtType,
typename FnInputType>
1383 ElmtType (*Fn)(FnInputType, FnInputType)) {
1384 Target[Index] = Fn(
A[Index],
B[Index]);
1388 static BlockInfo
join(
const BlockInfo &
A,
const BlockInfo &
B,
int NumVars) {
1408 Intersect &=
B.VariableIDsInBlock;
1411 joinElmt(
VarID, Join.LiveLoc,
A.LiveLoc,
B.LiveLoc, joinKind);
1412 joinElmt(
VarID, Join.DebugValue,
A.DebugValue,
B.DebugValue,
1414 joinElmt(
VarID, Join.StackHomeValue,
A.StackHomeValue,
B.StackHomeValue,
1418 Join.VariableIDsInBlock =
A.VariableIDsInBlock;
1419 Join.VariableIDsInBlock |=
B.VariableIDsInBlock;
1448 bool join(
const BasicBlock &BB,
const BlockLivenessTracker &Liveness,
1449 BlockInfo &LiveSet);
1453 bool updateLiveOut(
const BasicBlock &BB,
const BlockLivenessTracker &Liveness,
1454 BlockInfo &&LiveSet);
1475 static LocKind joinKind(LocKind
A, LocKind
B);
1476 static Assignment joinAssignment(
const Assignment &
A,
const Assignment &
B);
1477 BlockInfo joinBlockInfo(
const BlockInfo &
A,
const BlockInfo &
B);
1483 void process(
BasicBlock &BB, BlockInfo *LiveSet);
1488 void processNonDbgInstruction(
Instruction &
I, BlockInfo *LiveSet);
1491 void processTaggedInstruction(
Instruction &
I, BlockInfo *LiveSet);
1494 void processUntaggedInstruction(
Instruction &
I, BlockInfo *LiveSet);
1496 BlockInfo *LiveSet);
1497 void processEscapingCall(
Instruction &
I, BlockInfo *LiveSet);
1502 void addMemDef(BlockInfo *LiveSet,
VariableID Var,
const Assignment &AV);
1504 void addDbgDef(BlockInfo *LiveSet,
VariableID Var,
const Assignment &AV);
1508 void setLocKind(BlockInfo *LiveSet,
VariableID Var, LocKind
K);
1511 LocKind getLocKind(BlockInfo *LiveSet,
VariableID Var);
1513 bool hasVarWithAssignment(BlockInfo *LiveSet, BlockInfo::AssignmentKind Kind,
1529 : Fn(Fn), Layout(Layout), VarsWithStackSlot(VarsWithStackSlot) {}
1537AssignmentTrackingLowering::getContainedFragments(
VariableID Var)
const {
1538 auto R = VarContains.find(Var);
1539 if (R == VarContains.end())
1544void AssignmentTrackingLowering::touchFragment(
VariableID Var) {
1545 VarsTouchedThisFrame.insert(Var);
1548void AssignmentTrackingLowering::setLocKind(BlockInfo *LiveSet,
VariableID Var,
1550 auto SetKind = [
this](BlockInfo *LiveSet,
VariableID Var, LocKind
K) {
1551 LiveSet->setLocKind(Var, K);
1554 SetKind(LiveSet, Var, K);
1557 for (
VariableID Frag : getContainedFragments(Var))
1558 SetKind(LiveSet, Frag, K);
1561AssignmentTrackingLowering::LocKind
1562AssignmentTrackingLowering::getLocKind(BlockInfo *LiveSet,
VariableID Var) {
1563 return LiveSet->getLocKind(Var);
1566void AssignmentTrackingLowering::addMemDef(BlockInfo *LiveSet,
VariableID Var,
1567 const Assignment &AV) {
1568 LiveSet->setAssignment(BlockInfo::Stack, Var, AV);
1573 Assignment FragAV = AV;
1574 FragAV.Source =
nullptr;
1575 for (
VariableID Frag : getContainedFragments(Var))
1576 LiveSet->setAssignment(BlockInfo::Stack, Frag, FragAV);
1579void AssignmentTrackingLowering::addDbgDef(BlockInfo *LiveSet,
VariableID Var,
1580 const Assignment &AV) {
1581 LiveSet->setAssignment(BlockInfo::Debug, Var, AV);
1586 Assignment FragAV = AV;
1587 FragAV.Source =
nullptr;
1588 for (
VariableID Frag : getContainedFragments(Var))
1589 LiveSet->setAssignment(BlockInfo::Debug, Frag, FragAV);
1598 "Cannot get a DIAssignID from a non-assign DbgVariableRecord!");
1603bool AssignmentTrackingLowering::hasVarWithAssignment(
1604 BlockInfo *LiveSet, BlockInfo::AssignmentKind Kind,
VariableID Var,
1605 const Assignment &AV) {
1606 if (!LiveSet->hasAssignment(Kind, Var, AV))
1611 for (
VariableID Frag : getContainedFragments(Var))
1612 if (!LiveSet->hasAssignment(Kind, Frag, AV))
1618const char *
locStr(AssignmentTrackingLowering::LocKind
Loc) {
1619 using LocKind = AssignmentTrackingLowering::LocKind;
1640 if (!
Next->hasDbgRecords())
1642 return &*
Next->getDbgRecordRange().begin();
1650void AssignmentTrackingLowering::emitDbgValue(
1663 assert(InsertBefore &&
"Shouldn't be inserting after a terminator");
1672 InsertBeforeMap[InsertBefore].
push_back(VarLoc);
1676 if (Kind == LocKind::Mem) {
1681 if (
Assign->isKillAddress()) {
1683 Kind = LocKind::Val;
1688 "fragment info should be stored in value-expression only");
1691 if (
auto OptFragInfo =
Source->getExpression()->getFragmentInfo()) {
1692 auto FragInfo = *OptFragInfo;
1694 Expr, FragInfo.OffsetInBits, FragInfo.SizeInBits);
1697 std::tie(Val, Expr) =
1704 if (Kind == LocKind::Val) {
1705 Emit(
Source->getRawLocation(),
Source->getExpression());
1709 if (Kind == LocKind::None) {
1710 Emit(
nullptr,
Source->getExpression());
1715void AssignmentTrackingLowering::processNonDbgInstruction(
1716 Instruction &
I, AssignmentTrackingLowering::BlockInfo *LiveSet) {
1717 if (
I.hasMetadata(LLVMContext::MD_DIAssignID))
1718 processTaggedInstruction(
I, LiveSet);
1720 processUntaggedInstruction(
I, LiveSet);
1725 processEscapingCall(
I, LiveSet);
1728void AssignmentTrackingLowering::processUnknownStoreToVariable(
1732 addMemDef(LiveSet, Var, Assignment::makeNoneOrPhi());
1735 if (getLocKind(LiveSet, Var) != LocKind::Mem)
1739 Assignment DbgAV = LiveSet->getAssignment(BlockInfo::Debug, Var);
1740 if (DbgAV.Status != Assignment::NoneOrPhi && DbgAV.Source) {
1742 DbgAV.dump(
dbgs());
dbgs() <<
"\n");
1743 setLocKind(LiveSet, Var, LocKind::Val);
1744 emitDbgValue(LocKind::Val, DbgAV.Source, &
I);
1750 assert(InsertBefore &&
"Shouldn't be inserting after a terminator");
1756 Fn.getContext(), 0, 0,
V.getVariable()->getScope(), InlinedAt);
1764 InsertBeforeMap[InsertBefore].push_back(VarLoc);
1767void AssignmentTrackingLowering::processUntaggedInstruction(
1768 Instruction &
I, AssignmentTrackingLowering::BlockInfo *LiveSet) {
1780 assert(!
I.hasMetadata(LLVMContext::MD_DIAssignID));
1781 auto It = UntaggedStoreVars.find(&
I);
1782 if (It == UntaggedStoreVars.end()) {
1789 if (
auto UnhandledStoreIt = UnknownStoreVars.find(&
I);
1790 UnhandledStoreIt != UnknownStoreVars.end()) {
1791 LLVM_DEBUG(
dbgs() <<
"Processing untagged unknown store " <<
I <<
"\n");
1792 for (
auto &Var : UnhandledStoreIt->second)
1793 processUnknownStoreToVariable(
I, Var, LiveSet);
1798 LLVM_DEBUG(
dbgs() <<
"processUntaggedInstruction on UNTAGGED INST " <<
I
1802 for (
auto [Var, Info] : It->second) {
1806 addMemDef(LiveSet, Var, Assignment::makeNoneOrPhi());
1807 addDbgDef(LiveSet, Var, Assignment::makeNoneOrPhi());
1808 setLocKind(LiveSet, Var, LocKind::Mem);
1816 if (
auto Frag =
V.getFragment()) {
1819 assert(R &&
"unexpected createFragmentExpression failure");
1823 if (
Info.OffsetInBits)
1824 Ops = {dwarf::DW_OP_plus_uconst,
Info.OffsetInBits / 8};
1831 assert(InsertBefore &&
"Shouldn't be inserting after a terminator");
1836 Fn.getContext(), 0, 0,
V.getVariable()->getScope(), InlinedAt);
1845 InsertBeforeMap[InsertBefore].push_back(VarLoc);
1849void AssignmentTrackingLowering::processEscapingCall(
1850 Instruction &
I, AssignmentTrackingLowering::BlockInfo *LiveSet) {
1851 auto It = EscapingCallVars.find(&
I);
1852 if (It == EscapingCallVars.end())
1857 const DataLayout &Layout = Fn.getDataLayout();
1859 for (
auto &[Var, Addr, AddrExpr] : It->second) {
1865 addMemDef(LiveSet, Var, Assignment::makeNoneOrPhi());
1866 addDbgDef(LiveSet, Var, Assignment::makeNoneOrPhi());
1867 setLocKind(LiveSet, Var, LocKind::Mem);
1870 << FnVarLocs->getVariable(Var).getVariable()->getName()
1871 <<
", setting LocKind to Mem\n");
1878 if (
auto Frag =
V.getFragment()) {
1881 assert(R &&
"unexpected createFragmentExpression failure");
1889 assert(InsertBefore &&
"Shouldn't be inserting after a terminator");
1893 Fn.getContext(), 0, 0,
V.getVariable()->getScope(), InlinedAt);
1901 InsertBeforeMap[InsertBefore].push_back(VarLoc);
1905void AssignmentTrackingLowering::processTaggedInstruction(
1906 Instruction &
I, AssignmentTrackingLowering::BlockInfo *LiveSet) {
1912 if (LinkedDPAssigns.empty())
1921 "expected Assign's variable to have stack slot");
1924 addMemDef(LiveSet, Var, AV);
1932 if (hasVarWithAssignment(LiveSet, BlockInfo::Debug, Var, AV)) {
1938 LiveSet->DebugValue[
static_cast<unsigned>(Var)].dump(
dbgs());
1940 setLocKind(LiveSet, Var, LocKind::Mem);
1941 emitDbgValue(LocKind::Mem, Assign, &
I);
1950 LocKind PrevLoc = getLocKind(LiveSet, Var);
1952 case LocKind::Val: {
1956 setLocKind(LiveSet, Var, LocKind::Val);
1958 case LocKind::Mem: {
1962 Assignment DbgAV = LiveSet->getAssignment(BlockInfo::Debug, Var);
1963 if (DbgAV.Status == Assignment::NoneOrPhi) {
1966 setLocKind(LiveSet, Var, LocKind::None);
1967 emitDbgValue(LocKind::None, Assign, &
I);
1971 setLocKind(LiveSet, Var, LocKind::Val);
1973 emitDbgValue(LocKind::Val, DbgAV.Source, &
I);
1976 emitDbgValue(LocKind::None, Assign, &
I);
1980 case LocKind::None: {
1984 setLocKind(LiveSet, Var, LocKind::None);
1991 BlockInfo *LiveSet) {
1994 if (!VarsWithStackSlot->count(
getAggregate(DbgAssign)))
1998 Assignment AV = Assignment::make(
getIDFromMarker(*DbgAssign), DbgAssign);
1999 addDbgDef(LiveSet, Var, AV);
2001 LLVM_DEBUG(
dbgs() <<
"processDbgAssign on " << *DbgAssign <<
"\n";);
2007 if (hasVarWithAssignment(LiveSet, BlockInfo::Stack, Var, AV)) {
2015 <<
"Val, Stack matches Debug program but address is killed\n";);
2016 Kind = LocKind::Val;
2019 Kind = LocKind::Mem;
2021 setLocKind(LiveSet, Var, Kind);
2022 emitDbgValue(Kind, DbgAssign, DbgAssign);
2027 setLocKind(LiveSet, Var, LocKind::Val);
2028 emitDbgValue(LocKind::Val, DbgAssign, DbgAssign);
2033 BlockInfo *LiveSet) {
2046 Assignment AV = Assignment::makeNoneOrPhi();
2047 addDbgDef(LiveSet, Var, AV);
2051 <<
" -> Val, dbg.value override");
2053 setLocKind(LiveSet, Var, LocKind::Val);
2058 if (
auto F =
DbgValue.getExpression()->getFragmentInfo())
2059 return F->SizeInBits == 0;
2063void AssignmentTrackingLowering::processDbgVariableRecord(
2070 processDbgAssign(&DVR, LiveSet);
2072 processDbgValue(&DVR, LiveSet);
2075void AssignmentTrackingLowering::resetInsertionPoint(
Instruction &After) {
2078 if (R == InsertBeforeMap.end())
2084 if (R == InsertBeforeMap.end())
2089void AssignmentTrackingLowering::process(
BasicBlock &BB, BlockInfo *LiveSet) {
2092 bool ProcessedLeadingDbgRecords = !BB.
begin()->hasDbgRecords();
2094 assert(VarsTouchedThisFrame.empty());
2101 if (ProcessedLeadingDbgRecords) {
2106 if (
II->isTerminator())
2108 resetInsertionPoint(*
II);
2109 processNonDbgInstruction(*
II, LiveSet);
2110 assert(LiveSet->isValid());
2116 if (
II != EI &&
II->hasDbgRecords()) {
2121 resetInsertionPoint(DVR);
2122 processDbgVariableRecord(DVR, LiveSet);
2123 assert(LiveSet->isValid());
2126 ProcessedLeadingDbgRecords =
true;
2134 for (
auto Var : VarsTouchedThisFrame) {
2135 LocKind
Loc = getLocKind(LiveSet, Var);
2143 if (
Loc != LocKind::Mem) {
2146 NotAlwaysStackHomed.insert(Aggr);
2149 VarsTouchedThisFrame.clear();
2153AssignmentTrackingLowering::LocKind
2154AssignmentTrackingLowering::joinKind(LocKind
A, LocKind
B) {
2157 return A ==
B ?
A : LocKind::None;
2160AssignmentTrackingLowering::Assignment
2161AssignmentTrackingLowering::joinAssignment(
const Assignment &
A,
2162 const Assignment &
B) {
2169 if (!
A.isSameSourceAssignment(
B))
2170 return Assignment::makeNoneOrPhi();
2171 if (
A.Status == Assignment::NoneOrPhi)
2172 return Assignment::makeNoneOrPhi();
2188 if (
A.Source ==
B.Source)
2190 if (!
A.Source || !
B.Source)
2192 if (
A.Source->isEquivalentTo(*
B.Source))
2197 assert(
A.Status ==
B.Status &&
A.Status == Assignment::Known);
2199 return Assignment::make(
A.ID, Source);
2202AssignmentTrackingLowering::BlockInfo
2203AssignmentTrackingLowering::joinBlockInfo(
const BlockInfo &
A,
2204 const BlockInfo &
B) {
2205 return BlockInfo::join(
A,
B, TrackedVariablesVectorSize);
2208bool AssignmentTrackingLowering::join(
const BasicBlock &BB,
2209 const BlockLivenessTracker &Liveness,
2210 BlockInfo &LiveSet) {
2211 bool StoreLiveIn = Liveness.canRevisit(BB);
2222 if (Liveness.isVisited(
Pred))
2227 if (VisitedPreds.
empty()) {
2229 LiveSet.init(TrackedVariablesVectorSize);
2232 auto It = LiveIn.try_emplace(&BB, BlockInfo());
2233 bool DidInsert = It.second;
2235 It.first->second.init(TrackedVariablesVectorSize);
2236 LiveSet = It.first->second;
2243 if (VisitedPreds.
size() == 1) {
2244 auto PredIt = LiveOut.find(VisitedPreds[0]);
2245 assert(PredIt != LiveOut.end() &&
2246 "block should have been processed already");
2248 if (Liveness.canMoveLiveOut(VisitedPreds[0]))
2249 LiveSet = std::move(PredIt->second);
2251 LiveSet = PredIt->second;
2254 const BlockInfo &PredLiveOut = PredIt->second;
2258 auto [CurrentLiveInEntry,
Inserted] = LiveIn.try_emplace(&BB, PredLiveOut);
2260 LiveSet = CurrentLiveInEntry->second;
2263 if (PredLiveOut != CurrentLiveInEntry->second) {
2264 CurrentLiveInEntry->second = PredLiveOut;
2265 LiveSet = CurrentLiveInEntry->second;
2273 auto PredLiveOut0 = LiveOut.find(VisitedPreds[0]);
2274 auto PredLiveOut1 = LiveOut.find(VisitedPreds[1]);
2275 assert(PredLiveOut0 != LiveOut.end() && PredLiveOut1 != LiveOut.end() &&
2276 "blocks should have been processed already");
2277 BlockInfo BBLiveIn =
2278 joinBlockInfo(PredLiveOut0->second, PredLiveOut1->second);
2283 const auto &PredLiveOut = LiveOut.find(
Pred);
2284 assert(PredLiveOut != LiveOut.end() &&
2285 "block should have been processed already");
2286 BBLiveIn = joinBlockInfo(std::move(BBLiveIn), PredLiveOut->second);
2290 LiveSet = std::move(BBLiveIn);
2297 auto [CurrentLiveInEntry,
Inserted] = LiveIn.try_emplace(&BB);
2298 if (!Inserted && BBLiveIn == CurrentLiveInEntry->second)
2301 CurrentLiveInEntry->second = std::move(BBLiveIn);
2305bool AssignmentTrackingLowering::updateLiveOut(
2306 const BasicBlock &BB,
const BlockLivenessTracker &Liveness,
2307 BlockInfo &&LiveSet) {
2308 if (!Liveness.hasRemainingReads(BB))
2310 if (!Liveness.canRevisit(BB)) {
2311 LiveOut[&BB] = std::move(LiveSet);
2315 auto [OutIt, OutInserted] = LiveOut.try_emplace(&BB);
2316 if (!OutInserted && OutIt->second == LiveSet)
2318 OutIt->second = std::move(LiveSet);
2325 auto ALeft =
A.OffsetInBits;
2326 auto BLeft =
B.OffsetInBits;
2330 auto ARight = ALeft +
A.SizeInBits;
2331 auto BRight = BLeft +
B.SizeInBits;
2332 if (BRight > ARight)
2337static std::optional<at::AssignmentInfo>
2347 return std::nullopt;
2355 if (ID != Intrinsic::experimental_vp_strided_store &&
2356 ID != Intrinsic::masked_store && ID != Intrinsic::vp_scatter &&
2357 ID != Intrinsic::masked_scatter && ID != Intrinsic::vp_store &&
2358 ID != Intrinsic::masked_compressstore)
2394 AssignmentTrackingLowering::UntaggedStoreAssignmentMap &UntaggedStoreVars,
2395 AssignmentTrackingLowering::UnknownStoreAssignmentMap &UnknownStoreVars,
2396 AssignmentTrackingLowering::EscapingCallVarsMap &EscapingCallVars,
2397 unsigned &TrackedVariablesVectorSize) {
2411 if (
Record->isDbgDeclare()) {
2417 if (!VarsWithStackSlot.
contains(DA))
2419 if (Seen.
insert(DV).second)
2420 FragmentMap[DA].push_back(DV);
2422 for (
auto &BB : Fn) {
2423 for (
auto &
I : BB) {
2425 ProcessDbgRecord(&DVR);
2429 std::optional<DIExpression::FragmentInfo> FragInfo;
2434 I.getDataLayout(), Info->Base,
2435 Info->OffsetInBits, Info->SizeInBits, Assign, FragInfo) ||
2436 (FragInfo && FragInfo->SizeInBits == 0))
2445 FragInfo = Assign->getExpression()->getFragmentInfo();
2449 Assign->getDebugLoc().getInlinedAt());
2451 if (!VarsWithStackSlot.
contains(DA))
2455 UntaggedStoreVars[&
I].push_back(
2458 if (Seen.
insert(DV).second)
2459 FragmentMap[DA].push_back(DV);
2462 HandleDbgAssignForStore(DVR);
2470 Assign->getDebugLoc().getInlinedAt());
2472 if (!VarsWithStackSlot.
contains(DA))
2479 HandleDbgAssignForUnknownStore(DVR);
2492 if (CB->onlyReadsMemory())
2496 for (
unsigned ArgIdx = 0; ArgIdx < CB->arg_size(); ++ArgIdx) {
2497 Value *Arg = CB->getArgOperand(ArgIdx);
2501 if (CB->paramHasAttr(ArgIdx, Attribute::ReadOnly) ||
2502 CB->paramHasAttr(ArgIdx, Attribute::ReadNone))
2505 if (CB->isByValArgument(ArgIdx))
2520 if (!VarsWithStackSlot.
contains(DA))
2524 EscapingCallVars[&
I].push_back(
2533 for (
auto &Pair : FragmentMap) {
2535 std::sort(Frags.
begin(), Frags.
end(),
2537 return Elmt.getFragmentOrDefault().SizeInBits >
2538 Next.getFragmentOrDefault().SizeInBits;
2545 AssignmentTrackingLowering::OverlapMap Map;
2546 for (
auto &Pair : FragmentMap) {
2547 auto &Frags = Pair.second;
2548 for (
auto It = Frags.begin(), IEnd = Frags.end(); It != IEnd; ++It) {
2558 for (; OtherIt != IEnd; ++OtherIt) {
2562 Map[OtherVar].push_back(ThisVar);
2573 for (
auto *DVR : DPDeclares)
2580bool AssignmentTrackingLowering::run(FunctionVarLocsBuilder *FnVarLocsBuilder) {
2582 LLVM_DEBUG(
dbgs() <<
"[AT] Dropping var locs in: " << Fn.getName()
2583 <<
": too many blocks (" << Fn.size() <<
")\n");
2588 FnVarLocs = FnVarLocsBuilder;
2598 Fn, FnVarLocs, *VarsWithStackSlot, UntaggedStoreVars, UnknownStoreVars,
2599 EscapingCallVars, TrackedVariablesVectorSize);
2606 unsigned RPONumber = 0;
2608 OrderToBB[RPONumber] = BB;
2609 BBToOrder[BB] = RPONumber;
2614 BlockLivenessTracker Liveness(OrderToBB, BBToOrder);
2615 unsigned NumBlocks = OrderToBB.
size();
2616 RPOWorklist Worklist(NumBlocks,
true);
2617 RPOWorklist Pending(NumBlocks);
2629 while (!Worklist.empty() || !Pending.empty()) {
2631 while (!Worklist.empty()) {
2632 unsigned RPO = Worklist.pop();
2637 bool InChanged =
join(*BB, Liveness, LiveSet);
2638 if (!Liveness.canRevisit(RPO))
2639 Liveness.retireVisitedPreds(*BB, LiveOut);
2642 InChanged |= Liveness.markVisited(BB);
2647 process(*BB, &LiveSet);
2648 if (updateLiveOut(*BB, Liveness, std::move(LiveSet)))
2649 enqueueSuccessors(*BB, RPO, BBToOrder, Worklist, Pending);
2652 Worklist.swap(Pending);
2655 assert(Pending.empty() &&
"Pending should be empty");
2663 bool InsertedAnyIntrinsics =
false;
2672 for (
const auto &Pair : InsertBeforeMap) {
2673 auto &Vec = Pair.second;
2679 if (NotAlwaysStackHomed.contains(Aggr))
2689 NotAlwaysStackHomed.insert(Aggr);
2698 if (AlwaysStackHomed.
insert(Aggr).second) {
2706 FnVarLocs->addSingleLocVar(Var, VarLoc.
Expr, VarLoc.
DL, VarLoc.
Values);
2707 InsertedAnyIntrinsics =
true;
2713 for (
const auto &[InsertBefore, Vec] : InsertBeforeMap) {
2720 if (AlwaysStackHomed.
contains(Aggr))
2723 InsertedAnyIntrinsics =
true;
2726 FnVarLocs->setWedge(InsertBefore, std::move(NewDefs));
2729 InsertedAnyIntrinsics |= emitPromotedVarLocs(FnVarLocs);
2731 return InsertedAnyIntrinsics;
2734bool AssignmentTrackingLowering::emitPromotedVarLocs(
2735 FunctionVarLocsBuilder *FnVarLocs) {
2736 bool InsertedAnyIntrinsics =
false;
2745 assert(InsertBefore &&
"Unexpected: debug intrinsics after a terminator");
2749 InsertedAnyIntrinsics =
true;
2751 for (
auto &BB : Fn) {
2752 for (
auto &
I : BB) {
2756 TranslateDbgRecord(&DVR);
2759 return InsertedAnyIntrinsics;
2779 VariableDefinedBytes.
clear();
2781 auto HandleLocsForWedge = [&](
auto *WedgePosition) {
2783 const auto *Locs = FnVarLocs.
getWedge(WedgePosition);
2788 bool ChangedThisWedge =
false;
2793 for (
auto RIt = Locs->rbegin(), REnd = Locs->rend(); RIt != REnd; ++RIt) {
2797 uint64_t SizeInBits = Aggr.first->getSizeInBits().value_or(0);
2801 const uint64_t MaxSizeBytes = 2048;
2803 if (SizeInBytes == 0 || SizeInBytes > MaxSizeBytes) {
2817 bool FirstDefinition = InsertResult.second;
2818 BitVector &DefinedBytes = InsertResult.first->second;
2821 RIt->Expr->getFragmentInfo().value_or(
2823 bool InvalidFragment =
Fragment.endInBits() > SizeInBits;
2828 if (FirstDefinition || InvalidFragment ||
2830 if (!InvalidFragment)
2831 DefinedBytes.
set(StartInBytes, EndInBytes);
2838 ChangedThisWedge =
true;
2843 if (ChangedThisWedge) {
2844 std::reverse(NewDefsReversed.
begin(), NewDefsReversed.
end());
2845 FnVarLocs.
setWedge(WedgePosition, std::move(NewDefsReversed));
2850 HandleLocsForWedge(&
I);
2852 HandleLocsForWedge(&DVR);
2877 auto HandleLocsForWedge = [&](
auto *WedgePosition) {
2878 const auto *Locs = FnVarLocs.
getWedge(WedgePosition);
2883 bool ChangedThisWedge =
false;
2891 std::nullopt,
Loc.DL.getInlinedAt());
2896 if (Inserted || VMI->second.first !=
Loc.Values ||
2897 VMI->second.second !=
Loc.Expr) {
2898 VMI->second = {
Loc.Values,
Loc.Expr};
2904 ChangedThisWedge =
true;
2909 if (ChangedThisWedge) {
2910 FnVarLocs.
setWedge(WedgePosition, std::move(NewDefs));
2917 HandleLocsForWedge(&DVR);
2918 HandleLocsForWedge(&
I);
2943 VarsWithDef[
A].
insert(
V.getFragmentOrDefault());
2949 auto FragsIt = VarsWithDef.
find(
A);
2950 if (FragsIt == VarsWithDef.
end())
2953 return DIExpression::fragmentsOverlap(Frag, V.getFragmentOrDefault());
2964 auto HandleLocsForWedge = [&](
auto *WedgePosition) {
2965 const auto *Locs = FnVarLocs.
getWedge(WedgePosition);
2970 bool ChangedThisWedge =
false;
2978 Loc.DL.getInlinedAt()};
2983 if (
Loc.Values.isKillLocation(
Loc.Expr) && !HasDefinedBits(Aggr, Var)) {
2986 ChangedThisWedge =
true;
2990 DefineBits(Aggr, Var);
2995 if (ChangedThisWedge) {
2996 FnVarLocs.
setWedge(WedgePosition, std::move(NewDefs));
3002 HandleLocsForWedge(&DVR);
3003 HandleLocsForWedge(&
I);
3011 bool MadeChanges =
false;
3025 for (
auto &BB : Fn) {
3026 for (
auto &
I : BB) {
3052 AssignmentTrackingLowering
Pass(Fn, Layout, &VarsWithStackSlot);
3057 MemLocFragmentFill
Pass(Fn, &VarsWithStackSlot,
3059 Pass.run(FnVarLocs);
3076 auto &
DL =
F.getDataLayout();
3100 LLVM_DEBUG(
dbgs() <<
"AssignmentTrackingAnalysis run on " <<
F.getName()
3110 Results->init(Builder);
3113 Results->print(
errs(),
F);
3125 "Assignment Tracking Analysis",
false,
true)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
std::pair< const DILocalVariable *, const DILocation * > DebugAggregate
A whole (unfragmented) source variable.
VarLocInsertPt getNextNode(const DbgRecord *DVR)
static void analyzeFunction(Function &Fn, const DataLayout &Layout, FunctionVarLocsBuilder *FnVarLocs)
static std::pair< Value *, DIExpression * > walkToAllocaAndPrependOffsetDeref(const DataLayout &DL, Value *Start, DIExpression *Expression)
Walk backwards along constant GEPs and bitcasts to the base storage from Start as far as possible.
static DenseSet< DebugAggregate > findVarsWithStackSlot(Function &Fn)
static bool fullyContains(DIExpression::FragmentInfo A, DIExpression::FragmentInfo B)
Return true if A fully contains B.
static std::optional< at::AssignmentInfo > getUntaggedStoreAssignmentInfo(const Instruction &I, const DataLayout &Layout)
static bool removeUndefDbgLocsFromEntryBlock(const BasicBlock *BB, FunctionVarLocsBuilder &FnVarLocs)
DenseMap< BasicBlock *, unsigned > BlockToRPOMap
static cl::opt< bool > PrintResults("print-debug-ata", cl::init(false), cl::Hidden)
Print the results of the analysis. Respects -filter-print-funcs.
const char * locStr(AssignmentTrackingLowering::LocKind Loc)
PointerUnion< const Instruction *, const DbgRecord * > VarLocInsertPt
static bool removeRedundantDbgLocsUsingForwardScan(const BasicBlock *BB, FunctionVarLocsBuilder &FnVarLocs)
Remove redundant location defs using a forward scan.
static bool removeRedundantDbgLocs(const BasicBlock *BB, FunctionVarLocsBuilder &FnVarLocs)
static cl::opt< bool > EnableMemLocFragFill("mem-loc-frag-fill", cl::init(true), cl::Hidden)
Option for debugging the pass, determines if the memory location fragment filling happens after gener...
static AssignmentTrackingLowering::OverlapMap buildOverlapMapAndRecordDeclares(Function &Fn, FunctionVarLocsBuilder *FnVarLocs, const DenseSet< DebugAggregate > &VarsWithStackSlot, AssignmentTrackingLowering::UntaggedStoreAssignmentMap &UntaggedStoreVars, AssignmentTrackingLowering::UnknownStoreAssignmentMap &UnknownStoreVars, AssignmentTrackingLowering::EscapingCallVarsMap &EscapingCallVars, unsigned &TrackedVariablesVectorSize)
Build a map of {Variable x: Variables y} where all variable fragments contained within the variable f...
DenseMap< unsigned, BasicBlock * > RPOToBlockMap
Maps Reverse Post-Order (RPO) numbers to BasicBlocks and vice versa.
static DIAssignID * getIDFromMarker(const DbgVariableRecord &DVR)
static DebugAggregate getAggregate(const DebugVariable &Var)
static bool hasZeroSizedFragment(DbgVariableRecord &DbgValue)
static DIAssignID * getIDFromInst(const Instruction &I)
AllocaInst * getUnknownStore(const Instruction &I, const DataLayout &Layout)
static std::optional< int64_t > getDerefOffsetInBytes(const DIExpression *DIExpr)
Extract the offset used in DIExpr.
static bool removeRedundantDbgLocsUsingBackwardScan(const BasicBlock *BB, FunctionVarLocsBuilder &FnVarLocs)
Remove redundant definitions within sequences of consecutive location defs.
static cl::opt< cl::boolOrDefault > CoalesceAdjacentFragmentsOpt("debug-ata-coalesce-frags", cl::Hidden)
Coalesce adjacent dbg locs describing memory locations that have contiguous fragments.
static cl::opt< unsigned > MaxNumBlocks("debug-ata-max-blocks", cl::init(10000), cl::desc("Maximum num basic blocks before debug info dropped"), cl::Hidden)
static bool shouldCoalesceFragments(Function &F)
This file implements the BitVector class.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static ManagedStatic< cl::opt< bool, true >, CreateDebug > Debug
This file defines DenseMapInfo traits for DenseMap.
This file contains constants used for implementing Dwarf debug support.
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This file implements a coalescing interval map for small objects.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
IntervalMap< SlotIndex, DbgVariableValue, 4 > LocMap
Map of where a user value is live to that value.
print mir2vec MIR2Vec Vocabulary Printer Pass
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
Scalar Replacement Of Aggregates
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Helper class to build FunctionVarLocs, since that class isn't easy to modify.
void setWedge(VarLocInsertPt Before, SmallVector< VarLocInfo > &&Wedge)
Replace the defs that come just before /p Before with /p Wedge.
const SmallVectorImpl< VarLocInfo > * getWedge(VarLocInsertPt Before) const
Return ptr to wedge of defs or nullptr if no defs come just before /p Before.
unsigned getNumVariables() const
void addSingleLocVar(DebugVariable Var, DIExpression *Expr, DebugLoc DL, RawLocationWrapper R)
Add a def for a variable that is valid for its lifetime.
VariableID insertVariable(DebugVariable V)
Find or insert V and return the ID.
void addVarLoc(VarLocInsertPt Before, DebugVariable Var, DIExpression *Expr, DebugLoc DL, RawLocationWrapper R)
Add a def to the wedge of defs just before /p Before.
const DebugVariable & getVariable(VariableID ID) const
Get a variable from its ID.
Class recording the (high level) value of a variable.
Class for arbitrary precision integers.
uint64_t getZExtValue() const
Get zero extended value.
bool getBoolValue() const
Convert APInt to a boolean value.
an instruction to allocate memory on the stack
Represent a constant reference to an array (0 or more elements consecutively in memory),...
AssignmentTrackingAnalysis()
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
LLVM_ABI bool hasNPredecessorsOrMore(unsigned N) const
Return true if this block has N predecessors or more.
bool test(unsigned Idx) const
Returns true if bit Idx is set.
BitVector & reset()
Reset all bits in the bitvector.
int find_first_unset_in(unsigned Begin, unsigned End) const
Returns the index of the first unset bit in the range [Begin, End).
BitVector & set()
Set all bits in the bitvector.
iterator_range< const_set_bits_iterator > set_bits() const
A structured debug information entry.
static LLVM_ABI DIExpression * append(const DIExpression *Expr, ArrayRef< uint64_t > Ops)
Append the opcodes Ops to DIExpr.
unsigned getNumElements() const
DbgVariableFragmentInfo FragmentInfo
LLVM_ABI bool startsWithDeref() const
Return whether the first element a DW_OP_deref.
static LLVM_ABI std::optional< FragmentInfo > getFragmentInfo(expr_op_iterator Start, expr_op_iterator End)
Retrieve the details of this fragment expression.
ArrayRef< uint64_t > getElements() const
static LLVM_ABI 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 LLVM_ABI 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 ...
static LLVM_ABI DIExpression * prependOpcodes(const DIExpression *Expr, SmallVectorImpl< uint64_t > &Ops, bool StackValue=false, bool EntryValue=false)
Prepend DIExpr with the given opcodes and optionally turn it into a stack value.
LLVM_ABI std::optional< uint64_t > getSizeInBits() const
Determines the size of the variable's type.
StringRef getName() const
A parsed version of the target data layout string in and methods for querying it.
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
Instruction * MarkedInstr
Link back to the Instruction that owns this marker.
LLVM_ABI iterator_range< simple_ilist< DbgRecord >::iterator > getDbgRecordRange()
Produce a range over all the DbgRecords in this Marker.
Base class for non-instruction debug metadata records that have positions within IR.
DebugLoc getDebugLoc() const
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI Value * getAddress() const
LLVM_ABI bool isKillAddress() const
Check whether this kills the address component.
LLVM_ABI DIAssignID * getAssignID() const
DIExpression * getExpression() const
DILocalVariable * getVariable() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
DIExpression * getAddressExpression() const
LLVM_ABI Result run(Function &F, FunctionAnalysisManager &FAM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
LLVM_ABI DILocation * getInlinedAt() const
Identifies a unique instance of a variable.
const DILocation * getInlinedAt() const
const DILocalVariable * getVariable() const
iterator find(const_arg_type_t< KeyT > Val)
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Implements a dense probed hash-table based set.
Class representing an expression and its matching format.
Data structure describing the variable locations in a function.
LLVM_ABI void print(raw_ostream &OS, const Function &Fn) const
const VarLocInfo * locs_begin(const Instruction *Before) const
First variable location definition that comes before Before.
const VarLocInfo * single_locs_begin() const
const VarLocInfo * locs_end(const Instruction *Before) const
One past the last variable location definition that comes before Before.
const VarLocInfo * single_locs_end() const
One past the last single-location variable location definition.
LLVM_ABI void init(FunctionVarLocsBuilder &Builder)
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
bool isTerminator() const
const_iterator begin() const
void insert(KeyT a, KeyT b, ValT y)
insert - Add a mapping of [a;b] to y, coalesce with adjacent intervals.
void clear()
clear - Remove all entries.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
void push_back(MachineInstr *MI)
This class implements a map that also provides access to all stored values in a deterministic order.
Pass interface - Implemented by all 'passes'.
A discriminated union of two or more pointer types, with the discriminator in the low bits of the poi...
void * getOpaqueValue() const
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
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.
Lightweight class that wraps the location operand metadata of a debug intrinsic.
Implements a dense probed hash-table based set with some number of buckets stored inline.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Target - Wrapper for Target specific information.
bool isPointerTy() const
True if this is an instance of PointerType.
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
UniqueVector - This class produces a sequential ID number (base 1) for each unique entry that is adde...
unsigned insert(const T &Entry)
insert - Append entry to the vector if it doesn't already exist.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
std::pair< iterator, bool > insert(const ValueT &V)
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
self_iterator getIterator()
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
DenseMap< FragmentOfVar, SmallVector< DIExpression::FragmentInfo, 1 > > OverlapMap
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
LLVM_ABI void deleteAll(Function *F)
Remove all Assignment Tracking related intrinsics and metadata from F.
SmallVector< DbgVariableRecord * > getDVRAssignmentMarkers(const Instruction *Inst)
Return a range of dbg_assign records for which Inst performs the assignment they encode.
LLVM_ABI std::optional< AssignmentInfo > getAssignmentInfo(const DataLayout &DL, const MemIntrinsic *I)
LLVM_ABI bool calculateFragmentIntersect(const DataLayout &DL, const Value *Dest, uint64_t SliceOffsetInBits, uint64_t SliceSizeInBits, const DbgVariableRecord *DVRAssign, std::optional< DIExpression::FragmentInfo > &Result)
Calculate the fragment of the variable in DAI covered from (Dest + SliceOffsetInBits) to to (Dest + S...
initializer< Ty > init(const Ty &Val)
@ DW_OP_LLVM_fragment
Only used in LLVM metadata.
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
@ Known
Known to have no common set bits.
DebugVariableAggregate VarID
A unique key that represents one instance of a debug variable.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
auto successors(const MachineBasicBlock *BB)
bool operator!=(uint64_t V1, const APInt &V2)
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
auto reverse(ContainerTy &&C)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI bool isFunctionInPrintList(StringRef FunctionName)
VariableID
Type wrapper for integer ID for Variables. 0 is reserved.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
LLVM_ABI bool isAssignmentTrackingEnabled(const Module &M)
Return true if assignment tracking is enabled for module M.
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
auto predecessors(const MachineBasicBlock *BB)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
@ End
Run the machine verifier once, at the end of the pipeline.
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
bool debuginfoShouldUseDebugInstrRef(const Triple &T)
Implement std::hash so that hash_code can be used in STL containers.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
A special type used by analysis passes to provide an address that identifies that particular analysis...
static bool isEqual(const VariableID &LHS, const VariableID &RHS)
static unsigned getHashValue(const VariableID &Val)
DenseMapInfo< unsigned > Wrapped
An information struct used to provide DenseMap with the various necessary components for a given valu...
Variable location definition used by FunctionVarLocs.
RawLocationWrapper Values
llvm::VariableID VariableID
std::size_t operator()(const VarLocInsertPt &Arg) const