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 /// Unique-ification of spill slots. Used to number them -- their LocID 315 /// number is the index in SpillLocs minus one plus NumRegs. 316 UniqueVector<SpillLoc> SpillLocs; 317 318 // If we discover a new machine location, assign it an mphi with this 319 // block number. 320 unsigned CurBB; 321 322 /// Cached local copy of the number of registers the target has. 323 unsigned NumRegs; 324 325 /// Collection of register mask operands that have been observed. Second part 326 /// of pair indicates the instruction that they happened in. Used to 327 /// reconstruct where defs happened if we start tracking a location later 328 /// on. 329 SmallVector<std::pair<const MachineOperand *, unsigned>, 32> Masks; 330 331 /// Iterator for locations and the values they contain. Dereferencing 332 /// produces a struct/pair containing the LocIdx key for this location, 333 /// and a reference to the value currently stored. Simplifies the process 334 /// of seeking a particular location. 335 class MLocIterator { 336 LocToValueType &ValueMap; 337 LocIdx Idx; 338 339 public: 340 class value_type { 341 public: 342 value_type(LocIdx Idx, ValueIDNum &Value) : Idx(Idx), Value(Value) {} 343 const LocIdx Idx; /// Read-only index of this location. 344 ValueIDNum &Value; /// Reference to the stored value at this location. 345 }; 346 347 MLocIterator(LocToValueType &ValueMap, LocIdx Idx) 348 : ValueMap(ValueMap), Idx(Idx) {} 349 350 bool operator==(const MLocIterator &Other) const { 351 assert(&ValueMap == &Other.ValueMap); 352 return Idx == Other.Idx; 353 } 354 355 bool operator!=(const MLocIterator &Other) const { 356 return !(*this == Other); 357 } 358 359 void operator++() { Idx = LocIdx(Idx.asU64() + 1); } 360 361 value_type operator*() { return value_type(Idx, ValueMap[LocIdx(Idx)]); } 362 }; 363 364 MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII, 365 const TargetRegisterInfo &TRI, const TargetLowering &TLI); 366 367 /// Produce location ID number for indexing LocIDToLocIdx. Takes the register 368 /// or spill number, and flag for whether it's a spill or not. 369 unsigned getLocID(Register RegOrSpill, bool isSpill) { 370 return (isSpill) ? RegOrSpill.id() + NumRegs - 1 : RegOrSpill.id(); 371 } 372 373 /// Accessor for reading the value at Idx. 374 ValueIDNum getNumAtPos(LocIdx Idx) const { 375 assert(Idx.asU64() < LocIdxToIDNum.size()); 376 return LocIdxToIDNum[Idx]; 377 } 378 379 unsigned getNumLocs(void) const { return LocIdxToIDNum.size(); } 380 381 /// Reset all locations to contain a PHI value at the designated block. Used 382 /// sometimes for actual PHI values, othertimes to indicate the block entry 383 /// value (before any more information is known). 384 void setMPhis(unsigned NewCurBB) { 385 CurBB = NewCurBB; 386 for (auto Location : locations()) 387 Location.Value = {CurBB, 0, Location.Idx}; 388 } 389 390 /// Load values for each location from array of ValueIDNums. Take current 391 /// bbnum just in case we read a value from a hitherto untouched register. 392 void loadFromArray(ValueIDNum *Locs, unsigned NewCurBB) { 393 CurBB = NewCurBB; 394 // Iterate over all tracked locations, and load each locations live-in 395 // value into our local index. 396 for (auto Location : locations()) 397 Location.Value = Locs[Location.Idx.asU64()]; 398 } 399 400 /// Wipe any un-necessary location records after traversing a block. 401 void reset(void) { 402 // We could reset all the location values too; however either loadFromArray 403 // or setMPhis should be called before this object is re-used. Just 404 // clear Masks, they're definitely not needed. 405 Masks.clear(); 406 } 407 408 /// Clear all data. Destroys the LocID <=> LocIdx map, which makes most of 409 /// the information in this pass uninterpretable. 410 void clear(void) { 411 reset(); 412 LocIDToLocIdx.clear(); 413 LocIdxToLocID.clear(); 414 LocIdxToIDNum.clear(); 415 // SpillLocs.reset(); XXX UniqueVector::reset assumes a SpillLoc casts from 416 // 0 417 SpillLocs = decltype(SpillLocs)(); 418 419 LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc()); 420 } 421 422 /// Set a locaiton to a certain value. 423 void setMLoc(LocIdx L, ValueIDNum Num) { 424 assert(L.asU64() < LocIdxToIDNum.size()); 425 LocIdxToIDNum[L] = Num; 426 } 427 428 /// Create a LocIdx for an untracked register ID. Initialize it to either an 429 /// mphi value representing a live-in, or a recent register mask clobber. 430 LocIdx trackRegister(unsigned ID); 431 432 LocIdx lookupOrTrackRegister(unsigned ID) { 433 LocIdx &Index = LocIDToLocIdx[ID]; 434 if (Index.isIllegal()) 435 Index = trackRegister(ID); 436 return Index; 437 } 438 439 /// Record a definition of the specified register at the given block / inst. 440 /// This doesn't take a ValueIDNum, because the definition and its location 441 /// are synonymous. 442 void defReg(Register R, unsigned BB, unsigned Inst) { 443 unsigned ID = getLocID(R, false); 444 LocIdx Idx = lookupOrTrackRegister(ID); 445 ValueIDNum ValueID = {BB, Inst, Idx}; 446 LocIdxToIDNum[Idx] = ValueID; 447 } 448 449 /// Set a register to a value number. To be used if the value number is 450 /// known in advance. 451 void setReg(Register R, ValueIDNum ValueID) { 452 unsigned ID = getLocID(R, false); 453 LocIdx Idx = lookupOrTrackRegister(ID); 454 LocIdxToIDNum[Idx] = ValueID; 455 } 456 457 ValueIDNum readReg(Register R) { 458 unsigned ID = getLocID(R, false); 459 LocIdx Idx = lookupOrTrackRegister(ID); 460 return LocIdxToIDNum[Idx]; 461 } 462 463 /// Reset a register value to zero / empty. Needed to replicate the 464 /// VarLoc implementation where a copy to/from a register effectively 465 /// clears the contents of the source register. (Values can only have one 466 /// machine location in VarLocBasedImpl). 467 void wipeRegister(Register R) { 468 unsigned ID = getLocID(R, false); 469 LocIdx Idx = LocIDToLocIdx[ID]; 470 LocIdxToIDNum[Idx] = ValueIDNum::EmptyValue; 471 } 472 473 /// Determine the LocIdx of an existing register. 474 LocIdx getRegMLoc(Register R) { 475 unsigned ID = getLocID(R, false); 476 return LocIDToLocIdx[ID]; 477 } 478 479 /// Record a RegMask operand being executed. Defs any register we currently 480 /// track, stores a pointer to the mask in case we have to account for it 481 /// later. 482 void writeRegMask(const MachineOperand *MO, unsigned CurBB, unsigned InstID); 483 484 /// Find LocIdx for SpillLoc \p L, creating a new one if it's not tracked. 485 LocIdx getOrTrackSpillLoc(SpillLoc L); 486 487 /// Set the value stored in a spill slot. 488 void setSpill(SpillLoc L, ValueIDNum ValueID) { 489 LocIdx Idx = getOrTrackSpillLoc(L); 490 LocIdxToIDNum[Idx] = ValueID; 491 } 492 493 /// Read whatever value is in a spill slot, or None if it isn't tracked. 494 Optional<ValueIDNum> readSpill(SpillLoc L) { 495 unsigned SpillID = SpillLocs.idFor(L); 496 if (SpillID == 0) 497 return None; 498 499 unsigned LocID = getLocID(SpillID, true); 500 LocIdx Idx = LocIDToLocIdx[LocID]; 501 return LocIdxToIDNum[Idx]; 502 } 503 504 /// Determine the LocIdx of a spill slot. Return None if it previously 505 /// hasn't had a value assigned. 506 Optional<LocIdx> getSpillMLoc(SpillLoc L) { 507 unsigned SpillID = SpillLocs.idFor(L); 508 if (SpillID == 0) 509 return None; 510 unsigned LocNo = getLocID(SpillID, true); 511 return LocIDToLocIdx[LocNo]; 512 } 513 514 /// Return true if Idx is a spill machine location. 515 bool isSpill(LocIdx Idx) const { return LocIdxToLocID[Idx] >= NumRegs; } 516 517 MLocIterator begin() { return MLocIterator(LocIdxToIDNum, 0); } 518 519 MLocIterator end() { 520 return MLocIterator(LocIdxToIDNum, LocIdxToIDNum.size()); 521 } 522 523 /// Return a range over all locations currently tracked. 524 iterator_range<MLocIterator> locations() { 525 return llvm::make_range(begin(), end()); 526 } 527 528 std::string LocIdxToName(LocIdx Idx) const; 529 530 std::string IDAsString(const ValueIDNum &Num) const; 531 532 #ifndef NDEBUG 533 LLVM_DUMP_METHOD void dump(); 534 535 LLVM_DUMP_METHOD void dump_mloc_map(); 536 #endif 537 538 /// Create a DBG_VALUE based on machine location \p MLoc. Qualify it with the 539 /// information in \pProperties, for variable Var. Don't insert it anywhere, 540 /// just return the builder for it. 541 MachineInstrBuilder emitLoc(Optional<LocIdx> MLoc, const DebugVariable &Var, 542 const DbgValueProperties &Properties); 543 }; 544 545 /// Types for recording sets of variable fragments that overlap. For a given 546 /// local variable, we record all other fragments of that variable that could 547 /// overlap it, to reduce search time. 548 using FragmentOfVar = 549 std::pair<const DILocalVariable *, DIExpression::FragmentInfo>; 550 using OverlapMap = 551 DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>; 552 553 // XXX XXX docs 554 class InstrRefBasedLDV : public LDVImpl { 555 private: 556 friend class ::InstrRefLDVTest; 557 558 using FragmentInfo = DIExpression::FragmentInfo; 559 using OptFragmentInfo = Optional<DIExpression::FragmentInfo>; 560 561 // Helper while building OverlapMap, a map of all fragments seen for a given 562 // DILocalVariable. 563 using VarToFragments = 564 DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>; 565 566 /// Machine location/value transfer function, a mapping of which locations 567 /// are assigned which new values. 568 using MLocTransferMap = std::map<LocIdx, ValueIDNum>; 569 570 /// Live in/out structure for the variable values: a per-block map of 571 /// variables to their values. XXX, better name? 572 using LiveIdxT = 573 DenseMap<const MachineBasicBlock *, DenseMap<DebugVariable, DbgValue> *>; 574 575 using VarAndLoc = std::pair<DebugVariable, DbgValue>; 576 577 /// Type for a live-in value: the predecessor block, and its value. 578 using InValueT = std::pair<MachineBasicBlock *, DbgValue *>; 579 580 /// Vector (per block) of a collection (inner smallvector) of live-ins. 581 /// Used as the result type for the variable value dataflow problem. 582 using LiveInsT = SmallVector<SmallVector<VarAndLoc, 8>, 8>; 583 584 const TargetRegisterInfo *TRI; 585 const TargetInstrInfo *TII; 586 const TargetFrameLowering *TFI; 587 const MachineFrameInfo *MFI; 588 BitVector CalleeSavedRegs; 589 LexicalScopes LS; 590 TargetPassConfig *TPC; 591 592 /// Object to track machine locations as we step through a block. Could 593 /// probably be a field rather than a pointer, as it's always used. 594 MLocTracker *MTracker; 595 596 /// Number of the current block LiveDebugValues is stepping through. 597 unsigned CurBB; 598 599 /// Number of the current instruction LiveDebugValues is evaluating. 600 unsigned CurInst; 601 602 /// Variable tracker -- listens to DBG_VALUEs occurring as InstrRefBasedImpl 603 /// steps through a block. Reads the values at each location from the 604 /// MLocTracker object. 605 VLocTracker *VTracker; 606 607 /// Tracker for transfers, listens to DBG_VALUEs and transfers of values 608 /// between locations during stepping, creates new DBG_VALUEs when values move 609 /// location. 610 TransferTracker *TTracker; 611 612 /// Blocks which are artificial, i.e. blocks which exclusively contain 613 /// instructions without DebugLocs, or with line 0 locations. 614 SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks; 615 616 // Mapping of blocks to and from their RPOT order. 617 DenseMap<unsigned int, MachineBasicBlock *> OrderToBB; 618 DenseMap<MachineBasicBlock *, unsigned int> BBToOrder; 619 DenseMap<unsigned, unsigned> BBNumToRPO; 620 621 /// Pair of MachineInstr, and its 1-based offset into the containing block. 622 using InstAndNum = std::pair<const MachineInstr *, unsigned>; 623 /// Map from debug instruction number to the MachineInstr labelled with that 624 /// number, and its location within the function. Used to transform 625 /// instruction numbers in DBG_INSTR_REFs into machine value numbers. 626 std::map<uint64_t, InstAndNum> DebugInstrNumToInstr; 627 628 /// Record of where we observed a DBG_PHI instruction. 629 class DebugPHIRecord { 630 public: 631 uint64_t InstrNum; ///< Instruction number of this DBG_PHI. 632 MachineBasicBlock *MBB; ///< Block where DBG_PHI occurred. 633 ValueIDNum ValueRead; ///< The value number read by the DBG_PHI. 634 LocIdx ReadLoc; ///< Register/Stack location the DBG_PHI reads. 635 636 operator unsigned() const { return InstrNum; } 637 }; 638 639 /// Map from instruction numbers defined by DBG_PHIs to a record of what that 640 /// DBG_PHI read and where. Populated and edited during the machine value 641 /// location problem -- we use LLVMs SSA Updater to fix changes by 642 /// optimizations that destroy PHI instructions. 643 SmallVector<DebugPHIRecord, 32> DebugPHINumToValue; 644 645 // Map of overlapping variable fragments. 646 OverlapMap OverlapFragments; 647 VarToFragments SeenFragments; 648 649 /// Tests whether this instruction is a spill to a stack slot. 650 bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF); 651 652 /// Decide if @MI is a spill instruction and return true if it is. We use 2 653 /// criteria to make this decision: 654 /// - Is this instruction a store to a spill slot? 655 /// - Is there a register operand that is both used and killed? 656 /// TODO: Store optimization can fold spills into other stores (including 657 /// other spills). We do not handle this yet (more than one memory operand). 658 bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF, 659 unsigned &Reg); 660 661 /// If a given instruction is identified as a spill, return the spill slot 662 /// and set \p Reg to the spilled register. 663 Optional<SpillLoc> isRestoreInstruction(const MachineInstr &MI, 664 MachineFunction *MF, unsigned &Reg); 665 666 /// Given a spill instruction, extract the register and offset used to 667 /// address the spill slot in a target independent way. 668 SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI); 669 670 /// Observe a single instruction while stepping through a block. 671 void process(MachineInstr &MI, ValueIDNum **MLiveOuts = nullptr, 672 ValueIDNum **MLiveIns = nullptr); 673 674 /// Examines whether \p MI is a DBG_VALUE and notifies trackers. 675 /// \returns true if MI was recognized and processed. 676 bool transferDebugValue(const MachineInstr &MI); 677 678 /// Examines whether \p MI is a DBG_INSTR_REF and notifies trackers. 679 /// \returns true if MI was recognized and processed. 680 bool transferDebugInstrRef(MachineInstr &MI, ValueIDNum **MLiveOuts, 681 ValueIDNum **MLiveIns); 682 683 /// Stores value-information about where this PHI occurred, and what 684 /// instruction number is associated with it. 685 /// \returns true if MI was recognized and processed. 686 bool transferDebugPHI(MachineInstr &MI); 687 688 /// Examines whether \p MI is copy instruction, and notifies trackers. 689 /// \returns true if MI was recognized and processed. 690 bool transferRegisterCopy(MachineInstr &MI); 691 692 /// Examines whether \p MI is stack spill or restore instruction, and 693 /// notifies trackers. \returns true if MI was recognized and processed. 694 bool transferSpillOrRestoreInst(MachineInstr &MI); 695 696 /// Examines \p MI for any registers that it defines, and notifies trackers. 697 void transferRegisterDef(MachineInstr &MI); 698 699 /// Copy one location to the other, accounting for movement of subregisters 700 /// too. 701 void performCopy(Register Src, Register Dst); 702 703 void accumulateFragmentMap(MachineInstr &MI); 704 705 /// Determine the machine value number referred to by (potentially several) 706 /// DBG_PHI instructions. Block duplication and tail folding can duplicate 707 /// DBG_PHIs, shifting the position where values in registers merge, and 708 /// forming another mini-ssa problem to solve. 709 /// \p Here the position of a DBG_INSTR_REF seeking a machine value number 710 /// \p InstrNum Debug instruction number defined by DBG_PHI instructions. 711 /// \returns The machine value number at position Here, or None. 712 Optional<ValueIDNum> resolveDbgPHIs(MachineFunction &MF, 713 ValueIDNum **MLiveOuts, 714 ValueIDNum **MLiveIns, MachineInstr &Here, 715 uint64_t InstrNum); 716 717 /// Step through the function, recording register definitions and movements 718 /// in an MLocTracker. Convert the observations into a per-block transfer 719 /// function in \p MLocTransfer, suitable for using with the machine value 720 /// location dataflow problem. 721 void 722 produceMLocTransferFunction(MachineFunction &MF, 723 SmallVectorImpl<MLocTransferMap> &MLocTransfer, 724 unsigned MaxNumBlocks); 725 726 /// Solve the machine value location dataflow problem. Takes as input the 727 /// transfer functions in \p MLocTransfer. Writes the output live-in and 728 /// live-out arrays to the (initialized to zero) multidimensional arrays in 729 /// \p MInLocs and \p MOutLocs. The outer dimension is indexed by block 730 /// number, the inner by LocIdx. 731 void mlocDataflow(ValueIDNum **MInLocs, ValueIDNum **MOutLocs, 732 SmallVectorImpl<MLocTransferMap> &MLocTransfer); 733 734 /// Perform a control flow join (lattice value meet) of the values in machine 735 /// locations at \p MBB. Follows the algorithm described in the file-comment, 736 /// reading live-outs of predecessors from \p OutLocs, the current live ins 737 /// from \p InLocs, and assigning the newly computed live ins back into 738 /// \p InLocs. \returns two bools -- the first indicates whether a change 739 /// was made, the second whether a lattice downgrade occurred. If the latter 740 /// is true, revisiting this block is necessary. 741 std::tuple<bool, bool> 742 mlocJoin(MachineBasicBlock &MBB, 743 SmallPtrSet<const MachineBasicBlock *, 16> &Visited, 744 ValueIDNum **OutLocs, ValueIDNum *InLocs); 745 746 /// Solve the variable value dataflow problem, for a single lexical scope. 747 /// Uses the algorithm from the file comment to resolve control flow joins, 748 /// although there are extra hacks, see vlocJoin. Reads the 749 /// locations of values from the \p MInLocs and \p MOutLocs arrays (see 750 /// mlocDataflow) and reads the variable values transfer function from 751 /// \p AllTheVlocs. Live-in and Live-out variable values are stored locally, 752 /// with the live-ins permanently stored to \p Output once the fixedpoint is 753 /// reached. 754 /// \p VarsWeCareAbout contains a collection of the variables in \p Scope 755 /// that we should be tracking. 756 /// \p AssignBlocks contains the set of blocks that aren't in \p Scope, but 757 /// which do contain DBG_VALUEs, which VarLocBasedImpl tracks locations 758 /// through. 759 void vlocDataflow(const LexicalScope *Scope, const DILocation *DILoc, 760 const SmallSet<DebugVariable, 4> &VarsWeCareAbout, 761 SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, 762 LiveInsT &Output, ValueIDNum **MOutLocs, 763 ValueIDNum **MInLocs, 764 SmallVectorImpl<VLocTracker> &AllTheVLocs); 765 766 /// Compute the live-ins to a block, considering control flow merges according 767 /// to the method in the file comment. Live out and live in variable values 768 /// are stored in \p VLOCOutLocs and \p VLOCInLocs. The live-ins for \p MBB 769 /// are computed and stored into \p VLOCInLocs. \returns true if the live-ins 770 /// are modified. 771 /// \p InLocsT Output argument, storage for calculated live-ins. 772 /// \returns two bools -- the first indicates whether a change 773 /// was made, the second whether a lattice downgrade occurred. If the latter 774 /// is true, revisiting this block is necessary. 775 std::tuple<bool, bool> 776 vlocJoin(MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs, LiveIdxT &VLOCInLocs, 777 SmallPtrSet<const MachineBasicBlock *, 16> *VLOCVisited, 778 unsigned BBNum, const SmallSet<DebugVariable, 4> &AllVars, 779 ValueIDNum **MOutLocs, ValueIDNum **MInLocs, 780 SmallPtrSet<const MachineBasicBlock *, 8> &InScopeBlocks, 781 SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore, 782 DenseMap<DebugVariable, DbgValue> &InLocsT); 783 784 /// Continue exploration of the variable-value lattice, as explained in the 785 /// file-level comment. \p OldLiveInLocation contains the current 786 /// exploration position, from which we need to descend further. \p Values 787 /// contains the set of live-in values, \p CurBlockRPONum the RPO number of 788 /// the current block, and \p CandidateLocations a set of locations that 789 /// should be considered as PHI locations, if we reach the bottom of the 790 /// lattice. \returns true if we should downgrade; the value is the agreeing 791 /// value number in a non-backedge predecessor. 792 bool vlocDowngradeLattice(const MachineBasicBlock &MBB, 793 const DbgValue &OldLiveInLocation, 794 const SmallVectorImpl<InValueT> &Values, 795 unsigned CurBlockRPONum); 796 797 /// For the given block and live-outs feeding into it, try to find a 798 /// machine location where they all join. If a solution for all predecessors 799 /// can't be found, a location where all non-backedge-predecessors join 800 /// will be returned instead. While this method finds a join location, this 801 /// says nothing as to whether it should be used. 802 /// \returns Pair of value ID if found, and true when the correct value 803 /// is available on all predecessor edges, or false if it's only available 804 /// for non-backedge predecessors. 805 std::tuple<Optional<ValueIDNum>, bool> 806 pickVPHILoc(MachineBasicBlock &MBB, const DebugVariable &Var, 807 const LiveIdxT &LiveOuts, ValueIDNum **MOutLocs, 808 ValueIDNum **MInLocs, 809 const SmallVectorImpl<MachineBasicBlock *> &BlockOrders); 810 811 /// Given the solutions to the two dataflow problems, machine value locations 812 /// in \p MInLocs and live-in variable values in \p SavedLiveIns, runs the 813 /// TransferTracker class over the function to produce live-in and transfer 814 /// DBG_VALUEs, then inserts them. Groups of DBG_VALUEs are inserted in the 815 /// order given by AllVarsNumbering -- this could be any stable order, but 816 /// right now "order of appearence in function, when explored in RPO", so 817 /// that we can compare explictly against VarLocBasedImpl. 818 void emitLocations(MachineFunction &MF, LiveInsT SavedLiveIns, 819 ValueIDNum **MOutLocs, ValueIDNum **MInLocs, 820 DenseMap<DebugVariable, unsigned> &AllVarsNumbering, 821 const TargetPassConfig &TPC); 822 823 /// Boilerplate computation of some initial sets, artifical blocks and 824 /// RPOT block ordering. 825 void initialSetup(MachineFunction &MF); 826 827 bool ExtendRanges(MachineFunction &MF, TargetPassConfig *TPC, 828 unsigned InputBBLimit, unsigned InputDbgValLimit) override; 829 830 public: 831 /// Default construct and initialize the pass. 832 InstrRefBasedLDV(); 833 834 LLVM_DUMP_METHOD 835 void dump_mloc_transfer(const MLocTransferMap &mloc_transfer) const; 836 837 bool isCalleeSaved(LocIdx L) const; 838 }; 839 840 } // namespace LiveDebugValues 841 842 #endif /* LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H */ 843