1 //===-- AssignmentTrackingAnalysis.cpp ------------------------------------===// 2 // 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 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h" 10 #include "LiveDebugValues/LiveDebugValues.h" 11 #include "llvm/ADT/BitVector.h" 12 #include "llvm/ADT/DenseMapInfo.h" 13 #include "llvm/ADT/IntervalMap.h" 14 #include "llvm/ADT/PostOrderIterator.h" 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/ADT/Statistic.h" 17 #include "llvm/ADT/UniqueVector.h" 18 #include "llvm/Analysis/Interval.h" 19 #include "llvm/BinaryFormat/Dwarf.h" 20 #include "llvm/IR/BasicBlock.h" 21 #include "llvm/IR/DataLayout.h" 22 #include "llvm/IR/DebugInfo.h" 23 #include "llvm/IR/DebugProgramInstruction.h" 24 #include "llvm/IR/Function.h" 25 #include "llvm/IR/Instruction.h" 26 #include "llvm/IR/IntrinsicInst.h" 27 #include "llvm/IR/PassManager.h" 28 #include "llvm/IR/PrintPasses.h" 29 #include "llvm/InitializePasses.h" 30 #include "llvm/Support/CommandLine.h" 31 #include "llvm/Support/ErrorHandling.h" 32 #include "llvm/Support/raw_ostream.h" 33 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 34 #include <assert.h> 35 #include <cstdint> 36 #include <optional> 37 #include <queue> 38 #include <sstream> 39 #include <unordered_map> 40 41 using namespace llvm; 42 #define DEBUG_TYPE "debug-ata" 43 44 STATISTIC(NumDefsScanned, "Number of dbg locs that get scanned for removal"); 45 STATISTIC(NumDefsRemoved, "Number of dbg locs removed"); 46 STATISTIC(NumWedgesScanned, "Number of dbg wedges scanned"); 47 STATISTIC(NumWedgesChanged, "Number of dbg wedges changed"); 48 49 static cl::opt<unsigned> 50 MaxNumBlocks("debug-ata-max-blocks", cl::init(10000), 51 cl::desc("Maximum num basic blocks before debug info dropped"), 52 cl::Hidden); 53 /// Option for debugging the pass, determines if the memory location fragment 54 /// filling happens after generating the variable locations. 55 static cl::opt<bool> EnableMemLocFragFill("mem-loc-frag-fill", cl::init(true), 56 cl::Hidden); 57 /// Print the results of the analysis. Respects -filter-print-funcs. 58 static cl::opt<bool> PrintResults("print-debug-ata", cl::init(false), 59 cl::Hidden); 60 61 /// Coalesce adjacent dbg locs describing memory locations that have contiguous 62 /// fragments. This reduces the cost of LiveDebugValues which does SSA 63 /// construction for each explicitly stated variable fragment. 64 static cl::opt<cl::boolOrDefault> 65 CoalesceAdjacentFragmentsOpt("debug-ata-coalesce-frags", cl::Hidden); 66 67 // Implicit conversions are disabled for enum class types, so unfortunately we 68 // need to create a DenseMapInfo wrapper around the specified underlying type. 69 template <> struct llvm::DenseMapInfo<VariableID> { 70 using Wrapped = DenseMapInfo<unsigned>; 71 static inline VariableID getEmptyKey() { 72 return static_cast<VariableID>(Wrapped::getEmptyKey()); 73 } 74 static inline VariableID getTombstoneKey() { 75 return static_cast<VariableID>(Wrapped::getTombstoneKey()); 76 } 77 static unsigned getHashValue(const VariableID &Val) { 78 return Wrapped::getHashValue(static_cast<unsigned>(Val)); 79 } 80 static bool isEqual(const VariableID &LHS, const VariableID &RHS) { 81 return LHS == RHS; 82 } 83 }; 84 85 using VarLocInsertPt = PointerUnion<const Instruction *, const DPValue *>; 86 87 namespace std { 88 template <> struct hash<VarLocInsertPt> { 89 using argument_type = VarLocInsertPt; 90 using result_type = std::size_t; 91 92 result_type operator()(const argument_type &Arg) const { 93 return std::hash<void *>()(Arg.getOpaqueValue()); 94 } 95 }; 96 } // namespace std 97 98 /// Helper class to build FunctionVarLocs, since that class isn't easy to 99 /// modify. TODO: There's not a great deal of value in the split, it could be 100 /// worth merging the two classes. 101 class FunctionVarLocsBuilder { 102 friend FunctionVarLocs; 103 UniqueVector<DebugVariable> Variables; 104 // Use an unordered_map so we don't invalidate iterators after 105 // insert/modifications. 106 std::unordered_map<VarLocInsertPt, SmallVector<VarLocInfo>> VarLocsBeforeInst; 107 108 SmallVector<VarLocInfo> SingleLocVars; 109 110 public: 111 unsigned getNumVariables() const { return Variables.size(); } 112 113 /// Find or insert \p V and return the ID. 114 VariableID insertVariable(DebugVariable V) { 115 return static_cast<VariableID>(Variables.insert(V)); 116 } 117 118 /// Get a variable from its \p ID. 119 const DebugVariable &getVariable(VariableID ID) const { 120 return Variables[static_cast<unsigned>(ID)]; 121 } 122 123 /// Return ptr to wedge of defs or nullptr if no defs come just before /p 124 /// Before. 125 const SmallVectorImpl<VarLocInfo> *getWedge(VarLocInsertPt Before) const { 126 auto R = VarLocsBeforeInst.find(Before); 127 if (R == VarLocsBeforeInst.end()) 128 return nullptr; 129 return &R->second; 130 } 131 132 /// Replace the defs that come just before /p Before with /p Wedge. 133 void setWedge(VarLocInsertPt Before, SmallVector<VarLocInfo> &&Wedge) { 134 VarLocsBeforeInst[Before] = std::move(Wedge); 135 } 136 137 /// Add a def for a variable that is valid for its lifetime. 138 void addSingleLocVar(DebugVariable Var, DIExpression *Expr, DebugLoc DL, 139 RawLocationWrapper R) { 140 VarLocInfo VarLoc; 141 VarLoc.VariableID = insertVariable(Var); 142 VarLoc.Expr = Expr; 143 VarLoc.DL = DL; 144 VarLoc.Values = R; 145 SingleLocVars.emplace_back(VarLoc); 146 } 147 148 /// Add a def to the wedge of defs just before /p Before. 149 void addVarLoc(VarLocInsertPt Before, DebugVariable Var, DIExpression *Expr, 150 DebugLoc DL, RawLocationWrapper R) { 151 VarLocInfo VarLoc; 152 VarLoc.VariableID = insertVariable(Var); 153 VarLoc.Expr = Expr; 154 VarLoc.DL = DL; 155 VarLoc.Values = R; 156 VarLocsBeforeInst[Before].emplace_back(VarLoc); 157 } 158 }; 159 160 void FunctionVarLocs::print(raw_ostream &OS, const Function &Fn) const { 161 // Print the variable table first. TODO: Sorting by variable could make the 162 // output more stable? 163 unsigned Counter = -1; 164 OS << "=== Variables ===\n"; 165 for (const DebugVariable &V : Variables) { 166 ++Counter; 167 // Skip first entry because it is a dummy entry. 168 if (Counter == 0) { 169 continue; 170 } 171 OS << "[" << Counter << "] " << V.getVariable()->getName(); 172 if (auto F = V.getFragment()) 173 OS << " bits [" << F->OffsetInBits << ", " 174 << F->OffsetInBits + F->SizeInBits << ")"; 175 if (const auto *IA = V.getInlinedAt()) 176 OS << " inlined-at " << *IA; 177 OS << "\n"; 178 } 179 180 auto PrintLoc = [&OS](const VarLocInfo &Loc) { 181 OS << "DEF Var=[" << (unsigned)Loc.VariableID << "]" 182 << " Expr=" << *Loc.Expr << " Values=("; 183 for (auto *Op : Loc.Values.location_ops()) { 184 errs() << Op->getName() << " "; 185 } 186 errs() << ")\n"; 187 }; 188 189 // Print the single location variables. 190 OS << "=== Single location vars ===\n"; 191 for (auto It = single_locs_begin(), End = single_locs_end(); It != End; 192 ++It) { 193 PrintLoc(*It); 194 } 195 196 // Print the non-single-location defs in line with IR. 197 OS << "=== In-line variable defs ==="; 198 for (const BasicBlock &BB : Fn) { 199 OS << "\n" << BB.getName() << ":\n"; 200 for (const Instruction &I : BB) { 201 for (auto It = locs_begin(&I), End = locs_end(&I); It != End; ++It) { 202 PrintLoc(*It); 203 } 204 OS << I << "\n"; 205 } 206 } 207 } 208 209 void FunctionVarLocs::init(FunctionVarLocsBuilder &Builder) { 210 // Add the single-location variables first. 211 for (const auto &VarLoc : Builder.SingleLocVars) 212 VarLocRecords.emplace_back(VarLoc); 213 // Mark the end of the section. 214 SingleVarLocEnd = VarLocRecords.size(); 215 216 // Insert a contiguous block of VarLocInfos for each instruction, mapping it 217 // to the start and end position in the vector with VarLocsBeforeInst. This 218 // block includes VarLocs for any DPValues attached to that instruction. 219 for (auto &P : Builder.VarLocsBeforeInst) { 220 // Process VarLocs attached to a DPValue alongside their marker Instruction. 221 if (isa<const DPValue *>(P.first)) 222 continue; 223 const Instruction *I = cast<const Instruction *>(P.first); 224 unsigned BlockStart = VarLocRecords.size(); 225 // Any VarLocInfos attached to a DPValue should now be remapped to their 226 // marker Instruction, in order of DPValue appearance and prior to any 227 // VarLocInfos attached directly to that instruction. 228 for (const DPValue &DPV : I->getDbgValueRange()) { 229 // Even though DPV defines a variable location, VarLocsBeforeInst can 230 // still be empty if that VarLoc was redundant. 231 if (!Builder.VarLocsBeforeInst.count(&DPV)) 232 continue; 233 for (const VarLocInfo &VarLoc : Builder.VarLocsBeforeInst[&DPV]) 234 VarLocRecords.emplace_back(VarLoc); 235 } 236 for (const VarLocInfo &VarLoc : P.second) 237 VarLocRecords.emplace_back(VarLoc); 238 unsigned BlockEnd = VarLocRecords.size(); 239 // Record the start and end indices. 240 if (BlockEnd != BlockStart) 241 VarLocsBeforeInst[I] = {BlockStart, BlockEnd}; 242 } 243 244 // Copy the Variables vector from the builder's UniqueVector. 245 assert(Variables.empty() && "Expect clear before init"); 246 // UniqueVectors IDs are one-based (which means the VarLocInfo VarID values 247 // are one-based) so reserve an extra and insert a dummy. 248 Variables.reserve(Builder.Variables.size() + 1); 249 Variables.push_back(DebugVariable(nullptr, std::nullopt, nullptr)); 250 Variables.append(Builder.Variables.begin(), Builder.Variables.end()); 251 } 252 253 void FunctionVarLocs::clear() { 254 Variables.clear(); 255 VarLocRecords.clear(); 256 VarLocsBeforeInst.clear(); 257 SingleVarLocEnd = 0; 258 } 259 260 /// Walk backwards along constant GEPs and bitcasts to the base storage from \p 261 /// Start as far as possible. Prepend \Expression with the offset and append it 262 /// with a DW_OP_deref that haes been implicit until now. Returns the walked-to 263 /// value and modified expression. 264 static std::pair<Value *, DIExpression *> 265 walkToAllocaAndPrependOffsetDeref(const DataLayout &DL, Value *Start, 266 DIExpression *Expression) { 267 APInt OffsetInBytes(DL.getTypeSizeInBits(Start->getType()), false); 268 Value *End = 269 Start->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetInBytes); 270 SmallVector<uint64_t, 3> Ops; 271 if (OffsetInBytes.getBoolValue()) { 272 Ops = {dwarf::DW_OP_plus_uconst, OffsetInBytes.getZExtValue()}; 273 Expression = DIExpression::prependOpcodes( 274 Expression, Ops, /*StackValue=*/false, /*EntryValue=*/false); 275 } 276 Expression = DIExpression::append(Expression, {dwarf::DW_OP_deref}); 277 return {End, Expression}; 278 } 279 280 /// Extract the offset used in \p DIExpr. Returns std::nullopt if the expression 281 /// doesn't explicitly describe a memory location with DW_OP_deref or if the 282 /// expression is too complex to interpret. 283 static std::optional<int64_t> 284 getDerefOffsetInBytes(const DIExpression *DIExpr) { 285 int64_t Offset = 0; 286 const unsigned NumElements = DIExpr->getNumElements(); 287 const auto Elements = DIExpr->getElements(); 288 unsigned ExpectedDerefIdx = 0; 289 // Extract the offset. 290 if (NumElements > 2 && Elements[0] == dwarf::DW_OP_plus_uconst) { 291 Offset = Elements[1]; 292 ExpectedDerefIdx = 2; 293 } else if (NumElements > 3 && Elements[0] == dwarf::DW_OP_constu) { 294 ExpectedDerefIdx = 3; 295 if (Elements[2] == dwarf::DW_OP_plus) 296 Offset = Elements[1]; 297 else if (Elements[2] == dwarf::DW_OP_minus) 298 Offset = -Elements[1]; 299 else 300 return std::nullopt; 301 } 302 303 // If that's all there is it means there's no deref. 304 if (ExpectedDerefIdx >= NumElements) 305 return std::nullopt; 306 307 // Check the next element is DW_OP_deref - otherwise this is too complex or 308 // isn't a deref expression. 309 if (Elements[ExpectedDerefIdx] != dwarf::DW_OP_deref) 310 return std::nullopt; 311 312 // Check the final operation is either the DW_OP_deref or is a fragment. 313 if (NumElements == ExpectedDerefIdx + 1) 314 return Offset; // Ends with deref. 315 unsigned ExpectedFragFirstIdx = ExpectedDerefIdx + 1; 316 unsigned ExpectedFragFinalIdx = ExpectedFragFirstIdx + 2; 317 if (NumElements == ExpectedFragFinalIdx + 1 && 318 Elements[ExpectedFragFirstIdx] == dwarf::DW_OP_LLVM_fragment) 319 return Offset; // Ends with deref + fragment. 320 321 // Don't bother trying to interpret anything more complex. 322 return std::nullopt; 323 } 324 325 /// A whole (unfragmented) source variable. 326 using DebugAggregate = std::pair<const DILocalVariable *, const DILocation *>; 327 static DebugAggregate getAggregate(const DbgVariableIntrinsic *DII) { 328 return DebugAggregate(DII->getVariable(), DII->getDebugLoc().getInlinedAt()); 329 } 330 static DebugAggregate getAggregate(const DebugVariable &Var) { 331 return DebugAggregate(Var.getVariable(), Var.getInlinedAt()); 332 } 333 334 static bool shouldCoalesceFragments(Function &F) { 335 // Enabling fragment coalescing reduces compiler run time when instruction 336 // referencing is enabled. However, it may cause LiveDebugVariables to create 337 // incorrect locations. Since instruction-referencing mode effectively 338 // bypasses LiveDebugVariables we only enable coalescing if the cl::opt flag 339 // has not been explicitly set and instruction-referencing is turned on. 340 switch (CoalesceAdjacentFragmentsOpt) { 341 case cl::boolOrDefault::BOU_UNSET: 342 return debuginfoShouldUseDebugInstrRef( 343 Triple(F.getParent()->getTargetTriple())); 344 case cl::boolOrDefault::BOU_TRUE: 345 return true; 346 case cl::boolOrDefault::BOU_FALSE: 347 return false; 348 } 349 llvm_unreachable("Unknown boolOrDefault value"); 350 } 351 352 namespace { 353 /// In dwarf emission, the following sequence 354 /// 1. dbg.value ... Fragment(0, 64) 355 /// 2. dbg.value ... Fragment(0, 32) 356 /// effectively sets Fragment(32, 32) to undef (each def sets all bits not in 357 /// the intersection of the fragments to having "no location"). This makes 358 /// sense for implicit location values because splitting the computed values 359 /// could be troublesome, and is probably quite uncommon. When we convert 360 /// dbg.assigns to dbg.value+deref this kind of thing is common, and describing 361 /// a location (memory) rather than a value means we don't need to worry about 362 /// splitting any values, so we try to recover the rest of the fragment 363 /// location here. 364 /// This class performs a(nother) dataflow analysis over the function, adding 365 /// variable locations so that any bits of a variable with a memory location 366 /// have that location explicitly reinstated at each subsequent variable 367 /// location definition that that doesn't overwrite those bits. i.e. after a 368 /// variable location def, insert new defs for the memory location with 369 /// fragments for the difference of "all bits currently in memory" and "the 370 /// fragment of the second def". 371 class MemLocFragmentFill { 372 Function &Fn; 373 FunctionVarLocsBuilder *FnVarLocs; 374 const DenseSet<DebugAggregate> *VarsWithStackSlot; 375 bool CoalesceAdjacentFragments; 376 377 // 0 = no memory location. 378 using BaseAddress = unsigned; 379 using OffsetInBitsTy = unsigned; 380 using FragTraits = IntervalMapHalfOpenInfo<OffsetInBitsTy>; 381 using FragsInMemMap = IntervalMap< 382 OffsetInBitsTy, BaseAddress, 383 IntervalMapImpl::NodeSizer<OffsetInBitsTy, BaseAddress>::LeafSize, 384 FragTraits>; 385 FragsInMemMap::Allocator IntervalMapAlloc; 386 using VarFragMap = DenseMap<unsigned, FragsInMemMap>; 387 388 /// IDs for memory location base addresses in maps. Use 0 to indicate that 389 /// there's no memory location. 390 UniqueVector<RawLocationWrapper> Bases; 391 UniqueVector<DebugAggregate> Aggregates; 392 DenseMap<const BasicBlock *, VarFragMap> LiveIn; 393 DenseMap<const BasicBlock *, VarFragMap> LiveOut; 394 395 struct FragMemLoc { 396 unsigned Var; 397 unsigned Base; 398 unsigned OffsetInBits; 399 unsigned SizeInBits; 400 DebugLoc DL; 401 }; 402 using InsertMap = MapVector<VarLocInsertPt, SmallVector<FragMemLoc>>; 403 404 /// BBInsertBeforeMap holds a description for the set of location defs to be 405 /// inserted after the analysis is complete. It is updated during the dataflow 406 /// and the entry for a block is CLEARED each time it is (re-)visited. After 407 /// the dataflow is complete, each block entry will contain the set of defs 408 /// calculated during the final (fixed-point) iteration. 409 DenseMap<const BasicBlock *, InsertMap> BBInsertBeforeMap; 410 411 static bool intervalMapsAreEqual(const FragsInMemMap &A, 412 const FragsInMemMap &B) { 413 auto AIt = A.begin(), AEnd = A.end(); 414 auto BIt = B.begin(), BEnd = B.end(); 415 for (; AIt != AEnd; ++AIt, ++BIt) { 416 if (BIt == BEnd) 417 return false; // B has fewer elements than A. 418 if (AIt.start() != BIt.start() || AIt.stop() != BIt.stop()) 419 return false; // Interval is different. 420 if (*AIt != *BIt) 421 return false; // Value at interval is different. 422 } 423 // AIt == AEnd. Check BIt is also now at end. 424 return BIt == BEnd; 425 } 426 427 static bool varFragMapsAreEqual(const VarFragMap &A, const VarFragMap &B) { 428 if (A.size() != B.size()) 429 return false; 430 for (const auto &APair : A) { 431 auto BIt = B.find(APair.first); 432 if (BIt == B.end()) 433 return false; 434 if (!intervalMapsAreEqual(APair.second, BIt->second)) 435 return false; 436 } 437 return true; 438 } 439 440 /// Return a string for the value that \p BaseID represents. 441 std::string toString(unsigned BaseID) { 442 if (BaseID) 443 return Bases[BaseID].getVariableLocationOp(0)->getName().str(); 444 else 445 return "None"; 446 } 447 448 /// Format string describing an FragsInMemMap (IntervalMap) interval. 449 std::string toString(FragsInMemMap::const_iterator It, bool Newline = true) { 450 std::string String; 451 std::stringstream S(String); 452 if (It.valid()) { 453 S << "[" << It.start() << ", " << It.stop() 454 << "): " << toString(It.value()); 455 } else { 456 S << "invalid iterator (end)"; 457 } 458 if (Newline) 459 S << "\n"; 460 return S.str(); 461 }; 462 463 FragsInMemMap meetFragments(const FragsInMemMap &A, const FragsInMemMap &B) { 464 FragsInMemMap Result(IntervalMapAlloc); 465 for (auto AIt = A.begin(), AEnd = A.end(); AIt != AEnd; ++AIt) { 466 LLVM_DEBUG(dbgs() << "a " << toString(AIt)); 467 // This is basically copied from process() and inverted (process is 468 // performing something like a union whereas this is more of an 469 // intersect). 470 471 // There's no work to do if interval `a` overlaps no fragments in map `B`. 472 if (!B.overlaps(AIt.start(), AIt.stop())) 473 continue; 474 475 // Does StartBit intersect an existing fragment? 476 auto FirstOverlap = B.find(AIt.start()); 477 assert(FirstOverlap != B.end()); 478 bool IntersectStart = FirstOverlap.start() < AIt.start(); 479 LLVM_DEBUG(dbgs() << "- FirstOverlap " << toString(FirstOverlap, false) 480 << ", IntersectStart: " << IntersectStart << "\n"); 481 482 // Does EndBit intersect an existing fragment? 483 auto LastOverlap = B.find(AIt.stop()); 484 bool IntersectEnd = 485 LastOverlap != B.end() && LastOverlap.start() < AIt.stop(); 486 LLVM_DEBUG(dbgs() << "- LastOverlap " << toString(LastOverlap, false) 487 << ", IntersectEnd: " << IntersectEnd << "\n"); 488 489 // Check if both ends of `a` intersect the same interval `b`. 490 if (IntersectStart && IntersectEnd && FirstOverlap == LastOverlap) { 491 // Insert `a` (`a` is contained in `b`) if the values match. 492 // [ a ] 493 // [ - b - ] 494 // - 495 // [ r ] 496 LLVM_DEBUG(dbgs() << "- a is contained within " 497 << toString(FirstOverlap)); 498 if (*AIt && *AIt == *FirstOverlap) 499 Result.insert(AIt.start(), AIt.stop(), *AIt); 500 } else { 501 // There's an overlap but `a` is not fully contained within 502 // `b`. Shorten any end-point intersections. 503 // [ - a - ] 504 // [ - b - ] 505 // - 506 // [ r ] 507 auto Next = FirstOverlap; 508 if (IntersectStart) { 509 LLVM_DEBUG(dbgs() << "- insert intersection of a and " 510 << toString(FirstOverlap)); 511 if (*AIt && *AIt == *FirstOverlap) 512 Result.insert(AIt.start(), FirstOverlap.stop(), *AIt); 513 ++Next; 514 } 515 // [ - a - ] 516 // [ - b - ] 517 // - 518 // [ r ] 519 if (IntersectEnd) { 520 LLVM_DEBUG(dbgs() << "- insert intersection of a and " 521 << toString(LastOverlap)); 522 if (*AIt && *AIt == *LastOverlap) 523 Result.insert(LastOverlap.start(), AIt.stop(), *AIt); 524 } 525 526 // Insert all intervals in map `B` that are contained within interval 527 // `a` where the values match. 528 // [ - - a - - ] 529 // [ b1 ] [ b2 ] 530 // - 531 // [ r1 ] [ r2 ] 532 while (Next != B.end() && Next.start() < AIt.stop() && 533 Next.stop() <= AIt.stop()) { 534 LLVM_DEBUG(dbgs() 535 << "- insert intersection of a and " << toString(Next)); 536 if (*AIt && *AIt == *Next) 537 Result.insert(Next.start(), Next.stop(), *Next); 538 ++Next; 539 } 540 } 541 } 542 return Result; 543 } 544 545 /// Meet \p A and \p B, storing the result in \p A. 546 void meetVars(VarFragMap &A, const VarFragMap &B) { 547 // Meet A and B. 548 // 549 // Result = meet(a, b) for a in A, b in B where Var(a) == Var(b) 550 for (auto It = A.begin(), End = A.end(); It != End; ++It) { 551 unsigned AVar = It->first; 552 FragsInMemMap &AFrags = It->second; 553 auto BIt = B.find(AVar); 554 if (BIt == B.end()) { 555 A.erase(It); 556 continue; // Var has no bits defined in B. 557 } 558 LLVM_DEBUG(dbgs() << "meet fragment maps for " 559 << Aggregates[AVar].first->getName() << "\n"); 560 AFrags = meetFragments(AFrags, BIt->second); 561 } 562 } 563 564 bool meet(const BasicBlock &BB, 565 const SmallPtrSet<BasicBlock *, 16> &Visited) { 566 LLVM_DEBUG(dbgs() << "meet block info from preds of " << BB.getName() 567 << "\n"); 568 569 VarFragMap BBLiveIn; 570 bool FirstMeet = true; 571 // LiveIn locs for BB is the meet of the already-processed preds' LiveOut 572 // locs. 573 for (auto I = pred_begin(&BB), E = pred_end(&BB); I != E; I++) { 574 // Ignore preds that haven't been processed yet. This is essentially the 575 // same as initialising all variables to implicit top value (⊤) which is 576 // the identity value for the meet operation. 577 const BasicBlock *Pred = *I; 578 if (!Visited.count(Pred)) 579 continue; 580 581 auto PredLiveOut = LiveOut.find(Pred); 582 assert(PredLiveOut != LiveOut.end()); 583 584 if (FirstMeet) { 585 LLVM_DEBUG(dbgs() << "BBLiveIn = " << Pred->getName() << "\n"); 586 BBLiveIn = PredLiveOut->second; 587 FirstMeet = false; 588 } else { 589 LLVM_DEBUG(dbgs() << "BBLiveIn = meet BBLiveIn, " << Pred->getName() 590 << "\n"); 591 meetVars(BBLiveIn, PredLiveOut->second); 592 } 593 594 // An empty set is ⊥ for the intersect-like meet operation. If we've 595 // already got ⊥ there's no need to run the code - we know the result is 596 // ⊥ since `meet(a, ⊥) = ⊥`. 597 if (BBLiveIn.size() == 0) 598 break; 599 } 600 601 auto CurrentLiveInEntry = LiveIn.find(&BB); 602 // If there's no LiveIn entry for the block yet, add it. 603 if (CurrentLiveInEntry == LiveIn.end()) { 604 LLVM_DEBUG(dbgs() << "change=true (first) on meet on " << BB.getName() 605 << "\n"); 606 LiveIn[&BB] = std::move(BBLiveIn); 607 return /*Changed=*/true; 608 } 609 610 // If the LiveIn set has changed (expensive check) update it and return 611 // true. 612 if (!varFragMapsAreEqual(BBLiveIn, CurrentLiveInEntry->second)) { 613 LLVM_DEBUG(dbgs() << "change=true on meet on " << BB.getName() << "\n"); 614 CurrentLiveInEntry->second = std::move(BBLiveIn); 615 return /*Changed=*/true; 616 } 617 618 LLVM_DEBUG(dbgs() << "change=false on meet on " << BB.getName() << "\n"); 619 return /*Changed=*/false; 620 } 621 622 void insertMemLoc(BasicBlock &BB, VarLocInsertPt Before, unsigned Var, 623 unsigned StartBit, unsigned EndBit, unsigned Base, 624 DebugLoc DL) { 625 assert(StartBit < EndBit && "Cannot create fragment of size <= 0"); 626 if (!Base) 627 return; 628 FragMemLoc Loc; 629 Loc.Var = Var; 630 Loc.OffsetInBits = StartBit; 631 Loc.SizeInBits = EndBit - StartBit; 632 assert(Base && "Expected a non-zero ID for Base address"); 633 Loc.Base = Base; 634 Loc.DL = DL; 635 BBInsertBeforeMap[&BB][Before].push_back(Loc); 636 LLVM_DEBUG(dbgs() << "Add mem def for " << Aggregates[Var].first->getName() 637 << " bits [" << StartBit << ", " << EndBit << ")\n"); 638 } 639 640 /// Inserts a new dbg def if the interval found when looking up \p StartBit 641 /// in \p FragMap starts before \p StartBit or ends after \p EndBit (which 642 /// indicates - assuming StartBit->EndBit has just been inserted - that the 643 /// slice has been coalesced in the map). 644 void coalesceFragments(BasicBlock &BB, VarLocInsertPt Before, unsigned Var, 645 unsigned StartBit, unsigned EndBit, unsigned Base, 646 DebugLoc DL, const FragsInMemMap &FragMap) { 647 if (!CoalesceAdjacentFragments) 648 return; 649 // We've inserted the location into the map. The map will have coalesced 650 // adjacent intervals (variable fragments) that describe the same memory 651 // location. Use this knowledge to insert a debug location that describes 652 // that coalesced fragment. This may eclipse other locs we've just 653 // inserted. This is okay as redundant locs will be cleaned up later. 654 auto CoalescedFrag = FragMap.find(StartBit); 655 // Bail if no coalescing has taken place. 656 if (CoalescedFrag.start() == StartBit && CoalescedFrag.stop() == EndBit) 657 return; 658 659 LLVM_DEBUG(dbgs() << "- Insert loc for bits " << CoalescedFrag.start() 660 << " to " << CoalescedFrag.stop() << "\n"); 661 insertMemLoc(BB, Before, Var, CoalescedFrag.start(), CoalescedFrag.stop(), 662 Base, DL); 663 } 664 665 void addDef(const VarLocInfo &VarLoc, VarLocInsertPt Before, BasicBlock &BB, 666 VarFragMap &LiveSet) { 667 DebugVariable DbgVar = FnVarLocs->getVariable(VarLoc.VariableID); 668 if (skipVariable(DbgVar.getVariable())) 669 return; 670 // Don't bother doing anything for this variables if we know it's fully 671 // promoted. We're only interested in variables that (sometimes) live on 672 // the stack here. 673 if (!VarsWithStackSlot->count(getAggregate(DbgVar))) 674 return; 675 unsigned Var = Aggregates.insert( 676 DebugAggregate(DbgVar.getVariable(), VarLoc.DL.getInlinedAt())); 677 678 // [StartBit: EndBit) are the bits affected by this def. 679 const DIExpression *DIExpr = VarLoc.Expr; 680 unsigned StartBit; 681 unsigned EndBit; 682 if (auto Frag = DIExpr->getFragmentInfo()) { 683 StartBit = Frag->OffsetInBits; 684 EndBit = StartBit + Frag->SizeInBits; 685 } else { 686 assert(static_cast<bool>(DbgVar.getVariable()->getSizeInBits())); 687 StartBit = 0; 688 EndBit = *DbgVar.getVariable()->getSizeInBits(); 689 } 690 691 // We will only fill fragments for simple memory-describing dbg.value 692 // intrinsics. If the fragment offset is the same as the offset from the 693 // base pointer, do The Thing, otherwise fall back to normal dbg.value 694 // behaviour. AssignmentTrackingLowering has generated DIExpressions 695 // written in terms of the base pointer. 696 // TODO: Remove this condition since the fragment offset doesn't always 697 // equal the offset from base pointer (e.g. for a SROA-split variable). 698 const auto DerefOffsetInBytes = getDerefOffsetInBytes(DIExpr); 699 const unsigned Base = 700 DerefOffsetInBytes && *DerefOffsetInBytes * 8 == StartBit 701 ? Bases.insert(VarLoc.Values) 702 : 0; 703 LLVM_DEBUG(dbgs() << "DEF " << DbgVar.getVariable()->getName() << " [" 704 << StartBit << ", " << EndBit << "): " << toString(Base) 705 << "\n"); 706 707 // First of all, any locs that use mem that are disrupted need reinstating. 708 // Unfortunately, IntervalMap doesn't let us insert intervals that overlap 709 // with existing intervals so this code involves a lot of fiddling around 710 // with intervals to do that manually. 711 auto FragIt = LiveSet.find(Var); 712 713 // Check if the variable does not exist in the map. 714 if (FragIt == LiveSet.end()) { 715 // Add this variable to the BB map. 716 auto P = LiveSet.try_emplace(Var, FragsInMemMap(IntervalMapAlloc)); 717 assert(P.second && "Var already in map?"); 718 // Add the interval to the fragment map. 719 P.first->second.insert(StartBit, EndBit, Base); 720 return; 721 } 722 // The variable has an entry in the map. 723 724 FragsInMemMap &FragMap = FragIt->second; 725 // First check the easy case: the new fragment `f` doesn't overlap with any 726 // intervals. 727 if (!FragMap.overlaps(StartBit, EndBit)) { 728 LLVM_DEBUG(dbgs() << "- No overlaps\n"); 729 FragMap.insert(StartBit, EndBit, Base); 730 coalesceFragments(BB, Before, Var, StartBit, EndBit, Base, VarLoc.DL, 731 FragMap); 732 return; 733 } 734 // There is at least one overlap. 735 736 // Does StartBit intersect an existing fragment? 737 auto FirstOverlap = FragMap.find(StartBit); 738 assert(FirstOverlap != FragMap.end()); 739 bool IntersectStart = FirstOverlap.start() < StartBit; 740 741 // Does EndBit intersect an existing fragment? 742 auto LastOverlap = FragMap.find(EndBit); 743 bool IntersectEnd = LastOverlap.valid() && LastOverlap.start() < EndBit; 744 745 // Check if both ends of `f` intersect the same interval `i`. 746 if (IntersectStart && IntersectEnd && FirstOverlap == LastOverlap) { 747 LLVM_DEBUG(dbgs() << "- Intersect single interval @ both ends\n"); 748 // Shorten `i` so that there's space to insert `f`. 749 // [ f ] 750 // [ - i - ] 751 // + 752 // [ i ][ f ][ i ] 753 754 // Save values for use after inserting a new interval. 755 auto EndBitOfOverlap = FirstOverlap.stop(); 756 unsigned OverlapValue = FirstOverlap.value(); 757 758 // Shorten the overlapping interval. 759 FirstOverlap.setStop(StartBit); 760 insertMemLoc(BB, Before, Var, FirstOverlap.start(), StartBit, 761 OverlapValue, VarLoc.DL); 762 763 // Insert a new interval to represent the end part. 764 FragMap.insert(EndBit, EndBitOfOverlap, OverlapValue); 765 insertMemLoc(BB, Before, Var, EndBit, EndBitOfOverlap, OverlapValue, 766 VarLoc.DL); 767 768 // Insert the new (middle) fragment now there is space. 769 FragMap.insert(StartBit, EndBit, Base); 770 } else { 771 // There's an overlap but `f` may not be fully contained within 772 // `i`. Shorten any end-point intersections so that we can then 773 // insert `f`. 774 // [ - f - ] 775 // [ - i - ] 776 // | | 777 // [ i ] 778 // Shorten any end-point intersections. 779 if (IntersectStart) { 780 LLVM_DEBUG(dbgs() << "- Intersect interval at start\n"); 781 // Split off at the intersection. 782 FirstOverlap.setStop(StartBit); 783 insertMemLoc(BB, Before, Var, FirstOverlap.start(), StartBit, 784 *FirstOverlap, VarLoc.DL); 785 } 786 // [ - f - ] 787 // [ - i - ] 788 // | | 789 // [ i ] 790 if (IntersectEnd) { 791 LLVM_DEBUG(dbgs() << "- Intersect interval at end\n"); 792 // Split off at the intersection. 793 LastOverlap.setStart(EndBit); 794 insertMemLoc(BB, Before, Var, EndBit, LastOverlap.stop(), *LastOverlap, 795 VarLoc.DL); 796 } 797 798 LLVM_DEBUG(dbgs() << "- Erase intervals contained within\n"); 799 // FirstOverlap and LastOverlap have been shortened such that they're 800 // no longer overlapping with [StartBit, EndBit). Delete any overlaps 801 // that remain (these will be fully contained within `f`). 802 // [ - f - ] } 803 // [ - i - ] } Intersection shortening that has happened above. 804 // | | } 805 // [ i ] } 806 // ----------------- 807 // [i2 ] } Intervals fully contained within `f` get erased. 808 // ----------------- 809 // [ - f - ][ i ] } Completed insertion. 810 auto It = FirstOverlap; 811 if (IntersectStart) 812 ++It; // IntersectStart: first overlap has been shortened. 813 while (It.valid() && It.start() >= StartBit && It.stop() <= EndBit) { 814 LLVM_DEBUG(dbgs() << "- Erase " << toString(It)); 815 It.erase(); // This increments It after removing the interval. 816 } 817 // We've dealt with all the overlaps now! 818 assert(!FragMap.overlaps(StartBit, EndBit)); 819 LLVM_DEBUG(dbgs() << "- Insert DEF into now-empty space\n"); 820 FragMap.insert(StartBit, EndBit, Base); 821 } 822 823 coalesceFragments(BB, Before, Var, StartBit, EndBit, Base, VarLoc.DL, 824 FragMap); 825 } 826 827 bool skipVariable(const DILocalVariable *V) { return !V->getSizeInBits(); } 828 829 void process(BasicBlock &BB, VarFragMap &LiveSet) { 830 BBInsertBeforeMap[&BB].clear(); 831 for (auto &I : BB) { 832 if (const auto *Locs = FnVarLocs->getWedge(&I)) { 833 for (const VarLocInfo &Loc : *Locs) { 834 addDef(Loc, &I, *I.getParent(), LiveSet); 835 } 836 } 837 } 838 } 839 840 public: 841 MemLocFragmentFill(Function &Fn, 842 const DenseSet<DebugAggregate> *VarsWithStackSlot, 843 bool CoalesceAdjacentFragments) 844 : Fn(Fn), VarsWithStackSlot(VarsWithStackSlot), 845 CoalesceAdjacentFragments(CoalesceAdjacentFragments) {} 846 847 /// Add variable locations to \p FnVarLocs so that any bits of a variable 848 /// with a memory location have that location explicitly reinstated at each 849 /// subsequent variable location definition that that doesn't overwrite those 850 /// bits. i.e. after a variable location def, insert new defs for the memory 851 /// location with fragments for the difference of "all bits currently in 852 /// memory" and "the fragment of the second def". e.g. 853 /// 854 /// Before: 855 /// 856 /// var x bits 0 to 63: value in memory 857 /// more instructions 858 /// var x bits 0 to 31: value is %0 859 /// 860 /// After: 861 /// 862 /// var x bits 0 to 63: value in memory 863 /// more instructions 864 /// var x bits 0 to 31: value is %0 865 /// var x bits 32 to 61: value in memory ; <-- new loc def 866 /// 867 void run(FunctionVarLocsBuilder *FnVarLocs) { 868 if (!EnableMemLocFragFill) 869 return; 870 871 this->FnVarLocs = FnVarLocs; 872 873 // Prepare for traversal. 874 // 875 ReversePostOrderTraversal<Function *> RPOT(&Fn); 876 std::priority_queue<unsigned int, std::vector<unsigned int>, 877 std::greater<unsigned int>> 878 Worklist; 879 std::priority_queue<unsigned int, std::vector<unsigned int>, 880 std::greater<unsigned int>> 881 Pending; 882 DenseMap<unsigned int, BasicBlock *> OrderToBB; 883 DenseMap<BasicBlock *, unsigned int> BBToOrder; 884 { // Init OrderToBB and BBToOrder. 885 unsigned int RPONumber = 0; 886 for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) { 887 OrderToBB[RPONumber] = *RI; 888 BBToOrder[*RI] = RPONumber; 889 Worklist.push(RPONumber); 890 ++RPONumber; 891 } 892 LiveIn.init(RPONumber); 893 LiveOut.init(RPONumber); 894 } 895 896 // Perform the traversal. 897 // 898 // This is a standard "intersect of predecessor outs" dataflow problem. To 899 // solve it, we perform meet() and process() using the two worklist method 900 // until the LiveIn data for each block becomes unchanging. 901 // 902 // This dataflow is essentially working on maps of sets and at each meet we 903 // intersect the maps and the mapped sets. So, initialized live-in maps 904 // monotonically decrease in value throughout the dataflow. 905 SmallPtrSet<BasicBlock *, 16> Visited; 906 while (!Worklist.empty() || !Pending.empty()) { 907 // We track what is on the pending worklist to avoid inserting the same 908 // thing twice. We could avoid this with a custom priority queue, but 909 // this is probably not worth it. 910 SmallPtrSet<BasicBlock *, 16> OnPending; 911 LLVM_DEBUG(dbgs() << "Processing Worklist\n"); 912 while (!Worklist.empty()) { 913 BasicBlock *BB = OrderToBB[Worklist.top()]; 914 LLVM_DEBUG(dbgs() << "\nPop BB " << BB->getName() << "\n"); 915 Worklist.pop(); 916 bool InChanged = meet(*BB, Visited); 917 // Always consider LiveIn changed on the first visit. 918 InChanged |= Visited.insert(BB).second; 919 if (InChanged) { 920 LLVM_DEBUG(dbgs() 921 << BB->getName() << " has new InLocs, process it\n"); 922 // Mutate a copy of LiveIn while processing BB. Once we've processed 923 // the terminator LiveSet is the LiveOut set for BB. 924 // This is an expensive copy! 925 VarFragMap LiveSet = LiveIn[BB]; 926 927 // Process the instructions in the block. 928 process(*BB, LiveSet); 929 930 // Relatively expensive check: has anything changed in LiveOut for BB? 931 if (!varFragMapsAreEqual(LiveOut[BB], LiveSet)) { 932 LLVM_DEBUG(dbgs() << BB->getName() 933 << " has new OutLocs, add succs to worklist: [ "); 934 LiveOut[BB] = std::move(LiveSet); 935 for (auto I = succ_begin(BB), E = succ_end(BB); I != E; I++) { 936 if (OnPending.insert(*I).second) { 937 LLVM_DEBUG(dbgs() << I->getName() << " "); 938 Pending.push(BBToOrder[*I]); 939 } 940 } 941 LLVM_DEBUG(dbgs() << "]\n"); 942 } 943 } 944 } 945 Worklist.swap(Pending); 946 // At this point, pending must be empty, since it was just the empty 947 // worklist 948 assert(Pending.empty() && "Pending should be empty"); 949 } 950 951 // Insert new location defs. 952 for (auto &Pair : BBInsertBeforeMap) { 953 InsertMap &Map = Pair.second; 954 for (auto &Pair : Map) { 955 auto InsertBefore = Pair.first; 956 assert(InsertBefore && "should never be null"); 957 auto FragMemLocs = Pair.second; 958 auto &Ctx = Fn.getContext(); 959 960 for (auto &FragMemLoc : FragMemLocs) { 961 DIExpression *Expr = DIExpression::get(Ctx, std::nullopt); 962 if (FragMemLoc.SizeInBits != 963 *Aggregates[FragMemLoc.Var].first->getSizeInBits()) 964 Expr = *DIExpression::createFragmentExpression( 965 Expr, FragMemLoc.OffsetInBits, FragMemLoc.SizeInBits); 966 Expr = DIExpression::prepend(Expr, DIExpression::DerefAfter, 967 FragMemLoc.OffsetInBits / 8); 968 DebugVariable Var(Aggregates[FragMemLoc.Var].first, Expr, 969 FragMemLoc.DL.getInlinedAt()); 970 FnVarLocs->addVarLoc(InsertBefore, Var, Expr, FragMemLoc.DL, 971 Bases[FragMemLoc.Base]); 972 } 973 } 974 } 975 } 976 }; 977 978 /// AssignmentTrackingLowering encapsulates a dataflow analysis over a function 979 /// that interprets assignment tracking debug info metadata and stores in IR to 980 /// create a map of variable locations. 981 class AssignmentTrackingLowering { 982 public: 983 /// The kind of location in use for a variable, where Mem is the stack home, 984 /// Val is an SSA value or const, and None means that there is not one single 985 /// kind (either because there are multiple or because there is none; it may 986 /// prove useful to split this into two values in the future). 987 /// 988 /// LocKind is a join-semilattice with the partial order: 989 /// None > Mem, Val 990 /// 991 /// i.e. 992 /// join(Mem, Mem) = Mem 993 /// join(Val, Val) = Val 994 /// join(Mem, Val) = None 995 /// join(None, Mem) = None 996 /// join(None, Val) = None 997 /// join(None, None) = None 998 /// 999 /// Note: the order is not `None > Val > Mem` because we're using DIAssignID 1000 /// to name assignments and are not tracking the actual stored values. 1001 /// Therefore currently there's no way to ensure that Mem values and Val 1002 /// values are the same. This could be a future extension, though it's not 1003 /// clear that many additional locations would be recovered that way in 1004 /// practice as the likelihood of this sitation arising naturally seems 1005 /// incredibly low. 1006 enum class LocKind { Mem, Val, None }; 1007 1008 /// An abstraction of the assignment of a value to a variable or memory 1009 /// location. 1010 /// 1011 /// An Assignment is Known or NoneOrPhi. A Known Assignment means we have a 1012 /// DIAssignID ptr that represents it. NoneOrPhi means that we don't (or 1013 /// can't) know the ID of the last assignment that took place. 1014 /// 1015 /// The Status of the Assignment (Known or NoneOrPhi) is another 1016 /// join-semilattice. The partial order is: 1017 /// NoneOrPhi > Known {id_0, id_1, ...id_N} 1018 /// 1019 /// i.e. for all values x and y where x != y: 1020 /// join(x, x) = x 1021 /// join(x, y) = NoneOrPhi 1022 struct Assignment { 1023 enum S { Known, NoneOrPhi } Status; 1024 /// ID of the assignment. nullptr if Status is not Known. 1025 DIAssignID *ID; 1026 /// The dbg.assign that marks this dbg-def. Mem-defs don't use this field. 1027 /// May be nullptr. 1028 DbgAssignIntrinsic *Source; 1029 1030 bool isSameSourceAssignment(const Assignment &Other) const { 1031 // Don't include Source in the equality check. Assignments are 1032 // defined by their ID, not debug intrinsic(s). 1033 return std::tie(Status, ID) == std::tie(Other.Status, Other.ID); 1034 } 1035 void dump(raw_ostream &OS) { 1036 static const char *LUT[] = {"Known", "NoneOrPhi"}; 1037 OS << LUT[Status] << "(id="; 1038 if (ID) 1039 OS << ID; 1040 else 1041 OS << "null"; 1042 OS << ", s="; 1043 if (Source) 1044 OS << *Source; 1045 else 1046 OS << "null"; 1047 OS << ")"; 1048 } 1049 1050 static Assignment make(DIAssignID *ID, DbgAssignIntrinsic *Source) { 1051 return Assignment(Known, ID, Source); 1052 } 1053 static Assignment makeFromMemDef(DIAssignID *ID) { 1054 return Assignment(Known, ID, nullptr); 1055 } 1056 static Assignment makeNoneOrPhi() { 1057 return Assignment(NoneOrPhi, nullptr, nullptr); 1058 } 1059 // Again, need a Top value? 1060 Assignment() 1061 : Status(NoneOrPhi), ID(nullptr), Source(nullptr) { 1062 } // Can we delete this? 1063 Assignment(S Status, DIAssignID *ID, DbgAssignIntrinsic *Source) 1064 : Status(Status), ID(ID), Source(Source) { 1065 // If the Status is Known then we expect there to be an assignment ID. 1066 assert(Status == NoneOrPhi || ID); 1067 } 1068 }; 1069 1070 using AssignmentMap = SmallVector<Assignment>; 1071 using LocMap = SmallVector<LocKind>; 1072 using OverlapMap = DenseMap<VariableID, SmallVector<VariableID>>; 1073 using UntaggedStoreAssignmentMap = 1074 DenseMap<const Instruction *, 1075 SmallVector<std::pair<VariableID, at::AssignmentInfo>>>; 1076 1077 private: 1078 /// The highest numbered VariableID for partially promoted variables plus 1, 1079 /// the values for which start at 1. 1080 unsigned TrackedVariablesVectorSize = 0; 1081 /// Map a variable to the set of variables that it fully contains. 1082 OverlapMap VarContains; 1083 /// Map untagged stores to the variable fragments they assign to. Used by 1084 /// processUntaggedInstruction. 1085 UntaggedStoreAssignmentMap UntaggedStoreVars; 1086 1087 // Machinery to defer inserting dbg.values. 1088 using InstInsertMap = MapVector<VarLocInsertPt, SmallVector<VarLocInfo>>; 1089 InstInsertMap InsertBeforeMap; 1090 /// Clear the location definitions currently cached for insertion after /p 1091 /// After. 1092 void resetInsertionPoint(Instruction &After); 1093 void resetInsertionPoint(DPValue &After); 1094 void emitDbgValue(LocKind Kind, const DbgVariableIntrinsic *Source, 1095 Instruction *After); 1096 1097 static bool mapsAreEqual(const BitVector &Mask, const AssignmentMap &A, 1098 const AssignmentMap &B) { 1099 return llvm::all_of(Mask.set_bits(), [&](unsigned VarID) { 1100 return A[VarID].isSameSourceAssignment(B[VarID]); 1101 }); 1102 } 1103 1104 /// Represents the stack and debug assignments in a block. Used to describe 1105 /// the live-in and live-out values for blocks, as well as the "current" 1106 /// value as we process each instruction in a block. 1107 struct BlockInfo { 1108 /// The set of variables (VariableID) being tracked in this block. 1109 BitVector VariableIDsInBlock; 1110 /// Dominating assignment to memory for each variable, indexed by 1111 /// VariableID. 1112 AssignmentMap StackHomeValue; 1113 /// Dominating assignemnt to each variable, indexed by VariableID. 1114 AssignmentMap DebugValue; 1115 /// Location kind for each variable. LiveLoc indicates whether the 1116 /// dominating assignment in StackHomeValue (LocKind::Mem), DebugValue 1117 /// (LocKind::Val), or neither (LocKind::None) is valid, in that order of 1118 /// preference. This cannot be derived by inspecting DebugValue and 1119 /// StackHomeValue due to the fact that there's no distinction in 1120 /// Assignment (the class) between whether an assignment is unknown or a 1121 /// merge of multiple assignments (both are Status::NoneOrPhi). In other 1122 /// words, the memory location may well be valid while both DebugValue and 1123 /// StackHomeValue contain Assignments that have a Status of NoneOrPhi. 1124 /// Indexed by VariableID. 1125 LocMap LiveLoc; 1126 1127 public: 1128 enum AssignmentKind { Stack, Debug }; 1129 const AssignmentMap &getAssignmentMap(AssignmentKind Kind) const { 1130 switch (Kind) { 1131 case Stack: 1132 return StackHomeValue; 1133 case Debug: 1134 return DebugValue; 1135 } 1136 llvm_unreachable("Unknown AssignmentKind"); 1137 } 1138 AssignmentMap &getAssignmentMap(AssignmentKind Kind) { 1139 return const_cast<AssignmentMap &>( 1140 const_cast<const BlockInfo *>(this)->getAssignmentMap(Kind)); 1141 } 1142 1143 bool isVariableTracked(VariableID Var) const { 1144 return VariableIDsInBlock[static_cast<unsigned>(Var)]; 1145 } 1146 1147 const Assignment &getAssignment(AssignmentKind Kind, VariableID Var) const { 1148 assert(isVariableTracked(Var) && "Var not tracked in block"); 1149 return getAssignmentMap(Kind)[static_cast<unsigned>(Var)]; 1150 } 1151 1152 LocKind getLocKind(VariableID Var) const { 1153 assert(isVariableTracked(Var) && "Var not tracked in block"); 1154 return LiveLoc[static_cast<unsigned>(Var)]; 1155 } 1156 1157 /// Set LocKind for \p Var only: does not set LocKind for VariableIDs of 1158 /// fragments contained win \p Var. 1159 void setLocKind(VariableID Var, LocKind K) { 1160 VariableIDsInBlock.set(static_cast<unsigned>(Var)); 1161 LiveLoc[static_cast<unsigned>(Var)] = K; 1162 } 1163 1164 /// Set the assignment in the \p Kind assignment map for \p Var only: does 1165 /// not set the assignment for VariableIDs of fragments contained win \p 1166 /// Var. 1167 void setAssignment(AssignmentKind Kind, VariableID Var, 1168 const Assignment &AV) { 1169 VariableIDsInBlock.set(static_cast<unsigned>(Var)); 1170 getAssignmentMap(Kind)[static_cast<unsigned>(Var)] = AV; 1171 } 1172 1173 /// Return true if there is an assignment matching \p AV in the \p Kind 1174 /// assignment map. Does consider assignments for VariableIDs of fragments 1175 /// contained win \p Var. 1176 bool hasAssignment(AssignmentKind Kind, VariableID Var, 1177 const Assignment &AV) const { 1178 if (!isVariableTracked(Var)) 1179 return false; 1180 return AV.isSameSourceAssignment(getAssignment(Kind, Var)); 1181 } 1182 1183 /// Compare every element in each map to determine structural equality 1184 /// (slow). 1185 bool operator==(const BlockInfo &Other) const { 1186 return VariableIDsInBlock == Other.VariableIDsInBlock && 1187 LiveLoc == Other.LiveLoc && 1188 mapsAreEqual(VariableIDsInBlock, StackHomeValue, 1189 Other.StackHomeValue) && 1190 mapsAreEqual(VariableIDsInBlock, DebugValue, Other.DebugValue); 1191 } 1192 bool operator!=(const BlockInfo &Other) const { return !(*this == Other); } 1193 bool isValid() { 1194 return LiveLoc.size() == DebugValue.size() && 1195 LiveLoc.size() == StackHomeValue.size(); 1196 } 1197 1198 /// Clear everything and initialise with ⊤-values for all variables. 1199 void init(int NumVars) { 1200 StackHomeValue.clear(); 1201 DebugValue.clear(); 1202 LiveLoc.clear(); 1203 VariableIDsInBlock = BitVector(NumVars); 1204 StackHomeValue.insert(StackHomeValue.begin(), NumVars, 1205 Assignment::makeNoneOrPhi()); 1206 DebugValue.insert(DebugValue.begin(), NumVars, 1207 Assignment::makeNoneOrPhi()); 1208 LiveLoc.insert(LiveLoc.begin(), NumVars, LocKind::None); 1209 } 1210 1211 /// Helper for join. 1212 template <typename ElmtType, typename FnInputType> 1213 static void joinElmt(int Index, SmallVector<ElmtType> &Target, 1214 const SmallVector<ElmtType> &A, 1215 const SmallVector<ElmtType> &B, 1216 ElmtType (*Fn)(FnInputType, FnInputType)) { 1217 Target[Index] = Fn(A[Index], B[Index]); 1218 } 1219 1220 /// See comment for AssignmentTrackingLowering::joinBlockInfo. 1221 static BlockInfo join(const BlockInfo &A, const BlockInfo &B, int NumVars) { 1222 // Join A and B. 1223 // 1224 // Intersect = join(a, b) for a in A, b in B where Var(a) == Var(b) 1225 // Difference = join(x, ⊤) for x where Var(x) is in A xor B 1226 // Join = Intersect ∪ Difference 1227 // 1228 // This is achieved by performing a join on elements from A and B with 1229 // variables common to both A and B (join elements indexed by var 1230 // intersect), then adding ⊤-value elements for vars in A xor B. The 1231 // latter part is equivalent to performing join on elements with variables 1232 // in A xor B with the ⊤-value for the map element since join(x, ⊤) = ⊤. 1233 // BlockInfo::init initializes all variable entries to the ⊤ value so we 1234 // don't need to explicitly perform that step as Join.VariableIDsInBlock 1235 // is set to the union of the variables in A and B at the end of this 1236 // function. 1237 BlockInfo Join; 1238 Join.init(NumVars); 1239 1240 BitVector Intersect = A.VariableIDsInBlock; 1241 Intersect &= B.VariableIDsInBlock; 1242 1243 for (auto VarID : Intersect.set_bits()) { 1244 joinElmt(VarID, Join.LiveLoc, A.LiveLoc, B.LiveLoc, joinKind); 1245 joinElmt(VarID, Join.DebugValue, A.DebugValue, B.DebugValue, 1246 joinAssignment); 1247 joinElmt(VarID, Join.StackHomeValue, A.StackHomeValue, B.StackHomeValue, 1248 joinAssignment); 1249 } 1250 1251 Join.VariableIDsInBlock = A.VariableIDsInBlock; 1252 Join.VariableIDsInBlock |= B.VariableIDsInBlock; 1253 assert(Join.isValid()); 1254 return Join; 1255 } 1256 }; 1257 1258 Function &Fn; 1259 const DataLayout &Layout; 1260 const DenseSet<DebugAggregate> *VarsWithStackSlot; 1261 FunctionVarLocsBuilder *FnVarLocs; 1262 DenseMap<const BasicBlock *, BlockInfo> LiveIn; 1263 DenseMap<const BasicBlock *, BlockInfo> LiveOut; 1264 1265 /// Helper for process methods to track variables touched each frame. 1266 DenseSet<VariableID> VarsTouchedThisFrame; 1267 1268 /// The set of variables that sometimes are not located in their stack home. 1269 DenseSet<DebugAggregate> NotAlwaysStackHomed; 1270 1271 VariableID getVariableID(const DebugVariable &Var) { 1272 return static_cast<VariableID>(FnVarLocs->insertVariable(Var)); 1273 } 1274 1275 /// Join the LiveOut values of preds that are contained in \p Visited into 1276 /// LiveIn[BB]. Return True if LiveIn[BB] has changed as a result. LiveIn[BB] 1277 /// values monotonically increase. See the @link joinMethods join methods 1278 /// @endlink documentation for more info. 1279 bool join(const BasicBlock &BB, const SmallPtrSet<BasicBlock *, 16> &Visited); 1280 ///@name joinMethods 1281 /// Functions that implement `join` (the least upper bound) for the 1282 /// join-semilattice types used in the dataflow. There is an explicit bottom 1283 /// value (⊥) for some types and and explicit top value (⊤) for all types. 1284 /// By definition: 1285 /// 1286 /// Join(A, B) >= A && Join(A, B) >= B 1287 /// Join(A, ⊥) = A 1288 /// Join(A, ⊤) = ⊤ 1289 /// 1290 /// These invariants are important for monotonicity. 1291 /// 1292 /// For the map-type functions, all unmapped keys in an empty map are 1293 /// associated with a bottom value (⊥). This represents their values being 1294 /// unknown. Unmapped keys in non-empty maps (joining two maps with a key 1295 /// only present in one) represents either a variable going out of scope or 1296 /// dropped debug info. It is assumed the key is associated with a top value 1297 /// (⊤) in this case (unknown location / assignment). 1298 ///@{ 1299 static LocKind joinKind(LocKind A, LocKind B); 1300 static Assignment joinAssignment(const Assignment &A, const Assignment &B); 1301 BlockInfo joinBlockInfo(const BlockInfo &A, const BlockInfo &B); 1302 ///@} 1303 1304 /// Process the instructions in \p BB updating \p LiveSet along the way. \p 1305 /// LiveSet must be initialized with the current live-in locations before 1306 /// calling this. 1307 void process(BasicBlock &BB, BlockInfo *LiveSet); 1308 ///@name processMethods 1309 /// Methods to process instructions in order to update the LiveSet (current 1310 /// location information). 1311 ///@{ 1312 void processNonDbgInstruction(Instruction &I, BlockInfo *LiveSet); 1313 void processDbgInstruction(DbgInfoIntrinsic &I, BlockInfo *LiveSet); 1314 /// Update \p LiveSet after encountering an instruction with a DIAssignID 1315 /// attachment, \p I. 1316 void processTaggedInstruction(Instruction &I, BlockInfo *LiveSet); 1317 /// Update \p LiveSet after encountering an instruciton without a DIAssignID 1318 /// attachment, \p I. 1319 void processUntaggedInstruction(Instruction &I, BlockInfo *LiveSet); 1320 void processDbgAssign(DbgAssignIntrinsic &DAI, BlockInfo *LiveSet); 1321 void processDbgValue(DbgValueInst &DVI, BlockInfo *LiveSet); 1322 /// Add an assignment to memory for the variable /p Var. 1323 void addMemDef(BlockInfo *LiveSet, VariableID Var, const Assignment &AV); 1324 /// Add an assignment to the variable /p Var. 1325 void addDbgDef(BlockInfo *LiveSet, VariableID Var, const Assignment &AV); 1326 ///@} 1327 1328 /// Set the LocKind for \p Var. 1329 void setLocKind(BlockInfo *LiveSet, VariableID Var, LocKind K); 1330 /// Get the live LocKind for a \p Var. Requires addMemDef or addDbgDef to 1331 /// have been called for \p Var first. 1332 LocKind getLocKind(BlockInfo *LiveSet, VariableID Var); 1333 /// Return true if \p Var has an assignment in \p M matching \p AV. 1334 bool hasVarWithAssignment(BlockInfo *LiveSet, BlockInfo::AssignmentKind Kind, 1335 VariableID Var, const Assignment &AV); 1336 /// Return the set of VariableIDs corresponding the fragments contained fully 1337 /// within the variable/fragment \p Var. 1338 ArrayRef<VariableID> getContainedFragments(VariableID Var) const; 1339 1340 /// Mark \p Var as having been touched this frame. Note, this applies only 1341 /// to the exact fragment \p Var and not to any fragments contained within. 1342 void touchFragment(VariableID Var); 1343 1344 /// Emit info for variables that are fully promoted. 1345 bool emitPromotedVarLocs(FunctionVarLocsBuilder *FnVarLocs); 1346 1347 public: 1348 AssignmentTrackingLowering(Function &Fn, const DataLayout &Layout, 1349 const DenseSet<DebugAggregate> *VarsWithStackSlot) 1350 : Fn(Fn), Layout(Layout), VarsWithStackSlot(VarsWithStackSlot) {} 1351 /// Run the analysis, adding variable location info to \p FnVarLocs. Returns 1352 /// true if any variable locations have been added to FnVarLocs. 1353 bool run(FunctionVarLocsBuilder *FnVarLocs); 1354 }; 1355 } // namespace 1356 1357 ArrayRef<VariableID> 1358 AssignmentTrackingLowering::getContainedFragments(VariableID Var) const { 1359 auto R = VarContains.find(Var); 1360 if (R == VarContains.end()) 1361 return std::nullopt; 1362 return R->second; 1363 } 1364 1365 void AssignmentTrackingLowering::touchFragment(VariableID Var) { 1366 VarsTouchedThisFrame.insert(Var); 1367 } 1368 1369 void AssignmentTrackingLowering::setLocKind(BlockInfo *LiveSet, VariableID Var, 1370 LocKind K) { 1371 auto SetKind = [this](BlockInfo *LiveSet, VariableID Var, LocKind K) { 1372 LiveSet->setLocKind(Var, K); 1373 touchFragment(Var); 1374 }; 1375 SetKind(LiveSet, Var, K); 1376 1377 // Update the LocKind for all fragments contained within Var. 1378 for (VariableID Frag : getContainedFragments(Var)) 1379 SetKind(LiveSet, Frag, K); 1380 } 1381 1382 AssignmentTrackingLowering::LocKind 1383 AssignmentTrackingLowering::getLocKind(BlockInfo *LiveSet, VariableID Var) { 1384 return LiveSet->getLocKind(Var); 1385 } 1386 1387 void AssignmentTrackingLowering::addMemDef(BlockInfo *LiveSet, VariableID Var, 1388 const Assignment &AV) { 1389 LiveSet->setAssignment(BlockInfo::Stack, Var, AV); 1390 1391 // Use this assigment for all fragments contained within Var, but do not 1392 // provide a Source because we cannot convert Var's value to a value for the 1393 // fragment. 1394 Assignment FragAV = AV; 1395 FragAV.Source = nullptr; 1396 for (VariableID Frag : getContainedFragments(Var)) 1397 LiveSet->setAssignment(BlockInfo::Stack, Frag, FragAV); 1398 } 1399 1400 void AssignmentTrackingLowering::addDbgDef(BlockInfo *LiveSet, VariableID Var, 1401 const Assignment &AV) { 1402 LiveSet->setAssignment(BlockInfo::Debug, Var, AV); 1403 1404 // Use this assigment for all fragments contained within Var, but do not 1405 // provide a Source because we cannot convert Var's value to a value for the 1406 // fragment. 1407 Assignment FragAV = AV; 1408 FragAV.Source = nullptr; 1409 for (VariableID Frag : getContainedFragments(Var)) 1410 LiveSet->setAssignment(BlockInfo::Debug, Frag, FragAV); 1411 } 1412 1413 static DIAssignID *getIDFromInst(const Instruction &I) { 1414 return cast<DIAssignID>(I.getMetadata(LLVMContext::MD_DIAssignID)); 1415 } 1416 1417 static DIAssignID *getIDFromMarker(const DbgAssignIntrinsic &DAI) { 1418 return cast<DIAssignID>(DAI.getAssignID()); 1419 } 1420 1421 /// Return true if \p Var has an assignment in \p M matching \p AV. 1422 bool AssignmentTrackingLowering::hasVarWithAssignment( 1423 BlockInfo *LiveSet, BlockInfo::AssignmentKind Kind, VariableID Var, 1424 const Assignment &AV) { 1425 if (!LiveSet->hasAssignment(Kind, Var, AV)) 1426 return false; 1427 1428 // Check all the frags contained within Var as these will have all been 1429 // mapped to AV at the last store to Var. 1430 for (VariableID Frag : getContainedFragments(Var)) 1431 if (!LiveSet->hasAssignment(Kind, Frag, AV)) 1432 return false; 1433 return true; 1434 } 1435 1436 #ifndef NDEBUG 1437 const char *locStr(AssignmentTrackingLowering::LocKind Loc) { 1438 using LocKind = AssignmentTrackingLowering::LocKind; 1439 switch (Loc) { 1440 case LocKind::Val: 1441 return "Val"; 1442 case LocKind::Mem: 1443 return "Mem"; 1444 case LocKind::None: 1445 return "None"; 1446 }; 1447 llvm_unreachable("unknown LocKind"); 1448 } 1449 #endif 1450 1451 VarLocInsertPt getNextNode(const DPValue *DPV) { 1452 auto NextIt = ++(DPV->getIterator()); 1453 if (NextIt == DPV->getMarker()->getDbgValueRange().end()) 1454 return DPV->getMarker()->MarkedInstr; 1455 return &*NextIt; 1456 } 1457 VarLocInsertPt getNextNode(const Instruction *Inst) { 1458 const Instruction *Next = Inst->getNextNode(); 1459 if (!Next->hasDbgValues()) 1460 return Next; 1461 return &*Next->getDbgValueRange().begin(); 1462 } 1463 VarLocInsertPt getNextNode(VarLocInsertPt InsertPt) { 1464 if (isa<const Instruction *>(InsertPt)) 1465 return getNextNode(cast<const Instruction *>(InsertPt)); 1466 return getNextNode(cast<const DPValue *>(InsertPt)); 1467 } 1468 1469 void AssignmentTrackingLowering::emitDbgValue( 1470 AssignmentTrackingLowering::LocKind Kind, 1471 const DbgVariableIntrinsic *Source, Instruction *After) { 1472 1473 DILocation *DL = Source->getDebugLoc(); 1474 auto Emit = [this, Source, After, DL](Metadata *Val, DIExpression *Expr) { 1475 assert(Expr); 1476 if (!Val) 1477 Val = ValueAsMetadata::get( 1478 PoisonValue::get(Type::getInt1Ty(Source->getContext()))); 1479 1480 // Find a suitable insert point. 1481 auto InsertBefore = getNextNode(After); 1482 assert(InsertBefore && "Shouldn't be inserting after a terminator"); 1483 1484 VariableID Var = getVariableID(DebugVariable(Source)); 1485 VarLocInfo VarLoc; 1486 VarLoc.VariableID = static_cast<VariableID>(Var); 1487 VarLoc.Expr = Expr; 1488 VarLoc.Values = RawLocationWrapper(Val); 1489 VarLoc.DL = DL; 1490 // Insert it into the map for later. 1491 InsertBeforeMap[InsertBefore].push_back(VarLoc); 1492 }; 1493 1494 // NOTE: This block can mutate Kind. 1495 if (Kind == LocKind::Mem) { 1496 const auto *DAI = cast<DbgAssignIntrinsic>(Source); 1497 // Check the address hasn't been dropped (e.g. the debug uses may not have 1498 // been replaced before deleting a Value). 1499 if (DAI->isKillAddress()) { 1500 // The address isn't valid so treat this as a non-memory def. 1501 Kind = LocKind::Val; 1502 } else { 1503 Value *Val = DAI->getAddress(); 1504 DIExpression *Expr = DAI->getAddressExpression(); 1505 assert(!Expr->getFragmentInfo() && 1506 "fragment info should be stored in value-expression only"); 1507 // Copy the fragment info over from the value-expression to the new 1508 // DIExpression. 1509 if (auto OptFragInfo = Source->getExpression()->getFragmentInfo()) { 1510 auto FragInfo = *OptFragInfo; 1511 Expr = *DIExpression::createFragmentExpression( 1512 Expr, FragInfo.OffsetInBits, FragInfo.SizeInBits); 1513 } 1514 // The address-expression has an implicit deref, add it now. 1515 std::tie(Val, Expr) = 1516 walkToAllocaAndPrependOffsetDeref(Layout, Val, Expr); 1517 Emit(ValueAsMetadata::get(Val), Expr); 1518 return; 1519 } 1520 } 1521 1522 if (Kind == LocKind::Val) { 1523 Emit(Source->getRawLocation(), Source->getExpression()); 1524 return; 1525 } 1526 1527 if (Kind == LocKind::None) { 1528 Emit(nullptr, Source->getExpression()); 1529 return; 1530 } 1531 } 1532 1533 void AssignmentTrackingLowering::processNonDbgInstruction( 1534 Instruction &I, AssignmentTrackingLowering::BlockInfo *LiveSet) { 1535 if (I.hasMetadata(LLVMContext::MD_DIAssignID)) 1536 processTaggedInstruction(I, LiveSet); 1537 else 1538 processUntaggedInstruction(I, LiveSet); 1539 } 1540 1541 void AssignmentTrackingLowering::processUntaggedInstruction( 1542 Instruction &I, AssignmentTrackingLowering::BlockInfo *LiveSet) { 1543 // Interpret stack stores that are not tagged as an assignment in memory for 1544 // the variables associated with that address. These stores may not be tagged 1545 // because a) the store cannot be represented using dbg.assigns (non-const 1546 // length or offset) or b) the tag was accidentally dropped during 1547 // optimisations. For these stores we fall back to assuming that the stack 1548 // home is a valid location for the variables. The benefit is that this 1549 // prevents us missing an assignment and therefore incorrectly maintaining 1550 // earlier location definitions, and in many cases it should be a reasonable 1551 // assumption. However, this will occasionally lead to slight 1552 // inaccuracies. The value of a hoisted untagged store will be visible 1553 // "early", for example. 1554 assert(!I.hasMetadata(LLVMContext::MD_DIAssignID)); 1555 auto It = UntaggedStoreVars.find(&I); 1556 if (It == UntaggedStoreVars.end()) 1557 return; // No variables associated with the store destination. 1558 1559 LLVM_DEBUG(dbgs() << "processUntaggedInstruction on UNTAGGED INST " << I 1560 << "\n"); 1561 // Iterate over the variables that this store affects, add a NoneOrPhi dbg 1562 // and mem def, set lockind to Mem, and emit a location def for each. 1563 for (auto [Var, Info] : It->second) { 1564 // This instruction is treated as both a debug and memory assignment, 1565 // meaning the memory location should be used. We don't have an assignment 1566 // ID though so use Assignment::makeNoneOrPhi() to create an imaginary one. 1567 addMemDef(LiveSet, Var, Assignment::makeNoneOrPhi()); 1568 addDbgDef(LiveSet, Var, Assignment::makeNoneOrPhi()); 1569 setLocKind(LiveSet, Var, LocKind::Mem); 1570 LLVM_DEBUG(dbgs() << " setting Stack LocKind to: " << locStr(LocKind::Mem) 1571 << "\n"); 1572 // Build the dbg location def to insert. 1573 // 1574 // DIExpression: Add fragment and offset. 1575 DebugVariable V = FnVarLocs->getVariable(Var); 1576 DIExpression *DIE = DIExpression::get(I.getContext(), std::nullopt); 1577 if (auto Frag = V.getFragment()) { 1578 auto R = DIExpression::createFragmentExpression(DIE, Frag->OffsetInBits, 1579 Frag->SizeInBits); 1580 assert(R && "unexpected createFragmentExpression failure"); 1581 DIE = *R; 1582 } 1583 SmallVector<uint64_t, 3> Ops; 1584 if (Info.OffsetInBits) 1585 Ops = {dwarf::DW_OP_plus_uconst, Info.OffsetInBits / 8}; 1586 Ops.push_back(dwarf::DW_OP_deref); 1587 DIE = DIExpression::prependOpcodes(DIE, Ops, /*StackValue=*/false, 1588 /*EntryValue=*/false); 1589 // Find a suitable insert point, before the next instruction or DPValue 1590 // after I. 1591 auto InsertBefore = getNextNode(&I); 1592 assert(InsertBefore && "Shouldn't be inserting after a terminator"); 1593 1594 // Get DILocation for this unrecorded assignment. 1595 DILocation *InlinedAt = const_cast<DILocation *>(V.getInlinedAt()); 1596 const DILocation *DILoc = DILocation::get( 1597 Fn.getContext(), 0, 0, V.getVariable()->getScope(), InlinedAt); 1598 1599 VarLocInfo VarLoc; 1600 VarLoc.VariableID = static_cast<VariableID>(Var); 1601 VarLoc.Expr = DIE; 1602 VarLoc.Values = RawLocationWrapper( 1603 ValueAsMetadata::get(const_cast<AllocaInst *>(Info.Base))); 1604 VarLoc.DL = DILoc; 1605 // 3. Insert it into the map for later. 1606 InsertBeforeMap[InsertBefore].push_back(VarLoc); 1607 } 1608 } 1609 1610 void AssignmentTrackingLowering::processTaggedInstruction( 1611 Instruction &I, AssignmentTrackingLowering::BlockInfo *LiveSet) { 1612 auto Linked = at::getAssignmentMarkers(&I); 1613 // No dbg.assign intrinsics linked. 1614 // FIXME: All vars that have a stack slot this store modifies that don't have 1615 // a dbg.assign linked to it should probably treat this like an untagged 1616 // store. 1617 if (Linked.empty()) 1618 return; 1619 1620 LLVM_DEBUG(dbgs() << "processTaggedInstruction on " << I << "\n"); 1621 for (DbgAssignIntrinsic *DAI : Linked) { 1622 VariableID Var = getVariableID(DebugVariable(DAI)); 1623 // Something has gone wrong if VarsWithStackSlot doesn't contain a variable 1624 // that is linked to a store. 1625 assert(VarsWithStackSlot->count(getAggregate(DAI)) && 1626 "expected DAI's variable to have stack slot"); 1627 1628 Assignment AV = Assignment::makeFromMemDef(getIDFromInst(I)); 1629 addMemDef(LiveSet, Var, AV); 1630 1631 LLVM_DEBUG(dbgs() << " linked to " << *DAI << "\n"); 1632 LLVM_DEBUG(dbgs() << " LiveLoc " << locStr(getLocKind(LiveSet, Var)) 1633 << " -> "); 1634 1635 // The last assignment to the stack is now AV. Check if the last debug 1636 // assignment has a matching Assignment. 1637 if (hasVarWithAssignment(LiveSet, BlockInfo::Debug, Var, AV)) { 1638 // The StackHomeValue and DebugValue for this variable match so we can 1639 // emit a stack home location here. 1640 LLVM_DEBUG(dbgs() << "Mem, Stack matches Debug program\n";); 1641 LLVM_DEBUG(dbgs() << " Stack val: "; AV.dump(dbgs()); dbgs() << "\n"); 1642 LLVM_DEBUG(dbgs() << " Debug val: "; 1643 LiveSet->DebugValue[static_cast<unsigned>(Var)].dump(dbgs()); 1644 dbgs() << "\n"); 1645 setLocKind(LiveSet, Var, LocKind::Mem); 1646 emitDbgValue(LocKind::Mem, DAI, &I); 1647 continue; 1648 } 1649 1650 // The StackHomeValue and DebugValue for this variable do not match. I.e. 1651 // The value currently stored in the stack is not what we'd expect to 1652 // see, so we cannot use emit a stack home location here. Now we will 1653 // look at the live LocKind for the variable and determine an appropriate 1654 // dbg.value to emit. 1655 LocKind PrevLoc = getLocKind(LiveSet, Var); 1656 switch (PrevLoc) { 1657 case LocKind::Val: { 1658 // The value in memory in memory has changed but we're not currently 1659 // using the memory location. Do nothing. 1660 LLVM_DEBUG(dbgs() << "Val, (unchanged)\n";); 1661 setLocKind(LiveSet, Var, LocKind::Val); 1662 } break; 1663 case LocKind::Mem: { 1664 // There's been an assignment to memory that we were using as a 1665 // location for this variable, and the Assignment doesn't match what 1666 // we'd expect to see in memory. 1667 Assignment DbgAV = LiveSet->getAssignment(BlockInfo::Debug, Var); 1668 if (DbgAV.Status == Assignment::NoneOrPhi) { 1669 // We need to terminate any previously open location now. 1670 LLVM_DEBUG(dbgs() << "None, No Debug value available\n";); 1671 setLocKind(LiveSet, Var, LocKind::None); 1672 emitDbgValue(LocKind::None, DAI, &I); 1673 } else { 1674 // The previous DebugValue Value can be used here. 1675 LLVM_DEBUG(dbgs() << "Val, Debug value is Known\n";); 1676 setLocKind(LiveSet, Var, LocKind::Val); 1677 if (DbgAV.Source) { 1678 emitDbgValue(LocKind::Val, DbgAV.Source, &I); 1679 } else { 1680 // PrevAV.Source is nullptr so we must emit undef here. 1681 emitDbgValue(LocKind::None, DAI, &I); 1682 } 1683 } 1684 } break; 1685 case LocKind::None: { 1686 // There's been an assignment to memory and we currently are 1687 // not tracking a location for the variable. Do not emit anything. 1688 LLVM_DEBUG(dbgs() << "None, (unchanged)\n";); 1689 setLocKind(LiveSet, Var, LocKind::None); 1690 } break; 1691 } 1692 } 1693 } 1694 1695 void AssignmentTrackingLowering::processDbgAssign(DbgAssignIntrinsic &DAI, 1696 BlockInfo *LiveSet) { 1697 // Only bother tracking variables that are at some point stack homed. Other 1698 // variables can be dealt with trivially later. 1699 if (!VarsWithStackSlot->count(getAggregate(&DAI))) 1700 return; 1701 1702 VariableID Var = getVariableID(DebugVariable(&DAI)); 1703 Assignment AV = Assignment::make(getIDFromMarker(DAI), &DAI); 1704 addDbgDef(LiveSet, Var, AV); 1705 1706 LLVM_DEBUG(dbgs() << "processDbgAssign on " << DAI << "\n";); 1707 LLVM_DEBUG(dbgs() << " LiveLoc " << locStr(getLocKind(LiveSet, Var)) 1708 << " -> "); 1709 1710 // Check if the DebugValue and StackHomeValue both hold the same 1711 // Assignment. 1712 if (hasVarWithAssignment(LiveSet, BlockInfo::Stack, Var, AV)) { 1713 // They match. We can use the stack home because the debug intrinsics state 1714 // that an assignment happened here, and we know that specific assignment 1715 // was the last one to take place in memory for this variable. 1716 LocKind Kind; 1717 if (DAI.isKillAddress()) { 1718 LLVM_DEBUG( 1719 dbgs() 1720 << "Val, Stack matches Debug program but address is killed\n";); 1721 Kind = LocKind::Val; 1722 } else { 1723 LLVM_DEBUG(dbgs() << "Mem, Stack matches Debug program\n";); 1724 Kind = LocKind::Mem; 1725 }; 1726 setLocKind(LiveSet, Var, Kind); 1727 emitDbgValue(Kind, &DAI, &DAI); 1728 } else { 1729 // The last assignment to the memory location isn't the one that we want to 1730 // show to the user so emit a dbg.value(Value). Value may be undef. 1731 LLVM_DEBUG(dbgs() << "Val, Stack contents is unknown\n";); 1732 setLocKind(LiveSet, Var, LocKind::Val); 1733 emitDbgValue(LocKind::Val, &DAI, &DAI); 1734 } 1735 } 1736 1737 void AssignmentTrackingLowering::processDbgValue(DbgValueInst &DVI, 1738 BlockInfo *LiveSet) { 1739 // Only other tracking variables that are at some point stack homed. 1740 // Other variables can be dealt with trivally later. 1741 if (!VarsWithStackSlot->count(getAggregate(&DVI))) 1742 return; 1743 1744 VariableID Var = getVariableID(DebugVariable(&DVI)); 1745 // We have no ID to create an Assignment with so we mark this assignment as 1746 // NoneOrPhi. Note that the dbg.value still exists, we just cannot determine 1747 // the assignment responsible for setting this value. 1748 // This is fine; dbg.values are essentially interchangable with unlinked 1749 // dbg.assigns, and some passes such as mem2reg and instcombine add them to 1750 // PHIs for promoted variables. 1751 Assignment AV = Assignment::makeNoneOrPhi(); 1752 addDbgDef(LiveSet, Var, AV); 1753 1754 LLVM_DEBUG(dbgs() << "processDbgValue on " << DVI << "\n";); 1755 LLVM_DEBUG(dbgs() << " LiveLoc " << locStr(getLocKind(LiveSet, Var)) 1756 << " -> Val, dbg.value override"); 1757 1758 setLocKind(LiveSet, Var, LocKind::Val); 1759 emitDbgValue(LocKind::Val, &DVI, &DVI); 1760 } 1761 1762 template <typename T> static bool hasZeroSizedFragment(T &DbgValue) { 1763 if (auto F = DbgValue.getExpression()->getFragmentInfo()) 1764 return F->SizeInBits == 0; 1765 return false; 1766 } 1767 1768 void AssignmentTrackingLowering::processDbgInstruction( 1769 DbgInfoIntrinsic &I, AssignmentTrackingLowering::BlockInfo *LiveSet) { 1770 auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I); 1771 if (!DVI) 1772 return; 1773 1774 // Ignore assignments to zero bits of the variable. 1775 if (hasZeroSizedFragment(*DVI)) 1776 return; 1777 1778 if (auto *DAI = dyn_cast<DbgAssignIntrinsic>(&I)) 1779 processDbgAssign(*DAI, LiveSet); 1780 else if (auto *DVI = dyn_cast<DbgValueInst>(&I)) 1781 processDbgValue(*DVI, LiveSet); 1782 } 1783 1784 void AssignmentTrackingLowering::resetInsertionPoint(Instruction &After) { 1785 assert(!After.isTerminator() && "Can't insert after a terminator"); 1786 auto R = InsertBeforeMap.find(After.getNextNode()); 1787 if (R == InsertBeforeMap.end()) 1788 return; 1789 R->second.clear(); 1790 } 1791 1792 void AssignmentTrackingLowering::process(BasicBlock &BB, BlockInfo *LiveSet) { 1793 for (auto II = BB.begin(), EI = BB.end(); II != EI;) { 1794 assert(VarsTouchedThisFrame.empty()); 1795 // Process the instructions in "frames". A "frame" includes a single 1796 // non-debug instruction followed any debug instructions before the 1797 // next non-debug instruction. 1798 if (!isa<DbgInfoIntrinsic>(&*II)) { 1799 if (II->isTerminator()) 1800 break; 1801 resetInsertionPoint(*II); 1802 processNonDbgInstruction(*II, LiveSet); 1803 assert(LiveSet->isValid()); 1804 ++II; 1805 } 1806 while (II != EI) { 1807 auto *Dbg = dyn_cast<DbgInfoIntrinsic>(&*II); 1808 if (!Dbg) 1809 break; 1810 resetInsertionPoint(*II); 1811 processDbgInstruction(*Dbg, LiveSet); 1812 assert(LiveSet->isValid()); 1813 ++II; 1814 } 1815 1816 // We've processed everything in the "frame". Now determine which variables 1817 // cannot be represented by a dbg.declare. 1818 for (auto Var : VarsTouchedThisFrame) { 1819 LocKind Loc = getLocKind(LiveSet, Var); 1820 // If a variable's LocKind is anything other than LocKind::Mem then we 1821 // must note that it cannot be represented with a dbg.declare. 1822 // Note that this check is enough without having to check the result of 1823 // joins() because for join to produce anything other than Mem after 1824 // we've already seen a Mem we'd be joining None or Val with Mem. In that 1825 // case, we've already hit this codepath when we set the LocKind to Val 1826 // or None in that block. 1827 if (Loc != LocKind::Mem) { 1828 DebugVariable DbgVar = FnVarLocs->getVariable(Var); 1829 DebugAggregate Aggr{DbgVar.getVariable(), DbgVar.getInlinedAt()}; 1830 NotAlwaysStackHomed.insert(Aggr); 1831 } 1832 } 1833 VarsTouchedThisFrame.clear(); 1834 } 1835 } 1836 1837 AssignmentTrackingLowering::LocKind 1838 AssignmentTrackingLowering::joinKind(LocKind A, LocKind B) { 1839 // Partial order: 1840 // None > Mem, Val 1841 return A == B ? A : LocKind::None; 1842 } 1843 1844 AssignmentTrackingLowering::Assignment 1845 AssignmentTrackingLowering::joinAssignment(const Assignment &A, 1846 const Assignment &B) { 1847 // Partial order: 1848 // NoneOrPhi(null, null) > Known(v, ?s) 1849 1850 // If either are NoneOrPhi the join is NoneOrPhi. 1851 // If either value is different then the result is 1852 // NoneOrPhi (joining two values is a Phi). 1853 if (!A.isSameSourceAssignment(B)) 1854 return Assignment::makeNoneOrPhi(); 1855 if (A.Status == Assignment::NoneOrPhi) 1856 return Assignment::makeNoneOrPhi(); 1857 1858 // Source is used to lookup the value + expression in the debug program if 1859 // the stack slot gets assigned a value earlier than expected. Because 1860 // we're only tracking the one dbg.assign, we can't capture debug PHIs. 1861 // It's unlikely that we're losing out on much coverage by avoiding that 1862 // extra work. 1863 // The Source may differ in this situation: 1864 // Pred.1: 1865 // dbg.assign i32 0, ..., !1, ... 1866 // Pred.2: 1867 // dbg.assign i32 1, ..., !1, ... 1868 // Here the same assignment (!1) was performed in both preds in the source, 1869 // but we can't use either one unless they are identical (e.g. .we don't 1870 // want to arbitrarily pick between constant values). 1871 auto JoinSource = [&]() -> DbgAssignIntrinsic * { 1872 if (A.Source == B.Source) 1873 return A.Source; 1874 if (A.Source == nullptr || B.Source == nullptr) 1875 return nullptr; 1876 if (A.Source->isIdenticalTo(B.Source)) 1877 return A.Source; 1878 return nullptr; 1879 }; 1880 DbgAssignIntrinsic *Source = JoinSource(); 1881 assert(A.Status == B.Status && A.Status == Assignment::Known); 1882 assert(A.ID == B.ID); 1883 return Assignment::make(A.ID, Source); 1884 } 1885 1886 AssignmentTrackingLowering::BlockInfo 1887 AssignmentTrackingLowering::joinBlockInfo(const BlockInfo &A, 1888 const BlockInfo &B) { 1889 return BlockInfo::join(A, B, TrackedVariablesVectorSize); 1890 } 1891 1892 bool AssignmentTrackingLowering::join( 1893 const BasicBlock &BB, const SmallPtrSet<BasicBlock *, 16> &Visited) { 1894 1895 SmallVector<const BasicBlock *> VisitedPreds; 1896 // Ignore backedges if we have not visited the predecessor yet. As the 1897 // predecessor hasn't yet had locations propagated into it, most locations 1898 // will not yet be valid, so treat them as all being uninitialized and 1899 // potentially valid. If a location guessed to be correct here is 1900 // invalidated later, we will remove it when we revisit this block. This 1901 // is essentially the same as initialising all LocKinds and Assignments to 1902 // an implicit ⊥ value which is the identity value for the join operation. 1903 for (const BasicBlock *Pred : predecessors(&BB)) { 1904 if (Visited.count(Pred)) 1905 VisitedPreds.push_back(Pred); 1906 } 1907 1908 // No preds visited yet. 1909 if (VisitedPreds.empty()) { 1910 auto It = LiveIn.try_emplace(&BB, BlockInfo()); 1911 bool DidInsert = It.second; 1912 if (DidInsert) 1913 It.first->second.init(TrackedVariablesVectorSize); 1914 return /*Changed*/ DidInsert; 1915 } 1916 1917 // Exactly one visited pred. Copy the LiveOut from that pred into BB LiveIn. 1918 if (VisitedPreds.size() == 1) { 1919 const BlockInfo &PredLiveOut = LiveOut.find(VisitedPreds[0])->second; 1920 auto CurrentLiveInEntry = LiveIn.find(&BB); 1921 1922 // Check if there isn't an entry, or there is but the LiveIn set has 1923 // changed (expensive check). 1924 if (CurrentLiveInEntry == LiveIn.end()) 1925 LiveIn.insert(std::make_pair(&BB, PredLiveOut)); 1926 else if (PredLiveOut != CurrentLiveInEntry->second) 1927 CurrentLiveInEntry->second = PredLiveOut; 1928 else 1929 return /*Changed*/ false; 1930 return /*Changed*/ true; 1931 } 1932 1933 // More than one pred. Join LiveOuts of blocks 1 and 2. 1934 assert(VisitedPreds.size() > 1); 1935 const BlockInfo &PredLiveOut0 = LiveOut.find(VisitedPreds[0])->second; 1936 const BlockInfo &PredLiveOut1 = LiveOut.find(VisitedPreds[1])->second; 1937 BlockInfo BBLiveIn = joinBlockInfo(PredLiveOut0, PredLiveOut1); 1938 1939 // Join the LiveOuts of subsequent blocks. 1940 ArrayRef Tail = ArrayRef(VisitedPreds).drop_front(2); 1941 for (const BasicBlock *Pred : Tail) { 1942 const auto &PredLiveOut = LiveOut.find(Pred); 1943 assert(PredLiveOut != LiveOut.end() && 1944 "block should have been processed already"); 1945 BBLiveIn = joinBlockInfo(std::move(BBLiveIn), PredLiveOut->second); 1946 } 1947 1948 // Save the joined result for BB. 1949 auto CurrentLiveInEntry = LiveIn.find(&BB); 1950 // Check if there isn't an entry, or there is but the LiveIn set has changed 1951 // (expensive check). 1952 if (CurrentLiveInEntry == LiveIn.end()) 1953 LiveIn.try_emplace(&BB, std::move(BBLiveIn)); 1954 else if (BBLiveIn != CurrentLiveInEntry->second) 1955 CurrentLiveInEntry->second = std::move(BBLiveIn); 1956 else 1957 return /*Changed*/ false; 1958 return /*Changed*/ true; 1959 } 1960 1961 /// Return true if A fully contains B. 1962 static bool fullyContains(DIExpression::FragmentInfo A, 1963 DIExpression::FragmentInfo B) { 1964 auto ALeft = A.OffsetInBits; 1965 auto BLeft = B.OffsetInBits; 1966 if (BLeft < ALeft) 1967 return false; 1968 1969 auto ARight = ALeft + A.SizeInBits; 1970 auto BRight = BLeft + B.SizeInBits; 1971 if (BRight > ARight) 1972 return false; 1973 return true; 1974 } 1975 1976 static std::optional<at::AssignmentInfo> 1977 getUntaggedStoreAssignmentInfo(const Instruction &I, const DataLayout &Layout) { 1978 // Don't bother checking if this is an AllocaInst. We know this 1979 // instruction has no tag which means there are no variables associated 1980 // with it. 1981 if (const auto *SI = dyn_cast<StoreInst>(&I)) 1982 return at::getAssignmentInfo(Layout, SI); 1983 if (const auto *MI = dyn_cast<MemIntrinsic>(&I)) 1984 return at::getAssignmentInfo(Layout, MI); 1985 // Alloca or non-store-like inst. 1986 return std::nullopt; 1987 } 1988 1989 /// Build a map of {Variable x: Variables y} where all variable fragments 1990 /// contained within the variable fragment x are in set y. This means that 1991 /// y does not contain all overlaps because partial overlaps are excluded. 1992 /// 1993 /// While we're iterating over the function, add single location defs for 1994 /// dbg.declares to \p FnVarLocs. 1995 /// 1996 /// Variables that are interesting to this pass in are added to 1997 /// FnVarLocs->Variables first. TrackedVariablesVectorSize is set to the ID of 1998 /// the last interesting variable plus 1, meaning variables with ID 1 1999 /// (inclusive) to TrackedVariablesVectorSize (exclusive) are interesting. The 2000 /// subsequent variables are either stack homed or fully promoted. 2001 /// 2002 /// Finally, populate UntaggedStoreVars with a mapping of untagged stores to 2003 /// the stored-to variable fragments. 2004 /// 2005 /// These tasks are bundled together to reduce the number of times we need 2006 /// to iterate over the function as they can be achieved together in one pass. 2007 static AssignmentTrackingLowering::OverlapMap buildOverlapMapAndRecordDeclares( 2008 Function &Fn, FunctionVarLocsBuilder *FnVarLocs, 2009 const DenseSet<DebugAggregate> &VarsWithStackSlot, 2010 AssignmentTrackingLowering::UntaggedStoreAssignmentMap &UntaggedStoreVars, 2011 unsigned &TrackedVariablesVectorSize) { 2012 DenseSet<DebugVariable> Seen; 2013 // Map of Variable: [Fragments]. 2014 DenseMap<DebugAggregate, SmallVector<DebugVariable, 8>> FragmentMap; 2015 // Iterate over all instructions: 2016 // - dbg.declare -> add single location variable record 2017 // - dbg.* -> Add fragments to FragmentMap 2018 // - untagged store -> Add fragments to FragmentMap and update 2019 // UntaggedStoreVars. 2020 // We need to add fragments for untagged stores too so that we can correctly 2021 // clobber overlapped fragment locations later. 2022 SmallVector<DbgDeclareInst *> Declares; 2023 for (auto &BB : Fn) { 2024 for (auto &I : BB) { 2025 if (auto *DDI = dyn_cast<DbgDeclareInst>(&I)) { 2026 Declares.push_back(DDI); 2027 } else if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) { 2028 DebugVariable DV = DebugVariable(DII); 2029 DebugAggregate DA = {DV.getVariable(), DV.getInlinedAt()}; 2030 if (!VarsWithStackSlot.contains(DA)) 2031 continue; 2032 if (Seen.insert(DV).second) 2033 FragmentMap[DA].push_back(DV); 2034 } else if (auto Info = getUntaggedStoreAssignmentInfo( 2035 I, Fn.getParent()->getDataLayout())) { 2036 // Find markers linked to this alloca. 2037 for (DbgAssignIntrinsic *DAI : at::getAssignmentMarkers(Info->Base)) { 2038 std::optional<DIExpression::FragmentInfo> FragInfo; 2039 2040 // Skip this assignment if the affected bits are outside of the 2041 // variable fragment. 2042 if (!at::calculateFragmentIntersect( 2043 I.getModule()->getDataLayout(), Info->Base, 2044 Info->OffsetInBits, Info->SizeInBits, DAI, FragInfo) || 2045 (FragInfo && FragInfo->SizeInBits == 0)) 2046 continue; 2047 2048 // FragInfo from calculateFragmentIntersect is nullopt if the 2049 // resultant fragment matches DAI's fragment or entire variable - in 2050 // which case copy the fragment info from DAI. If FragInfo is still 2051 // nullopt after the copy it means "no fragment info" instead, which 2052 // is how it is usually interpreted. 2053 if (!FragInfo) 2054 FragInfo = DAI->getExpression()->getFragmentInfo(); 2055 2056 DebugVariable DV = DebugVariable(DAI->getVariable(), FragInfo, 2057 DAI->getDebugLoc().getInlinedAt()); 2058 DebugAggregate DA = {DV.getVariable(), DV.getInlinedAt()}; 2059 if (!VarsWithStackSlot.contains(DA)) 2060 continue; 2061 2062 // Cache this info for later. 2063 UntaggedStoreVars[&I].push_back( 2064 {FnVarLocs->insertVariable(DV), *Info}); 2065 2066 if (Seen.insert(DV).second) 2067 FragmentMap[DA].push_back(DV); 2068 } 2069 } 2070 } 2071 } 2072 2073 // Sort the fragment map for each DebugAggregate in ascending 2074 // order of fragment size - there should be no duplicates. 2075 for (auto &Pair : FragmentMap) { 2076 SmallVector<DebugVariable, 8> &Frags = Pair.second; 2077 std::sort(Frags.begin(), Frags.end(), 2078 [](const DebugVariable &Next, const DebugVariable &Elmt) { 2079 return Elmt.getFragmentOrDefault().SizeInBits > 2080 Next.getFragmentOrDefault().SizeInBits; 2081 }); 2082 // Check for duplicates. 2083 assert(std::adjacent_find(Frags.begin(), Frags.end()) == Frags.end()); 2084 } 2085 2086 // Build the map. 2087 AssignmentTrackingLowering::OverlapMap Map; 2088 for (auto &Pair : FragmentMap) { 2089 auto &Frags = Pair.second; 2090 for (auto It = Frags.begin(), IEnd = Frags.end(); It != IEnd; ++It) { 2091 DIExpression::FragmentInfo Frag = It->getFragmentOrDefault(); 2092 // Find the frags that this is contained within. 2093 // 2094 // Because Frags is sorted by size and none have the same offset and 2095 // size, we know that this frag can only be contained by subsequent 2096 // elements. 2097 SmallVector<DebugVariable, 8>::iterator OtherIt = It; 2098 ++OtherIt; 2099 VariableID ThisVar = FnVarLocs->insertVariable(*It); 2100 for (; OtherIt != IEnd; ++OtherIt) { 2101 DIExpression::FragmentInfo OtherFrag = OtherIt->getFragmentOrDefault(); 2102 VariableID OtherVar = FnVarLocs->insertVariable(*OtherIt); 2103 if (fullyContains(OtherFrag, Frag)) 2104 Map[OtherVar].push_back(ThisVar); 2105 } 2106 } 2107 } 2108 2109 // VariableIDs are 1-based so the variable-tracking bitvector needs 2110 // NumVariables plus 1 bits. 2111 TrackedVariablesVectorSize = FnVarLocs->getNumVariables() + 1; 2112 2113 // Finally, insert the declares afterwards, so the first IDs are all 2114 // partially stack homed vars. 2115 for (auto *DDI : Declares) 2116 FnVarLocs->addSingleLocVar(DebugVariable(DDI), DDI->getExpression(), 2117 DDI->getDebugLoc(), DDI->getWrappedLocation()); 2118 return Map; 2119 } 2120 2121 bool AssignmentTrackingLowering::run(FunctionVarLocsBuilder *FnVarLocsBuilder) { 2122 if (Fn.size() > MaxNumBlocks) { 2123 LLVM_DEBUG(dbgs() << "[AT] Dropping var locs in: " << Fn.getName() 2124 << ": too many blocks (" << Fn.size() << ")\n"); 2125 at::deleteAll(&Fn); 2126 return false; 2127 } 2128 2129 FnVarLocs = FnVarLocsBuilder; 2130 2131 // The general structure here is inspired by VarLocBasedImpl.cpp 2132 // (LiveDebugValues). 2133 2134 // Build the variable fragment overlap map. 2135 // Note that this pass doesn't handle partial overlaps correctly (FWIW 2136 // neither does LiveDebugVariables) because that is difficult to do and 2137 // appears to be rare occurance. 2138 VarContains = buildOverlapMapAndRecordDeclares( 2139 Fn, FnVarLocs, *VarsWithStackSlot, UntaggedStoreVars, 2140 TrackedVariablesVectorSize); 2141 2142 // Prepare for traversal. 2143 ReversePostOrderTraversal<Function *> RPOT(&Fn); 2144 std::priority_queue<unsigned int, std::vector<unsigned int>, 2145 std::greater<unsigned int>> 2146 Worklist; 2147 std::priority_queue<unsigned int, std::vector<unsigned int>, 2148 std::greater<unsigned int>> 2149 Pending; 2150 DenseMap<unsigned int, BasicBlock *> OrderToBB; 2151 DenseMap<BasicBlock *, unsigned int> BBToOrder; 2152 { // Init OrderToBB and BBToOrder. 2153 unsigned int RPONumber = 0; 2154 for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) { 2155 OrderToBB[RPONumber] = *RI; 2156 BBToOrder[*RI] = RPONumber; 2157 Worklist.push(RPONumber); 2158 ++RPONumber; 2159 } 2160 LiveIn.init(RPONumber); 2161 LiveOut.init(RPONumber); 2162 } 2163 2164 // Perform the traversal. 2165 // 2166 // This is a standard "union of predecessor outs" dataflow problem. To solve 2167 // it, we perform join() and process() using the two worklist method until 2168 // the LiveIn data for each block becomes unchanging. The "proof" that this 2169 // terminates can be put together by looking at the comments around LocKind, 2170 // Assignment, and the various join methods, which show that all the elements 2171 // involved are made up of join-semilattices; LiveIn(n) can only 2172 // monotonically increase in value throughout the dataflow. 2173 // 2174 SmallPtrSet<BasicBlock *, 16> Visited; 2175 while (!Worklist.empty()) { 2176 // We track what is on the pending worklist to avoid inserting the same 2177 // thing twice. 2178 SmallPtrSet<BasicBlock *, 16> OnPending; 2179 LLVM_DEBUG(dbgs() << "Processing Worklist\n"); 2180 while (!Worklist.empty()) { 2181 BasicBlock *BB = OrderToBB[Worklist.top()]; 2182 LLVM_DEBUG(dbgs() << "\nPop BB " << BB->getName() << "\n"); 2183 Worklist.pop(); 2184 bool InChanged = join(*BB, Visited); 2185 // Always consider LiveIn changed on the first visit. 2186 InChanged |= Visited.insert(BB).second; 2187 if (InChanged) { 2188 LLVM_DEBUG(dbgs() << BB->getName() << " has new InLocs, process it\n"); 2189 // Mutate a copy of LiveIn while processing BB. After calling process 2190 // LiveSet is the LiveOut set for BB. 2191 BlockInfo LiveSet = LiveIn[BB]; 2192 2193 // Process the instructions in the block. 2194 process(*BB, &LiveSet); 2195 2196 // Relatively expensive check: has anything changed in LiveOut for BB? 2197 if (LiveOut[BB] != LiveSet) { 2198 LLVM_DEBUG(dbgs() << BB->getName() 2199 << " has new OutLocs, add succs to worklist: [ "); 2200 LiveOut[BB] = std::move(LiveSet); 2201 for (auto I = succ_begin(BB), E = succ_end(BB); I != E; I++) { 2202 if (OnPending.insert(*I).second) { 2203 LLVM_DEBUG(dbgs() << I->getName() << " "); 2204 Pending.push(BBToOrder[*I]); 2205 } 2206 } 2207 LLVM_DEBUG(dbgs() << "]\n"); 2208 } 2209 } 2210 } 2211 Worklist.swap(Pending); 2212 // At this point, pending must be empty, since it was just the empty 2213 // worklist 2214 assert(Pending.empty() && "Pending should be empty"); 2215 } 2216 2217 // That's the hard part over. Now we just have some admin to do. 2218 2219 // Record whether we inserted any intrinsics. 2220 bool InsertedAnyIntrinsics = false; 2221 2222 // Identify and add defs for single location variables. 2223 // 2224 // Go through all of the defs that we plan to add. If the aggregate variable 2225 // it's a part of is not in the NotAlwaysStackHomed set we can emit a single 2226 // location def and omit the rest. Add an entry to AlwaysStackHomed so that 2227 // we can identify those uneeded defs later. 2228 DenseSet<DebugAggregate> AlwaysStackHomed; 2229 for (const auto &Pair : InsertBeforeMap) { 2230 const auto &Vec = Pair.second; 2231 for (VarLocInfo VarLoc : Vec) { 2232 DebugVariable Var = FnVarLocs->getVariable(VarLoc.VariableID); 2233 DebugAggregate Aggr{Var.getVariable(), Var.getInlinedAt()}; 2234 2235 // Skip this Var if it's not always stack homed. 2236 if (NotAlwaysStackHomed.contains(Aggr)) 2237 continue; 2238 2239 // Skip complex cases such as when different fragments of a variable have 2240 // been split into different allocas. Skipping in this case means falling 2241 // back to using a list of defs (which could reduce coverage, but is no 2242 // less correct). 2243 bool Simple = 2244 VarLoc.Expr->getNumElements() == 1 && VarLoc.Expr->startsWithDeref(); 2245 if (!Simple) { 2246 NotAlwaysStackHomed.insert(Aggr); 2247 continue; 2248 } 2249 2250 // All source assignments to this variable remain and all stores to any 2251 // part of the variable store to the same address (with varying 2252 // offsets). We can just emit a single location for the whole variable. 2253 // 2254 // Unless we've already done so, create the single location def now. 2255 if (AlwaysStackHomed.insert(Aggr).second) { 2256 assert(!VarLoc.Values.hasArgList()); 2257 // TODO: When more complex cases are handled VarLoc.Expr should be 2258 // built appropriately rather than always using an empty DIExpression. 2259 // The assert below is a reminder. 2260 assert(Simple); 2261 VarLoc.Expr = DIExpression::get(Fn.getContext(), std::nullopt); 2262 DebugVariable Var = FnVarLocs->getVariable(VarLoc.VariableID); 2263 FnVarLocs->addSingleLocVar(Var, VarLoc.Expr, VarLoc.DL, VarLoc.Values); 2264 InsertedAnyIntrinsics = true; 2265 } 2266 } 2267 } 2268 2269 // Insert the other DEFs. 2270 for (const auto &[InsertBefore, Vec] : InsertBeforeMap) { 2271 SmallVector<VarLocInfo> NewDefs; 2272 for (const VarLocInfo &VarLoc : Vec) { 2273 DebugVariable Var = FnVarLocs->getVariable(VarLoc.VariableID); 2274 DebugAggregate Aggr{Var.getVariable(), Var.getInlinedAt()}; 2275 // If this variable is always stack homed then we have already inserted a 2276 // dbg.declare and deleted this dbg.value. 2277 if (AlwaysStackHomed.contains(Aggr)) 2278 continue; 2279 NewDefs.push_back(VarLoc); 2280 InsertedAnyIntrinsics = true; 2281 } 2282 2283 FnVarLocs->setWedge(InsertBefore, std::move(NewDefs)); 2284 } 2285 2286 InsertedAnyIntrinsics |= emitPromotedVarLocs(FnVarLocs); 2287 2288 return InsertedAnyIntrinsics; 2289 } 2290 2291 bool AssignmentTrackingLowering::emitPromotedVarLocs( 2292 FunctionVarLocsBuilder *FnVarLocs) { 2293 bool InsertedAnyIntrinsics = false; 2294 // Go through every block, translating debug intrinsics for fully promoted 2295 // variables into FnVarLocs location defs. No analysis required for these. 2296 for (auto &BB : Fn) { 2297 for (auto &I : BB) { 2298 // Skip instructions other than dbg.values and dbg.assigns. 2299 auto *DVI = dyn_cast<DbgValueInst>(&I); 2300 if (!DVI) 2301 continue; 2302 // Skip variables that haven't been promoted - we've dealt with those 2303 // already. 2304 if (VarsWithStackSlot->contains(getAggregate(DVI))) 2305 continue; 2306 Instruction *InsertBefore = I.getNextNode(); 2307 assert(InsertBefore && "Unexpected: debug intrinsics after a terminator"); 2308 FnVarLocs->addVarLoc(InsertBefore, DebugVariable(DVI), 2309 DVI->getExpression(), DVI->getDebugLoc(), 2310 DVI->getWrappedLocation()); 2311 InsertedAnyIntrinsics = true; 2312 } 2313 } 2314 return InsertedAnyIntrinsics; 2315 } 2316 2317 /// Remove redundant definitions within sequences of consecutive location defs. 2318 /// This is done using a backward scan to keep the last def describing a 2319 /// specific variable/fragment. 2320 /// 2321 /// This implements removeRedundantDbgInstrsUsingBackwardScan from 2322 /// lib/Transforms/Utils/BasicBlockUtils.cpp for locations described with 2323 /// FunctionVarLocsBuilder instead of with intrinsics. 2324 static bool 2325 removeRedundantDbgLocsUsingBackwardScan(const BasicBlock *BB, 2326 FunctionVarLocsBuilder &FnVarLocs) { 2327 bool Changed = false; 2328 SmallDenseMap<DebugAggregate, BitVector> VariableDefinedBytes; 2329 // Scan over the entire block, not just over the instructions mapped by 2330 // FnVarLocs, because wedges in FnVarLocs may only be seperated by debug 2331 // instructions. 2332 for (const Instruction &I : reverse(*BB)) { 2333 if (!isa<DbgVariableIntrinsic>(I)) { 2334 // Sequence of consecutive defs ended. Clear map for the next one. 2335 VariableDefinedBytes.clear(); 2336 } 2337 2338 // Get the location defs that start just before this instruction. 2339 const auto *Locs = FnVarLocs.getWedge(&I); 2340 if (!Locs) 2341 continue; 2342 2343 NumWedgesScanned++; 2344 bool ChangedThisWedge = false; 2345 // The new pruned set of defs, reversed because we're scanning backwards. 2346 SmallVector<VarLocInfo> NewDefsReversed; 2347 2348 // Iterate over the existing defs in reverse. 2349 for (auto RIt = Locs->rbegin(), REnd = Locs->rend(); RIt != REnd; ++RIt) { 2350 NumDefsScanned++; 2351 DebugAggregate Aggr = 2352 getAggregate(FnVarLocs.getVariable(RIt->VariableID)); 2353 uint64_t SizeInBits = Aggr.first->getSizeInBits().value_or(0); 2354 uint64_t SizeInBytes = divideCeil(SizeInBits, 8); 2355 2356 // Cutoff for large variables to prevent expensive bitvector operations. 2357 const uint64_t MaxSizeBytes = 2048; 2358 2359 if (SizeInBytes == 0 || SizeInBytes > MaxSizeBytes) { 2360 // If the size is unknown (0) then keep this location def to be safe. 2361 // Do the same for defs of large variables, which would be expensive 2362 // to represent with a BitVector. 2363 NewDefsReversed.push_back(*RIt); 2364 continue; 2365 } 2366 2367 // Only keep this location definition if it is not fully eclipsed by 2368 // other definitions in this wedge that come after it 2369 2370 // Inert the bytes the location definition defines. 2371 auto InsertResult = 2372 VariableDefinedBytes.try_emplace(Aggr, BitVector(SizeInBytes)); 2373 bool FirstDefinition = InsertResult.second; 2374 BitVector &DefinedBytes = InsertResult.first->second; 2375 2376 DIExpression::FragmentInfo Fragment = 2377 RIt->Expr->getFragmentInfo().value_or( 2378 DIExpression::FragmentInfo(SizeInBits, 0)); 2379 bool InvalidFragment = Fragment.endInBits() > SizeInBits; 2380 uint64_t StartInBytes = Fragment.startInBits() / 8; 2381 uint64_t EndInBytes = divideCeil(Fragment.endInBits(), 8); 2382 2383 // If this defines any previously undefined bytes, keep it. 2384 if (FirstDefinition || InvalidFragment || 2385 DefinedBytes.find_first_unset_in(StartInBytes, EndInBytes) != -1) { 2386 if (!InvalidFragment) 2387 DefinedBytes.set(StartInBytes, EndInBytes); 2388 NewDefsReversed.push_back(*RIt); 2389 continue; 2390 } 2391 2392 // Redundant def found: throw it away. Since the wedge of defs is being 2393 // rebuilt, doing nothing is the same as deleting an entry. 2394 ChangedThisWedge = true; 2395 NumDefsRemoved++; 2396 } 2397 2398 // Un-reverse the defs and replace the wedge with the pruned version. 2399 if (ChangedThisWedge) { 2400 std::reverse(NewDefsReversed.begin(), NewDefsReversed.end()); 2401 FnVarLocs.setWedge(&I, std::move(NewDefsReversed)); 2402 NumWedgesChanged++; 2403 Changed = true; 2404 } 2405 } 2406 2407 return Changed; 2408 } 2409 2410 /// Remove redundant location defs using a forward scan. This can remove a 2411 /// location definition that is redundant due to indicating that a variable has 2412 /// the same value as is already being indicated by an earlier def. 2413 /// 2414 /// This implements removeRedundantDbgInstrsUsingForwardScan from 2415 /// lib/Transforms/Utils/BasicBlockUtils.cpp for locations described with 2416 /// FunctionVarLocsBuilder instead of with intrinsics 2417 static bool 2418 removeRedundantDbgLocsUsingForwardScan(const BasicBlock *BB, 2419 FunctionVarLocsBuilder &FnVarLocs) { 2420 bool Changed = false; 2421 DenseMap<DebugVariable, std::pair<RawLocationWrapper, DIExpression *>> 2422 VariableMap; 2423 2424 // Scan over the entire block, not just over the instructions mapped by 2425 // FnVarLocs, because wedges in FnVarLocs may only be seperated by debug 2426 // instructions. 2427 for (const Instruction &I : *BB) { 2428 // Get the defs that come just before this instruction. 2429 const auto *Locs = FnVarLocs.getWedge(&I); 2430 if (!Locs) 2431 continue; 2432 2433 NumWedgesScanned++; 2434 bool ChangedThisWedge = false; 2435 // The new pruned set of defs. 2436 SmallVector<VarLocInfo> NewDefs; 2437 2438 // Iterate over the existing defs. 2439 for (const VarLocInfo &Loc : *Locs) { 2440 NumDefsScanned++; 2441 DebugVariable Key(FnVarLocs.getVariable(Loc.VariableID).getVariable(), 2442 std::nullopt, Loc.DL.getInlinedAt()); 2443 auto VMI = VariableMap.find(Key); 2444 2445 // Update the map if we found a new value/expression describing the 2446 // variable, or if the variable wasn't mapped already. 2447 if (VMI == VariableMap.end() || VMI->second.first != Loc.Values || 2448 VMI->second.second != Loc.Expr) { 2449 VariableMap[Key] = {Loc.Values, Loc.Expr}; 2450 NewDefs.push_back(Loc); 2451 continue; 2452 } 2453 2454 // Did not insert this Loc, which is the same as removing it. 2455 ChangedThisWedge = true; 2456 NumDefsRemoved++; 2457 } 2458 2459 // Replace the existing wedge with the pruned version. 2460 if (ChangedThisWedge) { 2461 FnVarLocs.setWedge(&I, std::move(NewDefs)); 2462 NumWedgesChanged++; 2463 Changed = true; 2464 } 2465 } 2466 2467 return Changed; 2468 } 2469 2470 static bool 2471 removeUndefDbgLocsFromEntryBlock(const BasicBlock *BB, 2472 FunctionVarLocsBuilder &FnVarLocs) { 2473 assert(BB->isEntryBlock()); 2474 // Do extra work to ensure that we remove semantically unimportant undefs. 2475 // 2476 // This is to work around the fact that SelectionDAG will hoist dbg.values 2477 // using argument values to the top of the entry block. That can move arg 2478 // dbg.values before undef and constant dbg.values which they previously 2479 // followed. The easiest thing to do is to just try to feed SelectionDAG 2480 // input it's happy with. 2481 // 2482 // Map of {Variable x: Fragments y} where the fragments y of variable x have 2483 // have at least one non-undef location defined already. Don't use directly, 2484 // instead call DefineBits and HasDefinedBits. 2485 SmallDenseMap<DebugAggregate, SmallDenseSet<DIExpression::FragmentInfo>> 2486 VarsWithDef; 2487 // Specify that V (a fragment of A) has a non-undef location. 2488 auto DefineBits = [&VarsWithDef](DebugAggregate A, DebugVariable V) { 2489 VarsWithDef[A].insert(V.getFragmentOrDefault()); 2490 }; 2491 // Return true if a non-undef location has been defined for V (a fragment of 2492 // A). Doesn't imply that the location is currently non-undef, just that a 2493 // non-undef location has been seen previously. 2494 auto HasDefinedBits = [&VarsWithDef](DebugAggregate A, DebugVariable V) { 2495 auto FragsIt = VarsWithDef.find(A); 2496 if (FragsIt == VarsWithDef.end()) 2497 return false; 2498 return llvm::any_of(FragsIt->second, [V](auto Frag) { 2499 return DIExpression::fragmentsOverlap(Frag, V.getFragmentOrDefault()); 2500 }); 2501 }; 2502 2503 bool Changed = false; 2504 DenseMap<DebugVariable, std::pair<Value *, DIExpression *>> VariableMap; 2505 2506 // Scan over the entire block, not just over the instructions mapped by 2507 // FnVarLocs, because wedges in FnVarLocs may only be seperated by debug 2508 // instructions. 2509 for (const Instruction &I : *BB) { 2510 // Get the defs that come just before this instruction. 2511 const auto *Locs = FnVarLocs.getWedge(&I); 2512 if (!Locs) 2513 continue; 2514 2515 NumWedgesScanned++; 2516 bool ChangedThisWedge = false; 2517 // The new pruned set of defs. 2518 SmallVector<VarLocInfo> NewDefs; 2519 2520 // Iterate over the existing defs. 2521 for (const VarLocInfo &Loc : *Locs) { 2522 NumDefsScanned++; 2523 DebugAggregate Aggr{FnVarLocs.getVariable(Loc.VariableID).getVariable(), 2524 Loc.DL.getInlinedAt()}; 2525 DebugVariable Var = FnVarLocs.getVariable(Loc.VariableID); 2526 2527 // Remove undef entries that are encountered before any non-undef 2528 // intrinsics from the entry block. 2529 if (Loc.Values.isKillLocation(Loc.Expr) && !HasDefinedBits(Aggr, Var)) { 2530 // Did not insert this Loc, which is the same as removing it. 2531 NumDefsRemoved++; 2532 ChangedThisWedge = true; 2533 continue; 2534 } 2535 2536 DefineBits(Aggr, Var); 2537 NewDefs.push_back(Loc); 2538 } 2539 2540 // Replace the existing wedge with the pruned version. 2541 if (ChangedThisWedge) { 2542 FnVarLocs.setWedge(&I, std::move(NewDefs)); 2543 NumWedgesChanged++; 2544 Changed = true; 2545 } 2546 } 2547 2548 return Changed; 2549 } 2550 2551 static bool removeRedundantDbgLocs(const BasicBlock *BB, 2552 FunctionVarLocsBuilder &FnVarLocs) { 2553 bool MadeChanges = false; 2554 MadeChanges |= removeRedundantDbgLocsUsingBackwardScan(BB, FnVarLocs); 2555 if (BB->isEntryBlock()) 2556 MadeChanges |= removeUndefDbgLocsFromEntryBlock(BB, FnVarLocs); 2557 MadeChanges |= removeRedundantDbgLocsUsingForwardScan(BB, FnVarLocs); 2558 2559 if (MadeChanges) 2560 LLVM_DEBUG(dbgs() << "Removed redundant dbg locs from: " << BB->getName() 2561 << "\n"); 2562 return MadeChanges; 2563 } 2564 2565 static DenseSet<DebugAggregate> findVarsWithStackSlot(Function &Fn) { 2566 DenseSet<DebugAggregate> Result; 2567 for (auto &BB : Fn) { 2568 for (auto &I : BB) { 2569 // Any variable linked to an instruction is considered 2570 // interesting. Ideally we only need to check Allocas, however, a 2571 // DIAssignID might get dropped from an alloca but not stores. In that 2572 // case, we need to consider the variable interesting for NFC behaviour 2573 // with this change. TODO: Consider only looking at allocas. 2574 for (DbgAssignIntrinsic *DAI : at::getAssignmentMarkers(&I)) { 2575 Result.insert({DAI->getVariable(), DAI->getDebugLoc().getInlinedAt()}); 2576 } 2577 } 2578 } 2579 return Result; 2580 } 2581 2582 static void analyzeFunction(Function &Fn, const DataLayout &Layout, 2583 FunctionVarLocsBuilder *FnVarLocs) { 2584 // The analysis will generate location definitions for all variables, but we 2585 // only need to perform a dataflow on the set of variables which have a stack 2586 // slot. Find those now. 2587 DenseSet<DebugAggregate> VarsWithStackSlot = findVarsWithStackSlot(Fn); 2588 2589 bool Changed = false; 2590 2591 // Use a scope block to clean up AssignmentTrackingLowering before running 2592 // MemLocFragmentFill to reduce peak memory consumption. 2593 { 2594 AssignmentTrackingLowering Pass(Fn, Layout, &VarsWithStackSlot); 2595 Changed = Pass.run(FnVarLocs); 2596 } 2597 2598 if (Changed) { 2599 MemLocFragmentFill Pass(Fn, &VarsWithStackSlot, 2600 shouldCoalesceFragments(Fn)); 2601 Pass.run(FnVarLocs); 2602 2603 // Remove redundant entries. As well as reducing memory consumption and 2604 // avoiding waiting cycles later by burning some now, this has another 2605 // important job. That is to work around some SelectionDAG quirks. See 2606 // removeRedundantDbgLocsUsingForwardScan comments for more info on that. 2607 for (auto &BB : Fn) 2608 removeRedundantDbgLocs(&BB, *FnVarLocs); 2609 } 2610 } 2611 2612 FunctionVarLocs 2613 DebugAssignmentTrackingAnalysis::run(Function &F, 2614 FunctionAnalysisManager &FAM) { 2615 if (!isAssignmentTrackingEnabled(*F.getParent())) 2616 return FunctionVarLocs(); 2617 2618 auto &DL = F.getParent()->getDataLayout(); 2619 2620 FunctionVarLocsBuilder Builder; 2621 analyzeFunction(F, DL, &Builder); 2622 2623 // Save these results. 2624 FunctionVarLocs Results; 2625 Results.init(Builder); 2626 return Results; 2627 } 2628 2629 AnalysisKey DebugAssignmentTrackingAnalysis::Key; 2630 2631 PreservedAnalyses 2632 DebugAssignmentTrackingPrinterPass::run(Function &F, 2633 FunctionAnalysisManager &FAM) { 2634 FAM.getResult<DebugAssignmentTrackingAnalysis>(F).print(OS, F); 2635 return PreservedAnalyses::all(); 2636 } 2637 2638 bool AssignmentTrackingAnalysis::runOnFunction(Function &F) { 2639 if (!isAssignmentTrackingEnabled(*F.getParent())) 2640 return false; 2641 2642 LLVM_DEBUG(dbgs() << "AssignmentTrackingAnalysis run on " << F.getName() 2643 << "\n"); 2644 auto DL = std::make_unique<DataLayout>(F.getParent()); 2645 2646 // Clear previous results. 2647 Results->clear(); 2648 2649 FunctionVarLocsBuilder Builder; 2650 analyzeFunction(F, *DL.get(), &Builder); 2651 2652 // Save these results. 2653 Results->init(Builder); 2654 2655 if (PrintResults && isFunctionInPrintList(F.getName())) 2656 Results->print(errs(), F); 2657 2658 // Return false because this pass does not modify the function. 2659 return false; 2660 } 2661 2662 AssignmentTrackingAnalysis::AssignmentTrackingAnalysis() 2663 : FunctionPass(ID), Results(std::make_unique<FunctionVarLocs>()) {} 2664 2665 char AssignmentTrackingAnalysis::ID = 0; 2666 2667 INITIALIZE_PASS(AssignmentTrackingAnalysis, DEBUG_TYPE, 2668 "Assignment Tracking Analysis", false, true) 2669