1 //===- InstrRefBasedImpl.h - Tracking Debug Value MIs ---------------------===// 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 #ifndef LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H 10 #define LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H 11 12 #include "llvm/ADT/DenseMap.h" 13 #include "llvm/ADT/SmallPtrSet.h" 14 #include "llvm/ADT/SmallVector.h" 15 #include "llvm/ADT/UniqueVector.h" 16 #include "llvm/CodeGen/LexicalScopes.h" 17 #include "llvm/CodeGen/MachineBasicBlock.h" 18 #include "llvm/CodeGen/MachineFrameInfo.h" 19 #include "llvm/CodeGen/MachineFunction.h" 20 #include "llvm/CodeGen/MachineInstr.h" 21 #include "llvm/CodeGen/TargetFrameLowering.h" 22 #include "llvm/CodeGen/TargetInstrInfo.h" 23 #include "llvm/CodeGen/TargetPassConfig.h" 24 #include "llvm/IR/DebugInfoMetadata.h" 25 26 #include "LiveDebugValues.h" 27 28 class VLocTracker; 29 class TransferTracker; 30 31 // Forward dec of unit test class, so that we can peer into the LDV object. 32 class InstrRefLDVTest; 33 34 namespace LiveDebugValues { 35 36 class MLocTracker; 37 38 using namespace llvm; 39 40 /// Handle-class for a particular "location". This value-type uniquely 41 /// symbolises a register or stack location, allowing manipulation of locations 42 /// without concern for where that location is. Practically, this allows us to 43 /// treat the state of the machine at a particular point as an array of values, 44 /// rather than a map of values. 45 class LocIdx { 46 unsigned Location; 47 48 // Default constructor is private, initializing to an illegal location number. 49 // Use only for "not an entry" elements in IndexedMaps. 50 LocIdx() : Location(UINT_MAX) {} 51 52 public: 53 #define NUM_LOC_BITS 24 54 LocIdx(unsigned L) : Location(L) { 55 assert(L < (1 << NUM_LOC_BITS) && "Machine locations must fit in 24 bits"); 56 } 57 58 static LocIdx MakeIllegalLoc() { return LocIdx(); } 59 60 bool isIllegal() const { return Location == UINT_MAX; } 61 62 uint64_t asU64() const { return Location; } 63 64 bool operator==(unsigned L) const { return Location == L; } 65 66 bool operator==(const LocIdx &L) const { return Location == L.Location; } 67 68 bool operator!=(unsigned L) const { return !(*this == L); } 69 70 bool operator!=(const LocIdx &L) const { return !(*this == L); } 71 72 bool operator<(const LocIdx &Other) const { 73 return Location < Other.Location; 74 } 75 }; 76 77 // The location at which a spilled value resides. It consists of a register and 78 // an offset. 79 struct SpillLoc { 80 unsigned SpillBase; 81 StackOffset SpillOffset; 82 bool operator==(const SpillLoc &Other) const { 83 return std::make_pair(SpillBase, SpillOffset) == 84 std::make_pair(Other.SpillBase, Other.SpillOffset); 85 } 86 bool operator<(const SpillLoc &Other) const { 87 return std::make_tuple(SpillBase, SpillOffset.getFixed(), 88 SpillOffset.getScalable()) < 89 std::make_tuple(Other.SpillBase, Other.SpillOffset.getFixed(), 90 Other.SpillOffset.getScalable()); 91 } 92 }; 93 94 /// Unique identifier for a value defined by an instruction, as a value type. 95 /// Casts back and forth to a uint64_t. Probably replacable with something less 96 /// bit-constrained. Each value identifies the instruction and machine location 97 /// where the value is defined, although there may be no corresponding machine 98 /// operand for it (ex: regmasks clobbering values). The instructions are 99 /// one-based, and definitions that are PHIs have instruction number zero. 100 /// 101 /// The obvious limits of a 1M block function or 1M instruction blocks are 102 /// problematic; but by that point we should probably have bailed out of 103 /// trying to analyse the function. 104 class ValueIDNum { 105 uint64_t BlockNo : 20; /// The block where the def happens. 106 uint64_t InstNo : 20; /// The Instruction where the def happens. 107 /// One based, is distance from start of block. 108 uint64_t LocNo : NUM_LOC_BITS; /// The machine location where the def happens. 109 110 public: 111 // Default-initialize to EmptyValue. This is necessary to make IndexedMaps 112 // of values to work. 113 ValueIDNum() : BlockNo(0xFFFFF), InstNo(0xFFFFF), LocNo(0xFFFFFF) {} 114 115 ValueIDNum(uint64_t Block, uint64_t Inst, uint64_t Loc) 116 : BlockNo(Block), InstNo(Inst), LocNo(Loc) {} 117 118 ValueIDNum(uint64_t Block, uint64_t Inst, LocIdx Loc) 119 : BlockNo(Block), InstNo(Inst), LocNo(Loc.asU64()) {} 120 121 uint64_t getBlock() const { return BlockNo; } 122 uint64_t getInst() const { return InstNo; } 123 uint64_t getLoc() const { return LocNo; } 124 bool isPHI() const { return InstNo == 0; } 125 126 uint64_t asU64() const { 127 uint64_t TmpBlock = BlockNo; 128 uint64_t TmpInst = InstNo; 129 return TmpBlock << 44ull | TmpInst << NUM_LOC_BITS | LocNo; 130 } 131 132 static ValueIDNum fromU64(uint64_t v) { 133 uint64_t L = (v & 0x3FFF); 134 return {v >> 44ull, ((v >> NUM_LOC_BITS) & 0xFFFFF), L}; 135 } 136 137 bool operator<(const ValueIDNum &Other) const { 138 return asU64() < Other.asU64(); 139 } 140 141 bool operator==(const ValueIDNum &Other) const { 142 return std::tie(BlockNo, InstNo, LocNo) == 143 std::tie(Other.BlockNo, Other.InstNo, Other.LocNo); 144 } 145 146 bool operator!=(const ValueIDNum &Other) const { return !(*this == Other); } 147 148 std::string asString(const std::string &mlocname) const { 149 return Twine("Value{bb: ") 150 .concat(Twine(BlockNo).concat( 151 Twine(", inst: ") 152 .concat((InstNo ? Twine(InstNo) : Twine("live-in")) 153 .concat(Twine(", loc: ").concat(Twine(mlocname))) 154 .concat(Twine("}"))))) 155 .str(); 156 } 157 158 static ValueIDNum EmptyValue; 159 }; 160 161 /// Meta qualifiers for a value. Pair of whatever expression is used to qualify 162 /// the the value, and Boolean of whether or not it's indirect. 163 class DbgValueProperties { 164 public: 165 DbgValueProperties(const DIExpression *DIExpr, bool Indirect) 166 : DIExpr(DIExpr), Indirect(Indirect) {} 167 168 /// Extract properties from an existing DBG_VALUE instruction. 169 DbgValueProperties(const MachineInstr &MI) { 170 assert(MI.isDebugValue()); 171 DIExpr = MI.getDebugExpression(); 172 Indirect = MI.getOperand(1).isImm(); 173 } 174 175 bool operator==(const DbgValueProperties &Other) const { 176 return std::tie(DIExpr, Indirect) == std::tie(Other.DIExpr, Other.Indirect); 177 } 178 179 bool operator!=(const DbgValueProperties &Other) const { 180 return !(*this == Other); 181 } 182 183 const DIExpression *DIExpr; 184 bool Indirect; 185 }; 186 187 /// Class recording the (high level) _value_ of a variable. Identifies either 188 /// the value of the variable as a ValueIDNum, or a constant MachineOperand. 189 /// This class also stores meta-information about how the value is qualified. 190 /// Used to reason about variable values when performing the second 191 /// (DebugVariable specific) dataflow analysis. 192 class DbgValue { 193 public: 194 union { 195 /// If Kind is Def, the value number that this value is based on. 196 ValueIDNum ID; 197 /// If Kind is Const, the MachineOperand defining this value. 198 MachineOperand MO; 199 /// For a NoVal DbgValue, which block it was generated in. 200 unsigned BlockNo; 201 }; 202 /// Qualifiers for the ValueIDNum above. 203 DbgValueProperties Properties; 204 205 typedef enum { 206 Undef, // Represents a DBG_VALUE $noreg in the transfer function only. 207 Def, // This value is defined by an inst, or is a PHI value. 208 Const, // A constant value contained in the MachineOperand field. 209 Proposed, // This is a tentative PHI value, which may be confirmed or 210 // invalidated later. 211 NoVal // Empty DbgValue, generated during dataflow. BlockNo stores 212 // which block this was generated in. 213 } KindT; 214 /// Discriminator for whether this is a constant or an in-program value. 215 KindT Kind; 216 217 DbgValue(const ValueIDNum &Val, const DbgValueProperties &Prop, KindT Kind) 218 : ID(Val), Properties(Prop), Kind(Kind) { 219 assert(Kind == Def || Kind == Proposed); 220 } 221 222 DbgValue(unsigned BlockNo, const DbgValueProperties &Prop, KindT Kind) 223 : BlockNo(BlockNo), Properties(Prop), Kind(Kind) { 224 assert(Kind == NoVal); 225 } 226 227 DbgValue(const MachineOperand &MO, const DbgValueProperties &Prop, KindT Kind) 228 : MO(MO), Properties(Prop), Kind(Kind) { 229 assert(Kind == Const); 230 } 231 232 DbgValue(const DbgValueProperties &Prop, KindT Kind) 233 : Properties(Prop), Kind(Kind) { 234 assert(Kind == Undef && 235 "Empty DbgValue constructor must pass in Undef kind"); 236 } 237 238 #ifndef NDEBUG 239 void dump(const MLocTracker *MTrack) const; 240 #endif 241 242 bool operator==(const DbgValue &Other) const { 243 if (std::tie(Kind, Properties) != std::tie(Other.Kind, Other.Properties)) 244 return false; 245 else if (Kind == Proposed && ID != Other.ID) 246 return false; 247 else if (Kind == Def && ID != Other.ID) 248 return false; 249 else if (Kind == NoVal && BlockNo != Other.BlockNo) 250 return false; 251 else if (Kind == Const) 252 return MO.isIdenticalTo(Other.MO); 253 254 return true; 255 } 256 257 bool operator!=(const DbgValue &Other) const { return !(*this == Other); } 258 }; 259 260 class LocIdxToIndexFunctor { 261 public: 262 using argument_type = LocIdx; 263 unsigned operator()(const LocIdx &L) const { return L.asU64(); } 264 }; 265 266 /// Tracker for what values are in machine locations. Listens to the Things 267 /// being Done by various instructions, and maintains a table of what machine 268 /// locations have what values (as defined by a ValueIDNum). 269 /// 270 /// There are potentially a much larger number of machine locations on the 271 /// target machine than the actual working-set size of the function. On x86 for 272 /// example, we're extremely unlikely to want to track values through control 273 /// or debug registers. To avoid doing so, MLocTracker has several layers of 274 /// indirection going on, with two kinds of ``location'': 275 /// * A LocID uniquely identifies a register or spill location, with a 276 /// predictable value. 277 /// * A LocIdx is a key (in the database sense) for a LocID and a ValueIDNum. 278 /// Whenever a location is def'd or used by a MachineInstr, we automagically 279 /// create a new LocIdx for a location, but not otherwise. This ensures we only 280 /// account for locations that are actually used or defined. The cost is another 281 /// vector lookup (of LocID -> LocIdx) over any other implementation. This is 282 /// fairly cheap, and the compiler tries to reduce the working-set at any one 283 /// time in the function anyway. 284 /// 285 /// Register mask operands completely blow this out of the water; I've just 286 /// piled hacks on top of hacks to get around that. 287 class MLocTracker { 288 public: 289 MachineFunction &MF; 290 const TargetInstrInfo &TII; 291 const TargetRegisterInfo &TRI; 292 const TargetLowering &TLI; 293 294 /// IndexedMap type, mapping from LocIdx to ValueIDNum. 295 using LocToValueType = IndexedMap<ValueIDNum, LocIdxToIndexFunctor>; 296 297 /// Map of LocIdxes to the ValueIDNums that they store. This is tightly 298 /// packed, entries only exist for locations that are being tracked. 299 LocToValueType LocIdxToIDNum; 300 301 /// "Map" of machine location IDs (i.e., raw register or spill number) to the 302 /// LocIdx key / number for that location. There are always at least as many 303 /// as the number of registers on the target -- if the value in the register 304 /// is not being tracked, then the LocIdx value will be zero. New entries are 305 /// appended if a new spill slot begins being tracked. 306 /// This, and the corresponding reverse map persist for the analysis of the 307 /// whole function, and is necessarying for decoding various vectors of 308 /// values. 309 std::vector<LocIdx> LocIDToLocIdx; 310 311 /// Inverse map of LocIDToLocIdx. 312 IndexedMap<unsigned, LocIdxToIndexFunctor> LocIdxToLocID; 313 314 /// When clobbering register masks, we chose to not believe the machine model 315 /// and don't clobber SP. Do the same for SP aliases, and for efficiency, 316 /// keep a set of them here. 317 SmallSet<Register, 8> SPAliases; 318 319 /// Unique-ification of spill slots. Used to number them -- their LocID 320 /// number is the index in SpillLocs minus one plus NumRegs. 321 UniqueVector<SpillLoc> SpillLocs; 322 323 // If we discover a new machine location, assign it an mphi with this 324 // block number. 325 unsigned CurBB; 326 327 /// Cached local copy of the number of registers the target has. 328 unsigned NumRegs; 329 330 /// Collection of register mask operands that have been observed. Second part 331 /// of pair indicates the instruction that they happened in. Used to 332 /// reconstruct where defs happened if we start tracking a location later 333 /// on. 334 SmallVector<std::pair<const MachineOperand *, unsigned>, 32> Masks; 335 336 /// Iterator for locations and the values they contain. Dereferencing 337 /// produces a struct/pair containing the LocIdx key for this location, 338 /// and a reference to the value currently stored. Simplifies the process 339 /// of seeking a particular location. 340 class MLocIterator { 341 LocToValueType &ValueMap; 342 LocIdx Idx; 343 344 public: 345 class value_type { 346 public: 347 value_type(LocIdx Idx, ValueIDNum &Value) : Idx(Idx), Value(Value) {} 348 const LocIdx Idx; /// Read-only index of this location. 349 ValueIDNum &Value; /// Reference to the stored value at this location. 350 }; 351 352 MLocIterator(LocToValueType &ValueMap, LocIdx Idx) 353 : ValueMap(ValueMap), Idx(Idx) {} 354 355 bool operator==(const MLocIterator &Other) const { 356 assert(&ValueMap == &Other.ValueMap); 357 return Idx == Other.Idx; 358 } 359 360 bool operator!=(const MLocIterator &Other) const { 361 return !(*this == Other); 362 } 363 364 void operator++() { Idx = LocIdx(Idx.asU64() + 1); } 365 366 value_type operator*() { return value_type(Idx, ValueMap[LocIdx(Idx)]); } 367 }; 368 369 MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII, 370 const TargetRegisterInfo &TRI, const TargetLowering &TLI); 371 372 /// Produce location ID number for indexing LocIDToLocIdx. Takes the register 373 /// or spill number, and flag for whether it's a spill or not. 374 unsigned getLocID(Register RegOrSpill, bool isSpill) { 375 return (isSpill) ? RegOrSpill.id() + NumRegs - 1 : RegOrSpill.id(); 376 } 377 378 /// Accessor for reading the value at Idx. 379 ValueIDNum getNumAtPos(LocIdx Idx) const { 380 assert(Idx.asU64() < LocIdxToIDNum.size()); 381 return LocIdxToIDNum[Idx]; 382 } 383 384 unsigned getNumLocs(void) const { return LocIdxToIDNum.size(); } 385 386 /// Reset all locations to contain a PHI value at the designated block. Used 387 /// sometimes for actual PHI values, othertimes to indicate the block entry 388 /// value (before any more information is known). 389 void setMPhis(unsigned NewCurBB) { 390 CurBB = NewCurBB; 391 for (auto Location : locations()) 392 Location.Value = {CurBB, 0, Location.Idx}; 393 } 394 395 /// Load values for each location from array of ValueIDNums. Take current 396 /// bbnum just in case we read a value from a hitherto untouched register. 397 void loadFromArray(ValueIDNum *Locs, unsigned NewCurBB) { 398 CurBB = NewCurBB; 399 // Iterate over all tracked locations, and load each locations live-in 400 // value into our local index. 401 for (auto Location : locations()) 402 Location.Value = Locs[Location.Idx.asU64()]; 403 } 404 405 /// Wipe any un-necessary location records after traversing a block. 406 void reset(void) { 407 // We could reset all the location values too; however either loadFromArray 408 // or setMPhis should be called before this object is re-used. Just 409 // clear Masks, they're definitely not needed. 410 Masks.clear(); 411 } 412 413 /// Clear all data. Destroys the LocID <=> LocIdx map, which makes most of 414 /// the information in this pass uninterpretable. 415 void clear(void) { 416 reset(); 417 LocIDToLocIdx.clear(); 418 LocIdxToLocID.clear(); 419 LocIdxToIDNum.clear(); 420 // SpillLocs.reset(); XXX UniqueVector::reset assumes a SpillLoc casts from 421 // 0 422 SpillLocs = decltype(SpillLocs)(); 423 424 LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc()); 425 } 426 427 /// Set a locaiton to a certain value. 428 void setMLoc(LocIdx L, ValueIDNum Num) { 429 assert(L.asU64() < LocIdxToIDNum.size()); 430 LocIdxToIDNum[L] = Num; 431 } 432 433 /// Create a LocIdx for an untracked register ID. Initialize it to either an 434 /// mphi value representing a live-in, or a recent register mask clobber. 435 LocIdx trackRegister(unsigned ID); 436 437 LocIdx lookupOrTrackRegister(unsigned ID) { 438 LocIdx &Index = LocIDToLocIdx[ID]; 439 if (Index.isIllegal()) 440 Index = trackRegister(ID); 441 return Index; 442 } 443 444 /// Is register R currently tracked by MLocTracker? 445 bool isRegisterTracked(Register R) { 446 LocIdx &Index = LocIDToLocIdx[R]; 447 return !Index.isIllegal(); 448 } 449 450 /// Record a definition of the specified register at the given block / inst. 451 /// This doesn't take a ValueIDNum, because the definition and its location 452 /// are synonymous. 453 void defReg(Register R, unsigned BB, unsigned Inst) { 454 unsigned ID = getLocID(R, false); 455 LocIdx Idx = lookupOrTrackRegister(ID); 456 ValueIDNum ValueID = {BB, Inst, Idx}; 457 LocIdxToIDNum[Idx] = ValueID; 458 } 459 460 /// Set a register to a value number. To be used if the value number is 461 /// known in advance. 462 void setReg(Register R, ValueIDNum ValueID) { 463 unsigned ID = getLocID(R, false); 464 LocIdx Idx = lookupOrTrackRegister(ID); 465 LocIdxToIDNum[Idx] = ValueID; 466 } 467 468 ValueIDNum readReg(Register R) { 469 unsigned ID = getLocID(R, false); 470 LocIdx Idx = lookupOrTrackRegister(ID); 471 return LocIdxToIDNum[Idx]; 472 } 473 474 /// Reset a register value to zero / empty. Needed to replicate the 475 /// VarLoc implementation where a copy to/from a register effectively 476 /// clears the contents of the source register. (Values can only have one 477 /// machine location in VarLocBasedImpl). 478 void wipeRegister(Register R) { 479 unsigned ID = getLocID(R, false); 480 LocIdx Idx = LocIDToLocIdx[ID]; 481 LocIdxToIDNum[Idx] = ValueIDNum::EmptyValue; 482 } 483 484 /// Determine the LocIdx of an existing register. 485 LocIdx getRegMLoc(Register R) { 486 unsigned ID = getLocID(R, false); 487 return LocIDToLocIdx[ID]; 488 } 489 490 /// Record a RegMask operand being executed. Defs any register we currently 491 /// track, stores a pointer to the mask in case we have to account for it 492 /// later. 493 void writeRegMask(const MachineOperand *MO, unsigned CurBB, unsigned InstID); 494 495 /// Find LocIdx for SpillLoc \p L, creating a new one if it's not tracked. 496 LocIdx getOrTrackSpillLoc(SpillLoc L); 497 498 /// Set the value stored in a spill slot. 499 void setSpill(SpillLoc L, ValueIDNum ValueID) { 500 LocIdx Idx = getOrTrackSpillLoc(L); 501 LocIdxToIDNum[Idx] = ValueID; 502 } 503 504 /// Read whatever value is in a spill slot, or None if it isn't tracked. 505 Optional<ValueIDNum> readSpill(SpillLoc L) { 506 unsigned SpillID = SpillLocs.idFor(L); 507 if (SpillID == 0) 508 return None; 509 510 unsigned LocID = getLocID(SpillID, true); 511 LocIdx Idx = LocIDToLocIdx[LocID]; 512 return LocIdxToIDNum[Idx]; 513 } 514 515 /// Determine the LocIdx of a spill slot. Return None if it previously 516 /// hasn't had a value assigned. 517 Optional<LocIdx> getSpillMLoc(SpillLoc L) { 518 unsigned SpillID = SpillLocs.idFor(L); 519 if (SpillID == 0) 520 return None; 521 unsigned LocNo = getLocID(SpillID, true); 522 return LocIDToLocIdx[LocNo]; 523 } 524 525 /// Return true if Idx is a spill machine location. 526 bool isSpill(LocIdx Idx) const { return LocIdxToLocID[Idx] >= NumRegs; } 527 528 MLocIterator begin() { return MLocIterator(LocIdxToIDNum, 0); } 529 530 MLocIterator end() { 531 return MLocIterator(LocIdxToIDNum, LocIdxToIDNum.size()); 532 } 533 534 /// Return a range over all locations currently tracked. 535 iterator_range<MLocIterator> locations() { 536 return llvm::make_range(begin(), end()); 537 } 538 539 std::string LocIdxToName(LocIdx Idx) const; 540 541 std::string IDAsString(const ValueIDNum &Num) const; 542 543 #ifndef NDEBUG 544 LLVM_DUMP_METHOD void dump(); 545 546 LLVM_DUMP_METHOD void dump_mloc_map(); 547 #endif 548 549 /// Create a DBG_VALUE based on machine location \p MLoc. Qualify it with the 550 /// information in \pProperties, for variable Var. Don't insert it anywhere, 551 /// just return the builder for it. 552 MachineInstrBuilder emitLoc(Optional<LocIdx> MLoc, const DebugVariable &Var, 553 const DbgValueProperties &Properties); 554 }; 555 556 /// Types for recording sets of variable fragments that overlap. For a given 557 /// local variable, we record all other fragments of that variable that could 558 /// overlap it, to reduce search time. 559 using FragmentOfVar = 560 std::pair<const DILocalVariable *, DIExpression::FragmentInfo>; 561 using OverlapMap = 562 DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>; 563 564 // XXX XXX docs 565 class InstrRefBasedLDV : public LDVImpl { 566 private: 567 friend class ::InstrRefLDVTest; 568 569 using FragmentInfo = DIExpression::FragmentInfo; 570 using OptFragmentInfo = Optional<DIExpression::FragmentInfo>; 571 572 // Helper while building OverlapMap, a map of all fragments seen for a given 573 // DILocalVariable. 574 using VarToFragments = 575 DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>; 576 577 /// Machine location/value transfer function, a mapping of which locations 578 /// are assigned which new values. 579 using MLocTransferMap = std::map<LocIdx, ValueIDNum>; 580 581 /// Live in/out structure for the variable values: a per-block map of 582 /// variables to their values. XXX, better name? 583 using LiveIdxT = 584 DenseMap<const MachineBasicBlock *, DenseMap<DebugVariable, DbgValue> *>; 585 586 using VarAndLoc = std::pair<DebugVariable, DbgValue>; 587 588 /// Type for a live-in value: the predecessor block, and its value. 589 using InValueT = std::pair<MachineBasicBlock *, DbgValue *>; 590 591 /// Vector (per block) of a collection (inner smallvector) of live-ins. 592 /// Used as the result type for the variable value dataflow problem. 593 using LiveInsT = SmallVector<SmallVector<VarAndLoc, 8>, 8>; 594 595 MachineDominatorTree *DomTree; 596 const TargetRegisterInfo *TRI; 597 const TargetInstrInfo *TII; 598 const TargetFrameLowering *TFI; 599 const MachineFrameInfo *MFI; 600 BitVector CalleeSavedRegs; 601 LexicalScopes LS; 602 TargetPassConfig *TPC; 603 604 /// Object to track machine locations as we step through a block. Could 605 /// probably be a field rather than a pointer, as it's always used. 606 MLocTracker *MTracker; 607 608 /// Number of the current block LiveDebugValues is stepping through. 609 unsigned CurBB; 610 611 /// Number of the current instruction LiveDebugValues is evaluating. 612 unsigned CurInst; 613 614 /// Variable tracker -- listens to DBG_VALUEs occurring as InstrRefBasedImpl 615 /// steps through a block. Reads the values at each location from the 616 /// MLocTracker object. 617 VLocTracker *VTracker; 618 619 /// Tracker for transfers, listens to DBG_VALUEs and transfers of values 620 /// between locations during stepping, creates new DBG_VALUEs when values move 621 /// location. 622 TransferTracker *TTracker; 623 624 /// Blocks which are artificial, i.e. blocks which exclusively contain 625 /// instructions without DebugLocs, or with line 0 locations. 626 SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks; 627 628 // Mapping of blocks to and from their RPOT order. 629 DenseMap<unsigned int, MachineBasicBlock *> OrderToBB; 630 DenseMap<MachineBasicBlock *, unsigned int> BBToOrder; 631 DenseMap<unsigned, unsigned> BBNumToRPO; 632 633 /// Pair of MachineInstr, and its 1-based offset into the containing block. 634 using InstAndNum = std::pair<const MachineInstr *, unsigned>; 635 /// Map from debug instruction number to the MachineInstr labelled with that 636 /// number, and its location within the function. Used to transform 637 /// instruction numbers in DBG_INSTR_REFs into machine value numbers. 638 std::map<uint64_t, InstAndNum> DebugInstrNumToInstr; 639 640 /// Record of where we observed a DBG_PHI instruction. 641 class DebugPHIRecord { 642 public: 643 uint64_t InstrNum; ///< Instruction number of this DBG_PHI. 644 MachineBasicBlock *MBB; ///< Block where DBG_PHI occurred. 645 ValueIDNum ValueRead; ///< The value number read by the DBG_PHI. 646 LocIdx ReadLoc; ///< Register/Stack location the DBG_PHI reads. 647 648 operator unsigned() const { return InstrNum; } 649 }; 650 651 /// Map from instruction numbers defined by DBG_PHIs to a record of what that 652 /// DBG_PHI read and where. Populated and edited during the machine value 653 /// location problem -- we use LLVMs SSA Updater to fix changes by 654 /// optimizations that destroy PHI instructions. 655 SmallVector<DebugPHIRecord, 32> DebugPHINumToValue; 656 657 // Map of overlapping variable fragments. 658 OverlapMap OverlapFragments; 659 VarToFragments SeenFragments; 660 661 /// Tests whether this instruction is a spill to a stack slot. 662 bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF); 663 664 /// Decide if @MI is a spill instruction and return true if it is. We use 2 665 /// criteria to make this decision: 666 /// - Is this instruction a store to a spill slot? 667 /// - Is there a register operand that is both used and killed? 668 /// TODO: Store optimization can fold spills into other stores (including 669 /// other spills). We do not handle this yet (more than one memory operand). 670 bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF, 671 unsigned &Reg); 672 673 /// If a given instruction is identified as a spill, return the spill slot 674 /// and set \p Reg to the spilled register. 675 Optional<SpillLoc> isRestoreInstruction(const MachineInstr &MI, 676 MachineFunction *MF, unsigned &Reg); 677 678 /// Given a spill instruction, extract the register and offset used to 679 /// address the spill slot in a target independent way. 680 SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI); 681 682 /// Observe a single instruction while stepping through a block. 683 void process(MachineInstr &MI, ValueIDNum **MLiveOuts = nullptr, 684 ValueIDNum **MLiveIns = nullptr); 685 686 /// Examines whether \p MI is a DBG_VALUE and notifies trackers. 687 /// \returns true if MI was recognized and processed. 688 bool transferDebugValue(const MachineInstr &MI); 689 690 /// Examines whether \p MI is a DBG_INSTR_REF and notifies trackers. 691 /// \returns true if MI was recognized and processed. 692 bool transferDebugInstrRef(MachineInstr &MI, ValueIDNum **MLiveOuts, 693 ValueIDNum **MLiveIns); 694 695 /// Stores value-information about where this PHI occurred, and what 696 /// instruction number is associated with it. 697 /// \returns true if MI was recognized and processed. 698 bool transferDebugPHI(MachineInstr &MI); 699 700 /// Examines whether \p MI is copy instruction, and notifies trackers. 701 /// \returns true if MI was recognized and processed. 702 bool transferRegisterCopy(MachineInstr &MI); 703 704 /// Examines whether \p MI is stack spill or restore instruction, and 705 /// notifies trackers. \returns true if MI was recognized and processed. 706 bool transferSpillOrRestoreInst(MachineInstr &MI); 707 708 /// Examines \p MI for any registers that it defines, and notifies trackers. 709 void transferRegisterDef(MachineInstr &MI); 710 711 /// Copy one location to the other, accounting for movement of subregisters 712 /// too. 713 void performCopy(Register Src, Register Dst); 714 715 void accumulateFragmentMap(MachineInstr &MI); 716 717 /// Determine the machine value number referred to by (potentially several) 718 /// DBG_PHI instructions. Block duplication and tail folding can duplicate 719 /// DBG_PHIs, shifting the position where values in registers merge, and 720 /// forming another mini-ssa problem to solve. 721 /// \p Here the position of a DBG_INSTR_REF seeking a machine value number 722 /// \p InstrNum Debug instruction number defined by DBG_PHI instructions. 723 /// \returns The machine value number at position Here, or None. 724 Optional<ValueIDNum> resolveDbgPHIs(MachineFunction &MF, 725 ValueIDNum **MLiveOuts, 726 ValueIDNum **MLiveIns, MachineInstr &Here, 727 uint64_t InstrNum); 728 729 /// Step through the function, recording register definitions and movements 730 /// in an MLocTracker. Convert the observations into a per-block transfer 731 /// function in \p MLocTransfer, suitable for using with the machine value 732 /// location dataflow problem. 733 void 734 produceMLocTransferFunction(MachineFunction &MF, 735 SmallVectorImpl<MLocTransferMap> &MLocTransfer, 736 unsigned MaxNumBlocks); 737 738 /// Solve the machine value location dataflow problem. Takes as input the 739 /// transfer functions in \p MLocTransfer. Writes the output live-in and 740 /// live-out arrays to the (initialized to zero) multidimensional arrays in 741 /// \p MInLocs and \p MOutLocs. The outer dimension is indexed by block 742 /// number, the inner by LocIdx. 743 void buildMLocValueMap(MachineFunction &MF, ValueIDNum **MInLocs, 744 ValueIDNum **MOutLocs, 745 SmallVectorImpl<MLocTransferMap> &MLocTransfer); 746 747 /// Install PHI values into the live-in array for each block, according to 748 /// the IDF of each register. 749 void placeMLocPHIs(MachineFunction &MF, 750 SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks, 751 ValueIDNum **MInLocs, 752 SmallVectorImpl<MLocTransferMap> &MLocTransfer); 753 754 /// Calculate the iterated-dominance-frontier for a set of defs, using the 755 /// existing LLVM facilities for this. Works for a single "value" or 756 /// machine/variable location. 757 /// \p AllBlocks Set of blocks where we might consume the value. 758 /// \p DefBlocks Set of blocks where the value/location is defined. 759 /// \p PHIBlocks Output set of blocks where PHIs must be placed. 760 void BlockPHIPlacement(const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks, 761 const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks, 762 SmallVectorImpl<MachineBasicBlock *> &PHIBlocks); 763 764 /// Perform a control flow join (lattice value meet) of the values in machine 765 /// locations at \p MBB. Follows the algorithm described in the file-comment, 766 /// reading live-outs of predecessors from \p OutLocs, the current live ins 767 /// from \p InLocs, and assigning the newly computed live ins back into 768 /// \p InLocs. \returns two bools -- the first indicates whether a change 769 /// was made, the second whether a lattice downgrade occurred. If the latter 770 /// is true, revisiting this block is necessary. 771 bool mlocJoin(MachineBasicBlock &MBB, 772 SmallPtrSet<const MachineBasicBlock *, 16> &Visited, 773 ValueIDNum **OutLocs, ValueIDNum *InLocs); 774 775 /// Solve the variable value dataflow problem, for a single lexical scope. 776 /// Uses the algorithm from the file comment to resolve control flow joins, 777 /// although there are extra hacks, see vlocJoin. Reads the 778 /// locations of values from the \p MInLocs and \p MOutLocs arrays (see 779 /// buildMLocValueMap) and reads the variable values transfer function from 780 /// \p AllTheVlocs. Live-in and Live-out variable values are stored locally, 781 /// with the live-ins permanently stored to \p Output once the fixedpoint is 782 /// reached. 783 /// \p VarsWeCareAbout contains a collection of the variables in \p Scope 784 /// that we should be tracking. 785 /// \p AssignBlocks contains the set of blocks that aren't in \p Scope, but 786 /// which do contain DBG_VALUEs, which VarLocBasedImpl tracks locations 787 /// through. 788 void vlocDataflow(const LexicalScope *Scope, const DILocation *DILoc, 789 const SmallSet<DebugVariable, 4> &VarsWeCareAbout, 790 SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, 791 LiveInsT &Output, ValueIDNum **MOutLocs, 792 ValueIDNum **MInLocs, 793 SmallVectorImpl<VLocTracker> &AllTheVLocs); 794 795 /// Compute the live-ins to a block, considering control flow merges according 796 /// to the method in the file comment. Live out and live in variable values 797 /// are stored in \p VLOCOutLocs and \p VLOCInLocs. The live-ins for \p MBB 798 /// are computed and stored into \p VLOCInLocs. \returns true if the live-ins 799 /// are modified. 800 /// \p InLocsT Output argument, storage for calculated live-ins. 801 /// \returns two bools -- the first indicates whether a change 802 /// was made, the second whether a lattice downgrade occurred. If the latter 803 /// is true, revisiting this block is necessary. 804 std::tuple<bool, bool> 805 vlocJoin(MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs, LiveIdxT &VLOCInLocs, 806 SmallPtrSet<const MachineBasicBlock *, 16> *VLOCVisited, 807 unsigned BBNum, const SmallSet<DebugVariable, 4> &AllVars, 808 ValueIDNum **MOutLocs, ValueIDNum **MInLocs, 809 SmallPtrSet<const MachineBasicBlock *, 8> &InScopeBlocks, 810 SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore, 811 DenseMap<DebugVariable, DbgValue> &InLocsT); 812 813 /// Continue exploration of the variable-value lattice, as explained in the 814 /// file-level comment. \p OldLiveInLocation contains the current 815 /// exploration position, from which we need to descend further. \p Values 816 /// contains the set of live-in values, \p CurBlockRPONum the RPO number of 817 /// the current block, and \p CandidateLocations a set of locations that 818 /// should be considered as PHI locations, if we reach the bottom of the 819 /// lattice. \returns true if we should downgrade; the value is the agreeing 820 /// value number in a non-backedge predecessor. 821 bool vlocDowngradeLattice(const MachineBasicBlock &MBB, 822 const DbgValue &OldLiveInLocation, 823 const SmallVectorImpl<InValueT> &Values, 824 unsigned CurBlockRPONum); 825 826 /// For the given block and live-outs feeding into it, try to find a 827 /// machine location where they all join. If a solution for all predecessors 828 /// can't be found, a location where all non-backedge-predecessors join 829 /// will be returned instead. While this method finds a join location, this 830 /// says nothing as to whether it should be used. 831 /// \returns Pair of value ID if found, and true when the correct value 832 /// is available on all predecessor edges, or false if it's only available 833 /// for non-backedge predecessors. 834 std::tuple<Optional<ValueIDNum>, bool> 835 pickVPHILoc(MachineBasicBlock &MBB, const DebugVariable &Var, 836 const LiveIdxT &LiveOuts, ValueIDNum **MOutLocs, 837 ValueIDNum **MInLocs, 838 const SmallVectorImpl<MachineBasicBlock *> &BlockOrders); 839 840 /// Given the solutions to the two dataflow problems, machine value locations 841 /// in \p MInLocs and live-in variable values in \p SavedLiveIns, runs the 842 /// TransferTracker class over the function to produce live-in and transfer 843 /// DBG_VALUEs, then inserts them. Groups of DBG_VALUEs are inserted in the 844 /// order given by AllVarsNumbering -- this could be any stable order, but 845 /// right now "order of appearence in function, when explored in RPO", so 846 /// that we can compare explictly against VarLocBasedImpl. 847 void emitLocations(MachineFunction &MF, LiveInsT SavedLiveIns, 848 ValueIDNum **MOutLocs, ValueIDNum **MInLocs, 849 DenseMap<DebugVariable, unsigned> &AllVarsNumbering, 850 const TargetPassConfig &TPC); 851 852 /// Boilerplate computation of some initial sets, artifical blocks and 853 /// RPOT block ordering. 854 void initialSetup(MachineFunction &MF); 855 856 bool ExtendRanges(MachineFunction &MF, MachineDominatorTree *DomTree, 857 TargetPassConfig *TPC, unsigned InputBBLimit, 858 unsigned InputDbgValLimit) override; 859 860 public: 861 /// Default construct and initialize the pass. 862 InstrRefBasedLDV(); 863 864 LLVM_DUMP_METHOD 865 void dump_mloc_transfer(const MLocTransferMap &mloc_transfer) const; 866 867 bool isCalleeSaved(LocIdx L) const; 868 }; 869 870 } // namespace LiveDebugValues 871 872 #endif /* LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H */ 873