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 TransferTracker; 29 30 // Forward dec of unit test class, so that we can peer into the LDV object. 31 class InstrRefLDVTest; 32 33 namespace LiveDebugValues { 34 35 class MLocTracker; 36 37 using namespace llvm; 38 39 /// Handle-class for a particular "location". This value-type uniquely 40 /// symbolises a register or stack location, allowing manipulation of locations 41 /// without concern for where that location is. Practically, this allows us to 42 /// treat the state of the machine at a particular point as an array of values, 43 /// rather than a map of values. 44 class LocIdx { 45 unsigned Location; 46 47 // Default constructor is private, initializing to an illegal location number. 48 // Use only for "not an entry" elements in IndexedMaps. 49 LocIdx() : Location(UINT_MAX) {} 50 51 public: 52 #define NUM_LOC_BITS 24 53 LocIdx(unsigned L) : Location(L) { 54 assert(L < (1 << NUM_LOC_BITS) && "Machine locations must fit in 24 bits"); 55 } 56 57 static LocIdx MakeIllegalLoc() { return LocIdx(); } 58 static LocIdx MakeTombstoneLoc() { 59 LocIdx L = LocIdx(); 60 --L.Location; 61 return L; 62 } 63 64 bool isIllegal() const { return Location == UINT_MAX; } 65 66 uint64_t asU64() const { return Location; } 67 68 bool operator==(unsigned L) const { return Location == L; } 69 70 bool operator==(const LocIdx &L) const { return Location == L.Location; } 71 72 bool operator!=(unsigned L) const { return !(*this == L); } 73 74 bool operator!=(const LocIdx &L) const { return !(*this == L); } 75 76 bool operator<(const LocIdx &Other) const { 77 return Location < Other.Location; 78 } 79 }; 80 81 // The location at which a spilled value resides. It consists of a register and 82 // an offset. 83 struct SpillLoc { 84 unsigned SpillBase; 85 StackOffset SpillOffset; 86 bool operator==(const SpillLoc &Other) const { 87 return std::make_pair(SpillBase, SpillOffset) == 88 std::make_pair(Other.SpillBase, Other.SpillOffset); 89 } 90 bool operator<(const SpillLoc &Other) const { 91 return std::make_tuple(SpillBase, SpillOffset.getFixed(), 92 SpillOffset.getScalable()) < 93 std::make_tuple(Other.SpillBase, Other.SpillOffset.getFixed(), 94 Other.SpillOffset.getScalable()); 95 } 96 }; 97 98 /// Unique identifier for a value defined by an instruction, as a value type. 99 /// Casts back and forth to a uint64_t. Probably replacable with something less 100 /// bit-constrained. Each value identifies the instruction and machine location 101 /// where the value is defined, although there may be no corresponding machine 102 /// operand for it (ex: regmasks clobbering values). The instructions are 103 /// one-based, and definitions that are PHIs have instruction number zero. 104 /// 105 /// The obvious limits of a 1M block function or 1M instruction blocks are 106 /// problematic; but by that point we should probably have bailed out of 107 /// trying to analyse the function. 108 class ValueIDNum { 109 union { 110 struct { 111 uint64_t BlockNo : 20; /// The block where the def happens. 112 uint64_t InstNo : 20; /// The Instruction where the def happens. 113 /// One based, is distance from start of block. 114 uint64_t LocNo 115 : NUM_LOC_BITS; /// The machine location where the def happens. 116 } s; 117 uint64_t Value; 118 } u; 119 120 static_assert(sizeof(u) == 8, "Badly packed ValueIDNum?"); 121 122 public: 123 // Default-initialize to EmptyValue. This is necessary to make IndexedMaps 124 // of values to work. 125 ValueIDNum() { u.Value = EmptyValue.asU64(); } 126 127 ValueIDNum(uint64_t Block, uint64_t Inst, uint64_t Loc) { 128 u.s = {Block, Inst, Loc}; 129 } 130 131 ValueIDNum(uint64_t Block, uint64_t Inst, LocIdx Loc) { 132 u.s = {Block, Inst, Loc.asU64()}; 133 } 134 135 ValueIDNum &operator=(const ValueIDNum &Other) { 136 u.Value = Other.u.Value; 137 return *this; 138 } 139 140 uint64_t getBlock() const { return u.s.BlockNo; } 141 uint64_t getInst() const { return u.s.InstNo; } 142 uint64_t getLoc() const { return u.s.LocNo; } 143 bool isPHI() const { return u.s.InstNo == 0; } 144 145 uint64_t asU64() const { return u.Value; } 146 147 static ValueIDNum fromU64(uint64_t v) { 148 ValueIDNum Val; 149 Val.u.Value = v; 150 return Val; 151 } 152 153 bool operator<(const ValueIDNum &Other) const { 154 return asU64() < Other.asU64(); 155 } 156 157 bool operator==(const ValueIDNum &Other) const { 158 return u.Value == Other.u.Value; 159 } 160 161 bool operator!=(const ValueIDNum &Other) const { return !(*this == Other); } 162 163 std::string asString(const std::string &mlocname) const { 164 return Twine("Value{bb: ") 165 .concat(Twine(u.s.BlockNo) 166 .concat(Twine(", inst: ") 167 .concat((u.s.InstNo ? Twine(u.s.InstNo) 168 : Twine("live-in")) 169 .concat(Twine(", loc: ").concat( 170 Twine(mlocname))) 171 .concat(Twine("}"))))) 172 .str(); 173 } 174 175 static ValueIDNum EmptyValue; 176 static ValueIDNum TombstoneValue; 177 }; 178 179 /// Thin wrapper around an integer -- designed to give more type safety to 180 /// spill location numbers. 181 class SpillLocationNo { 182 public: 183 explicit SpillLocationNo(unsigned SpillNo) : SpillNo(SpillNo) {} 184 unsigned SpillNo; 185 unsigned id() const { return SpillNo; } 186 187 bool operator<(const SpillLocationNo &Other) const { 188 return SpillNo < Other.SpillNo; 189 } 190 191 bool operator==(const SpillLocationNo &Other) const { 192 return SpillNo == Other.SpillNo; 193 } 194 bool operator!=(const SpillLocationNo &Other) const { 195 return !(*this == Other); 196 } 197 }; 198 199 /// Meta qualifiers for a value. Pair of whatever expression is used to qualify 200 /// the the value, and Boolean of whether or not it's indirect. 201 class DbgValueProperties { 202 public: 203 DbgValueProperties(const DIExpression *DIExpr, bool Indirect) 204 : DIExpr(DIExpr), Indirect(Indirect) {} 205 206 /// Extract properties from an existing DBG_VALUE instruction. 207 DbgValueProperties(const MachineInstr &MI) { 208 assert(MI.isDebugValue()); 209 DIExpr = MI.getDebugExpression(); 210 Indirect = MI.getOperand(1).isImm(); 211 } 212 213 bool operator==(const DbgValueProperties &Other) const { 214 return std::tie(DIExpr, Indirect) == std::tie(Other.DIExpr, Other.Indirect); 215 } 216 217 bool operator!=(const DbgValueProperties &Other) const { 218 return !(*this == Other); 219 } 220 221 const DIExpression *DIExpr; 222 bool Indirect; 223 }; 224 225 /// Class recording the (high level) _value_ of a variable. Identifies either 226 /// the value of the variable as a ValueIDNum, or a constant MachineOperand. 227 /// This class also stores meta-information about how the value is qualified. 228 /// Used to reason about variable values when performing the second 229 /// (DebugVariable specific) dataflow analysis. 230 class DbgValue { 231 public: 232 /// If Kind is Def, the value number that this value is based on. VPHIs set 233 /// this field to EmptyValue if there is no machine-value for this VPHI, or 234 /// the corresponding machine-value if there is one. 235 ValueIDNum ID; 236 /// If Kind is Const, the MachineOperand defining this value. 237 Optional<MachineOperand> MO; 238 /// For a NoVal or VPHI DbgValue, which block it was generated in. 239 int BlockNo; 240 241 /// Qualifiers for the ValueIDNum above. 242 DbgValueProperties Properties; 243 244 typedef enum { 245 Undef, // Represents a DBG_VALUE $noreg in the transfer function only. 246 Def, // This value is defined by an inst, or is a PHI value. 247 Const, // A constant value contained in the MachineOperand field. 248 VPHI, // Incoming values to BlockNo differ, those values must be joined by 249 // a PHI in this block. 250 NoVal, // Empty DbgValue indicating an unknown value. Used as initializer, 251 // before dominating blocks values are propagated in. 252 } KindT; 253 /// Discriminator for whether this is a constant or an in-program value. 254 KindT Kind; 255 256 DbgValue(const ValueIDNum &Val, const DbgValueProperties &Prop, KindT Kind) 257 : ID(Val), MO(None), BlockNo(0), Properties(Prop), Kind(Kind) { 258 assert(Kind == Def); 259 } 260 261 DbgValue(unsigned BlockNo, const DbgValueProperties &Prop, KindT Kind) 262 : ID(ValueIDNum::EmptyValue), MO(None), BlockNo(BlockNo), 263 Properties(Prop), Kind(Kind) { 264 assert(Kind == NoVal || Kind == VPHI); 265 } 266 267 DbgValue(const MachineOperand &MO, const DbgValueProperties &Prop, KindT Kind) 268 : ID(ValueIDNum::EmptyValue), MO(MO), BlockNo(0), Properties(Prop), 269 Kind(Kind) { 270 assert(Kind == Const); 271 } 272 273 DbgValue(const DbgValueProperties &Prop, KindT Kind) 274 : ID(ValueIDNum::EmptyValue), MO(None), BlockNo(0), Properties(Prop), 275 Kind(Kind) { 276 assert(Kind == Undef && 277 "Empty DbgValue constructor must pass in Undef kind"); 278 } 279 280 #ifndef NDEBUG 281 void dump(const MLocTracker *MTrack) const; 282 #endif 283 284 bool operator==(const DbgValue &Other) const { 285 if (std::tie(Kind, Properties) != std::tie(Other.Kind, Other.Properties)) 286 return false; 287 else if (Kind == Def && ID != Other.ID) 288 return false; 289 else if (Kind == NoVal && BlockNo != Other.BlockNo) 290 return false; 291 else if (Kind == Const) 292 return MO->isIdenticalTo(*Other.MO); 293 else if (Kind == VPHI && BlockNo != Other.BlockNo) 294 return false; 295 else if (Kind == VPHI && ID != Other.ID) 296 return false; 297 298 return true; 299 } 300 301 bool operator!=(const DbgValue &Other) const { return !(*this == Other); } 302 }; 303 304 class LocIdxToIndexFunctor { 305 public: 306 using argument_type = LocIdx; 307 unsigned operator()(const LocIdx &L) const { return L.asU64(); } 308 }; 309 310 /// Tracker for what values are in machine locations. Listens to the Things 311 /// being Done by various instructions, and maintains a table of what machine 312 /// locations have what values (as defined by a ValueIDNum). 313 /// 314 /// There are potentially a much larger number of machine locations on the 315 /// target machine than the actual working-set size of the function. On x86 for 316 /// example, we're extremely unlikely to want to track values through control 317 /// or debug registers. To avoid doing so, MLocTracker has several layers of 318 /// indirection going on, described below, to avoid unnecessarily tracking 319 /// any location. 320 /// 321 /// Here's a sort of diagram of the indexes, read from the bottom up: 322 /// 323 /// Size on stack Offset on stack 324 /// \ / 325 /// Stack Idx (Where in slot is this?) 326 /// / 327 /// / 328 /// Slot Num (%stack.0) / 329 /// FrameIdx => SpillNum / 330 /// \ / 331 /// SpillID (int) Register number (int) 332 /// \ / 333 /// LocationID => LocIdx 334 /// | 335 /// LocIdx => ValueIDNum 336 /// 337 /// The aim here is that the LocIdx => ValueIDNum vector is just an array of 338 /// values in numbered locations, so that later analyses can ignore whether the 339 /// location is a register or otherwise. To map a register / spill location to 340 /// a LocIdx, you have to use the (sparse) LocationID => LocIdx map. And to 341 /// build a LocationID for a stack slot, you need to combine identifiers for 342 /// which stack slot it is and where within that slot is being described. 343 /// 344 /// Register mask operands cause trouble by technically defining every register; 345 /// various hacks are used to avoid tracking registers that are never read and 346 /// only written by regmasks. 347 class MLocTracker { 348 public: 349 MachineFunction &MF; 350 const TargetInstrInfo &TII; 351 const TargetRegisterInfo &TRI; 352 const TargetLowering &TLI; 353 354 /// IndexedMap type, mapping from LocIdx to ValueIDNum. 355 using LocToValueType = IndexedMap<ValueIDNum, LocIdxToIndexFunctor>; 356 357 /// Map of LocIdxes to the ValueIDNums that they store. This is tightly 358 /// packed, entries only exist for locations that are being tracked. 359 LocToValueType LocIdxToIDNum; 360 361 /// "Map" of machine location IDs (i.e., raw register or spill number) to the 362 /// LocIdx key / number for that location. There are always at least as many 363 /// as the number of registers on the target -- if the value in the register 364 /// is not being tracked, then the LocIdx value will be zero. New entries are 365 /// appended if a new spill slot begins being tracked. 366 /// This, and the corresponding reverse map persist for the analysis of the 367 /// whole function, and is necessarying for decoding various vectors of 368 /// values. 369 std::vector<LocIdx> LocIDToLocIdx; 370 371 /// Inverse map of LocIDToLocIdx. 372 IndexedMap<unsigned, LocIdxToIndexFunctor> LocIdxToLocID; 373 374 /// When clobbering register masks, we chose to not believe the machine model 375 /// and don't clobber SP. Do the same for SP aliases, and for efficiency, 376 /// keep a set of them here. 377 SmallSet<Register, 8> SPAliases; 378 379 /// Unique-ification of spill. Used to number them -- their LocID number is 380 /// the index in SpillLocs minus one plus NumRegs. 381 UniqueVector<SpillLoc> SpillLocs; 382 383 // If we discover a new machine location, assign it an mphi with this 384 // block number. 385 unsigned CurBB; 386 387 /// Cached local copy of the number of registers the target has. 388 unsigned NumRegs; 389 390 /// Number of slot indexes the target has -- distinct segments of a stack 391 /// slot that can take on the value of a subregister, when a super-register 392 /// is written to the stack. 393 unsigned NumSlotIdxes; 394 395 /// Collection of register mask operands that have been observed. Second part 396 /// of pair indicates the instruction that they happened in. Used to 397 /// reconstruct where defs happened if we start tracking a location later 398 /// on. 399 SmallVector<std::pair<const MachineOperand *, unsigned>, 32> Masks; 400 401 /// Pair for describing a position within a stack slot -- first the size in 402 /// bits, then the offset. 403 typedef std::pair<unsigned short, unsigned short> StackSlotPos; 404 405 /// Map from a size/offset pair describing a position in a stack slot, to a 406 /// numeric identifier for that position. Allows easier identification of 407 /// individual positions. 408 DenseMap<StackSlotPos, unsigned> StackSlotIdxes; 409 410 /// Inverse of StackSlotIdxes. 411 DenseMap<unsigned, StackSlotPos> StackIdxesToPos; 412 413 /// Iterator for locations and the values they contain. Dereferencing 414 /// produces a struct/pair containing the LocIdx key for this location, 415 /// and a reference to the value currently stored. Simplifies the process 416 /// of seeking a particular location. 417 class MLocIterator { 418 LocToValueType &ValueMap; 419 LocIdx Idx; 420 421 public: 422 class value_type { 423 public: 424 value_type(LocIdx Idx, ValueIDNum &Value) : Idx(Idx), Value(Value) {} 425 const LocIdx Idx; /// Read-only index of this location. 426 ValueIDNum &Value; /// Reference to the stored value at this location. 427 }; 428 429 MLocIterator(LocToValueType &ValueMap, LocIdx Idx) 430 : ValueMap(ValueMap), Idx(Idx) {} 431 432 bool operator==(const MLocIterator &Other) const { 433 assert(&ValueMap == &Other.ValueMap); 434 return Idx == Other.Idx; 435 } 436 437 bool operator!=(const MLocIterator &Other) const { 438 return !(*this == Other); 439 } 440 441 void operator++() { Idx = LocIdx(Idx.asU64() + 1); } 442 443 value_type operator*() { return value_type(Idx, ValueMap[LocIdx(Idx)]); } 444 }; 445 446 MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII, 447 const TargetRegisterInfo &TRI, const TargetLowering &TLI); 448 449 /// Produce location ID number for a Register. Provides some small amount of 450 /// type safety. 451 /// \param Reg The register we're looking up. 452 unsigned getLocID(Register Reg) { return Reg.id(); } 453 454 /// Produce location ID number for a spill position. 455 /// \param Spill The number of the spill we're fetching the location for. 456 /// \param SpillSubReg Subregister within the spill we're addressing. 457 unsigned getLocID(SpillLocationNo Spill, unsigned SpillSubReg) { 458 unsigned short Size = TRI.getSubRegIdxSize(SpillSubReg); 459 unsigned short Offs = TRI.getSubRegIdxOffset(SpillSubReg); 460 return getLocID(Spill, {Size, Offs}); 461 } 462 463 /// Produce location ID number for a spill position. 464 /// \param Spill The number of the spill we're fetching the location for. 465 /// \apram SpillIdx size/offset within the spill slot to be addressed. 466 unsigned getLocID(SpillLocationNo Spill, StackSlotPos Idx) { 467 unsigned SlotNo = Spill.id() - 1; 468 SlotNo *= NumSlotIdxes; 469 assert(StackSlotIdxes.find(Idx) != StackSlotIdxes.end()); 470 SlotNo += StackSlotIdxes[Idx]; 471 SlotNo += NumRegs; 472 return SlotNo; 473 } 474 475 /// Given a spill number, and a slot within the spill, calculate the ID number 476 /// for that location. 477 unsigned getSpillIDWithIdx(SpillLocationNo Spill, unsigned Idx) { 478 unsigned SlotNo = Spill.id() - 1; 479 SlotNo *= NumSlotIdxes; 480 SlotNo += Idx; 481 SlotNo += NumRegs; 482 return SlotNo; 483 } 484 485 /// Return the spill number that a location ID corresponds to. 486 SpillLocationNo locIDToSpill(unsigned ID) const { 487 assert(ID >= NumRegs); 488 ID -= NumRegs; 489 // Truncate away the index part, leaving only the spill number. 490 ID /= NumSlotIdxes; 491 return SpillLocationNo(ID + 1); // The UniqueVector is one-based. 492 } 493 494 /// Returns the spill-slot size/offs that a location ID corresponds to. 495 StackSlotPos locIDToSpillIdx(unsigned ID) const { 496 assert(ID >= NumRegs); 497 ID -= NumRegs; 498 unsigned Idx = ID % NumSlotIdxes; 499 return StackIdxesToPos.find(Idx)->second; 500 } 501 502 unsigned getNumLocs() const { return LocIdxToIDNum.size(); } 503 504 /// Reset all locations to contain a PHI value at the designated block. Used 505 /// sometimes for actual PHI values, othertimes to indicate the block entry 506 /// value (before any more information is known). 507 void setMPhis(unsigned NewCurBB) { 508 CurBB = NewCurBB; 509 for (auto Location : locations()) 510 Location.Value = {CurBB, 0, Location.Idx}; 511 } 512 513 /// Load values for each location from array of ValueIDNums. Take current 514 /// bbnum just in case we read a value from a hitherto untouched register. 515 void loadFromArray(ValueIDNum *Locs, unsigned NewCurBB) { 516 CurBB = NewCurBB; 517 // Iterate over all tracked locations, and load each locations live-in 518 // value into our local index. 519 for (auto Location : locations()) 520 Location.Value = Locs[Location.Idx.asU64()]; 521 } 522 523 /// Wipe any un-necessary location records after traversing a block. 524 void reset() { 525 // We could reset all the location values too; however either loadFromArray 526 // or setMPhis should be called before this object is re-used. Just 527 // clear Masks, they're definitely not needed. 528 Masks.clear(); 529 } 530 531 /// Clear all data. Destroys the LocID <=> LocIdx map, which makes most of 532 /// the information in this pass uninterpretable. 533 void clear() { 534 reset(); 535 LocIDToLocIdx.clear(); 536 LocIdxToLocID.clear(); 537 LocIdxToIDNum.clear(); 538 // SpillLocs.reset(); XXX UniqueVector::reset assumes a SpillLoc casts from 539 // 0 540 SpillLocs = decltype(SpillLocs)(); 541 StackSlotIdxes.clear(); 542 StackIdxesToPos.clear(); 543 544 LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc()); 545 } 546 547 /// Set a locaiton to a certain value. 548 void setMLoc(LocIdx L, ValueIDNum Num) { 549 assert(L.asU64() < LocIdxToIDNum.size()); 550 LocIdxToIDNum[L] = Num; 551 } 552 553 /// Read the value of a particular location 554 ValueIDNum readMLoc(LocIdx L) { 555 assert(L.asU64() < LocIdxToIDNum.size()); 556 return LocIdxToIDNum[L]; 557 } 558 559 /// Create a LocIdx for an untracked register ID. Initialize it to either an 560 /// mphi value representing a live-in, or a recent register mask clobber. 561 LocIdx trackRegister(unsigned ID); 562 563 LocIdx lookupOrTrackRegister(unsigned ID) { 564 LocIdx &Index = LocIDToLocIdx[ID]; 565 if (Index.isIllegal()) 566 Index = trackRegister(ID); 567 return Index; 568 } 569 570 /// Is register R currently tracked by MLocTracker? 571 bool isRegisterTracked(Register R) { 572 LocIdx &Index = LocIDToLocIdx[R]; 573 return !Index.isIllegal(); 574 } 575 576 /// Record a definition of the specified register at the given block / inst. 577 /// This doesn't take a ValueIDNum, because the definition and its location 578 /// are synonymous. 579 void defReg(Register R, unsigned BB, unsigned Inst) { 580 unsigned ID = getLocID(R); 581 LocIdx Idx = lookupOrTrackRegister(ID); 582 ValueIDNum ValueID = {BB, Inst, Idx}; 583 LocIdxToIDNum[Idx] = ValueID; 584 } 585 586 /// Set a register to a value number. To be used if the value number is 587 /// known in advance. 588 void setReg(Register R, ValueIDNum ValueID) { 589 unsigned ID = getLocID(R); 590 LocIdx Idx = lookupOrTrackRegister(ID); 591 LocIdxToIDNum[Idx] = ValueID; 592 } 593 594 ValueIDNum readReg(Register R) { 595 unsigned ID = getLocID(R); 596 LocIdx Idx = lookupOrTrackRegister(ID); 597 return LocIdxToIDNum[Idx]; 598 } 599 600 /// Reset a register value to zero / empty. Needed to replicate the 601 /// VarLoc implementation where a copy to/from a register effectively 602 /// clears the contents of the source register. (Values can only have one 603 /// machine location in VarLocBasedImpl). 604 void wipeRegister(Register R) { 605 unsigned ID = getLocID(R); 606 LocIdx Idx = LocIDToLocIdx[ID]; 607 LocIdxToIDNum[Idx] = ValueIDNum::EmptyValue; 608 } 609 610 /// Determine the LocIdx of an existing register. 611 LocIdx getRegMLoc(Register R) { 612 unsigned ID = getLocID(R); 613 assert(ID < LocIDToLocIdx.size()); 614 assert(LocIDToLocIdx[ID] != UINT_MAX); // Sentinal for IndexedMap. 615 return LocIDToLocIdx[ID]; 616 } 617 618 /// Record a RegMask operand being executed. Defs any register we currently 619 /// track, stores a pointer to the mask in case we have to account for it 620 /// later. 621 void writeRegMask(const MachineOperand *MO, unsigned CurBB, unsigned InstID); 622 623 /// Find LocIdx for SpillLoc \p L, creating a new one if it's not tracked. 624 SpillLocationNo getOrTrackSpillLoc(SpillLoc L); 625 626 // Get LocIdx of a spill ID. 627 LocIdx getSpillMLoc(unsigned SpillID) { 628 assert(LocIDToLocIdx[SpillID] != UINT_MAX); // Sentinal for IndexedMap. 629 return LocIDToLocIdx[SpillID]; 630 } 631 632 /// Return true if Idx is a spill machine location. 633 bool isSpill(LocIdx Idx) const { return LocIdxToLocID[Idx] >= NumRegs; } 634 635 MLocIterator begin() { return MLocIterator(LocIdxToIDNum, 0); } 636 637 MLocIterator end() { 638 return MLocIterator(LocIdxToIDNum, LocIdxToIDNum.size()); 639 } 640 641 /// Return a range over all locations currently tracked. 642 iterator_range<MLocIterator> locations() { 643 return llvm::make_range(begin(), end()); 644 } 645 646 std::string LocIdxToName(LocIdx Idx) const; 647 648 std::string IDAsString(const ValueIDNum &Num) const; 649 650 #ifndef NDEBUG 651 LLVM_DUMP_METHOD void dump(); 652 653 LLVM_DUMP_METHOD void dump_mloc_map(); 654 #endif 655 656 /// Create a DBG_VALUE based on machine location \p MLoc. Qualify it with the 657 /// information in \pProperties, for variable Var. Don't insert it anywhere, 658 /// just return the builder for it. 659 MachineInstrBuilder emitLoc(Optional<LocIdx> MLoc, const DebugVariable &Var, 660 const DbgValueProperties &Properties); 661 }; 662 663 /// Types for recording sets of variable fragments that overlap. For a given 664 /// local variable, we record all other fragments of that variable that could 665 /// overlap it, to reduce search time. 666 using FragmentOfVar = 667 std::pair<const DILocalVariable *, DIExpression::FragmentInfo>; 668 using OverlapMap = 669 DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>; 670 671 /// Collection of DBG_VALUEs observed when traversing a block. Records each 672 /// variable and the value the DBG_VALUE refers to. Requires the machine value 673 /// location dataflow algorithm to have run already, so that values can be 674 /// identified. 675 class VLocTracker { 676 public: 677 /// Map DebugVariable to the latest Value it's defined to have. 678 /// Needs to be a MapVector because we determine order-in-the-input-MIR from 679 /// the order in this container. 680 /// We only retain the last DbgValue in each block for each variable, to 681 /// determine the blocks live-out variable value. The Vars container forms the 682 /// transfer function for this block, as part of the dataflow analysis. The 683 /// movement of values between locations inside of a block is handled at a 684 /// much later stage, in the TransferTracker class. 685 MapVector<DebugVariable, DbgValue> Vars; 686 DenseMap<DebugVariable, const DILocation *> Scopes; 687 MachineBasicBlock *MBB = nullptr; 688 const OverlapMap &OverlappingFragments; 689 DbgValueProperties EmptyProperties; 690 691 public: 692 VLocTracker(const OverlapMap &O, const DIExpression *EmptyExpr) 693 : OverlappingFragments(O), EmptyProperties(EmptyExpr, false) {} 694 695 void defVar(const MachineInstr &MI, const DbgValueProperties &Properties, 696 Optional<ValueIDNum> ID) { 697 assert(MI.isDebugValue() || MI.isDebugRef()); 698 DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(), 699 MI.getDebugLoc()->getInlinedAt()); 700 DbgValue Rec = (ID) ? DbgValue(*ID, Properties, DbgValue::Def) 701 : DbgValue(Properties, DbgValue::Undef); 702 703 // Attempt insertion; overwrite if it's already mapped. 704 auto Result = Vars.insert(std::make_pair(Var, Rec)); 705 if (!Result.second) 706 Result.first->second = Rec; 707 Scopes[Var] = MI.getDebugLoc().get(); 708 709 considerOverlaps(Var, MI.getDebugLoc().get()); 710 } 711 712 void defVar(const MachineInstr &MI, const MachineOperand &MO) { 713 // Only DBG_VALUEs can define constant-valued variables. 714 assert(MI.isDebugValue()); 715 DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(), 716 MI.getDebugLoc()->getInlinedAt()); 717 DbgValueProperties Properties(MI); 718 DbgValue Rec = DbgValue(MO, Properties, DbgValue::Const); 719 720 // Attempt insertion; overwrite if it's already mapped. 721 auto Result = Vars.insert(std::make_pair(Var, Rec)); 722 if (!Result.second) 723 Result.first->second = Rec; 724 Scopes[Var] = MI.getDebugLoc().get(); 725 726 considerOverlaps(Var, MI.getDebugLoc().get()); 727 } 728 729 void considerOverlaps(const DebugVariable &Var, const DILocation *Loc) { 730 auto Overlaps = OverlappingFragments.find( 731 {Var.getVariable(), Var.getFragmentOrDefault()}); 732 if (Overlaps == OverlappingFragments.end()) 733 return; 734 735 // Otherwise: terminate any overlapped variable locations. 736 for (auto FragmentInfo : Overlaps->second) { 737 // The "empty" fragment is stored as DebugVariable::DefaultFragment, so 738 // that it overlaps with everything, however its cannonical representation 739 // in a DebugVariable is as "None". 740 Optional<DIExpression::FragmentInfo> OptFragmentInfo = FragmentInfo; 741 if (DebugVariable::isDefaultFragment(FragmentInfo)) 742 OptFragmentInfo = None; 743 744 DebugVariable Overlapped(Var.getVariable(), OptFragmentInfo, 745 Var.getInlinedAt()); 746 DbgValue Rec = DbgValue(EmptyProperties, DbgValue::Undef); 747 748 // Attempt insertion; overwrite if it's already mapped. 749 auto Result = Vars.insert(std::make_pair(Overlapped, Rec)); 750 if (!Result.second) 751 Result.first->second = Rec; 752 Scopes[Overlapped] = Loc; 753 } 754 } 755 }; 756 757 // XXX XXX docs 758 class InstrRefBasedLDV : public LDVImpl { 759 public: 760 friend class ::InstrRefLDVTest; 761 762 using FragmentInfo = DIExpression::FragmentInfo; 763 using OptFragmentInfo = Optional<DIExpression::FragmentInfo>; 764 765 // Helper while building OverlapMap, a map of all fragments seen for a given 766 // DILocalVariable. 767 using VarToFragments = 768 DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>; 769 770 /// Machine location/value transfer function, a mapping of which locations 771 /// are assigned which new values. 772 using MLocTransferMap = SmallDenseMap<LocIdx, ValueIDNum>; 773 774 /// Live in/out structure for the variable values: a per-block map of 775 /// variables to their values. 776 using LiveIdxT = DenseMap<const MachineBasicBlock *, DbgValue *>; 777 778 using VarAndLoc = std::pair<DebugVariable, DbgValue>; 779 780 /// Type for a live-in value: the predecessor block, and its value. 781 using InValueT = std::pair<MachineBasicBlock *, DbgValue *>; 782 783 /// Vector (per block) of a collection (inner smallvector) of live-ins. 784 /// Used as the result type for the variable value dataflow problem. 785 using LiveInsT = SmallVector<SmallVector<VarAndLoc, 8>, 8>; 786 787 private: 788 MachineDominatorTree *DomTree; 789 const TargetRegisterInfo *TRI; 790 const MachineRegisterInfo *MRI; 791 const TargetInstrInfo *TII; 792 const TargetFrameLowering *TFI; 793 const MachineFrameInfo *MFI; 794 BitVector CalleeSavedRegs; 795 LexicalScopes LS; 796 TargetPassConfig *TPC; 797 798 // An empty DIExpression. Used default / placeholder DbgValueProperties 799 // objects, as we can't have null expressions. 800 const DIExpression *EmptyExpr; 801 802 /// Object to track machine locations as we step through a block. Could 803 /// probably be a field rather than a pointer, as it's always used. 804 MLocTracker *MTracker = nullptr; 805 806 /// Number of the current block LiveDebugValues is stepping through. 807 unsigned CurBB; 808 809 /// Number of the current instruction LiveDebugValues is evaluating. 810 unsigned CurInst; 811 812 /// Variable tracker -- listens to DBG_VALUEs occurring as InstrRefBasedImpl 813 /// steps through a block. Reads the values at each location from the 814 /// MLocTracker object. 815 VLocTracker *VTracker = nullptr; 816 817 /// Tracker for transfers, listens to DBG_VALUEs and transfers of values 818 /// between locations during stepping, creates new DBG_VALUEs when values move 819 /// location. 820 TransferTracker *TTracker = nullptr; 821 822 /// Blocks which are artificial, i.e. blocks which exclusively contain 823 /// instructions without DebugLocs, or with line 0 locations. 824 SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks; 825 826 // Mapping of blocks to and from their RPOT order. 827 DenseMap<unsigned int, MachineBasicBlock *> OrderToBB; 828 DenseMap<const MachineBasicBlock *, unsigned int> BBToOrder; 829 DenseMap<unsigned, unsigned> BBNumToRPO; 830 831 /// Pair of MachineInstr, and its 1-based offset into the containing block. 832 using InstAndNum = std::pair<const MachineInstr *, unsigned>; 833 /// Map from debug instruction number to the MachineInstr labelled with that 834 /// number, and its location within the function. Used to transform 835 /// instruction numbers in DBG_INSTR_REFs into machine value numbers. 836 std::map<uint64_t, InstAndNum> DebugInstrNumToInstr; 837 838 /// Record of where we observed a DBG_PHI instruction. 839 class DebugPHIRecord { 840 public: 841 uint64_t InstrNum; ///< Instruction number of this DBG_PHI. 842 MachineBasicBlock *MBB; ///< Block where DBG_PHI occurred. 843 ValueIDNum ValueRead; ///< The value number read by the DBG_PHI. 844 LocIdx ReadLoc; ///< Register/Stack location the DBG_PHI reads. 845 846 operator unsigned() const { return InstrNum; } 847 }; 848 849 /// Map from instruction numbers defined by DBG_PHIs to a record of what that 850 /// DBG_PHI read and where. Populated and edited during the machine value 851 /// location problem -- we use LLVMs SSA Updater to fix changes by 852 /// optimizations that destroy PHI instructions. 853 SmallVector<DebugPHIRecord, 32> DebugPHINumToValue; 854 855 // Map of overlapping variable fragments. 856 OverlapMap OverlapFragments; 857 VarToFragments SeenFragments; 858 859 /// True if we need to examine call instructions for stack clobbers. We 860 /// normally assume that they don't clobber SP, but stack probes on Windows 861 /// do. 862 bool AdjustsStackInCalls = false; 863 864 /// If AdjustsStackInCalls is true, this holds the name of the target's stack 865 /// probe function, which is the function we expect will alter the stack 866 /// pointer. 867 StringRef StackProbeSymbolName; 868 869 /// Tests whether this instruction is a spill to a stack slot. 870 bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF); 871 872 /// Decide if @MI is a spill instruction and return true if it is. We use 2 873 /// criteria to make this decision: 874 /// - Is this instruction a store to a spill slot? 875 /// - Is there a register operand that is both used and killed? 876 /// TODO: Store optimization can fold spills into other stores (including 877 /// other spills). We do not handle this yet (more than one memory operand). 878 bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF, 879 unsigned &Reg); 880 881 /// If a given instruction is identified as a spill, return the spill slot 882 /// and set \p Reg to the spilled register. 883 Optional<SpillLocationNo> isRestoreInstruction(const MachineInstr &MI, 884 MachineFunction *MF, unsigned &Reg); 885 886 /// Given a spill instruction, extract the spill slot information, ensure it's 887 /// tracked, and return the spill number. 888 SpillLocationNo extractSpillBaseRegAndOffset(const MachineInstr &MI); 889 890 /// Observe a single instruction while stepping through a block. 891 void process(MachineInstr &MI, ValueIDNum **MLiveOuts = nullptr, 892 ValueIDNum **MLiveIns = nullptr); 893 894 /// Examines whether \p MI is a DBG_VALUE and notifies trackers. 895 /// \returns true if MI was recognized and processed. 896 bool transferDebugValue(const MachineInstr &MI); 897 898 /// Examines whether \p MI is a DBG_INSTR_REF and notifies trackers. 899 /// \returns true if MI was recognized and processed. 900 bool transferDebugInstrRef(MachineInstr &MI, ValueIDNum **MLiveOuts, 901 ValueIDNum **MLiveIns); 902 903 /// Stores value-information about where this PHI occurred, and what 904 /// instruction number is associated with it. 905 /// \returns true if MI was recognized and processed. 906 bool transferDebugPHI(MachineInstr &MI); 907 908 /// Examines whether \p MI is copy instruction, and notifies trackers. 909 /// \returns true if MI was recognized and processed. 910 bool transferRegisterCopy(MachineInstr &MI); 911 912 /// Examines whether \p MI is stack spill or restore instruction, and 913 /// notifies trackers. \returns true if MI was recognized and processed. 914 bool transferSpillOrRestoreInst(MachineInstr &MI); 915 916 /// Examines \p MI for any registers that it defines, and notifies trackers. 917 void transferRegisterDef(MachineInstr &MI); 918 919 /// Copy one location to the other, accounting for movement of subregisters 920 /// too. 921 void performCopy(Register Src, Register Dst); 922 923 void accumulateFragmentMap(MachineInstr &MI); 924 925 /// Determine the machine value number referred to by (potentially several) 926 /// DBG_PHI instructions. Block duplication and tail folding can duplicate 927 /// DBG_PHIs, shifting the position where values in registers merge, and 928 /// forming another mini-ssa problem to solve. 929 /// \p Here the position of a DBG_INSTR_REF seeking a machine value number 930 /// \p InstrNum Debug instruction number defined by DBG_PHI instructions. 931 /// \returns The machine value number at position Here, or None. 932 Optional<ValueIDNum> resolveDbgPHIs(MachineFunction &MF, 933 ValueIDNum **MLiveOuts, 934 ValueIDNum **MLiveIns, MachineInstr &Here, 935 uint64_t InstrNum); 936 937 /// Step through the function, recording register definitions and movements 938 /// in an MLocTracker. Convert the observations into a per-block transfer 939 /// function in \p MLocTransfer, suitable for using with the machine value 940 /// location dataflow problem. 941 void 942 produceMLocTransferFunction(MachineFunction &MF, 943 SmallVectorImpl<MLocTransferMap> &MLocTransfer, 944 unsigned MaxNumBlocks); 945 946 /// Solve the machine value location dataflow problem. Takes as input the 947 /// transfer functions in \p MLocTransfer. Writes the output live-in and 948 /// live-out arrays to the (initialized to zero) multidimensional arrays in 949 /// \p MInLocs and \p MOutLocs. The outer dimension is indexed by block 950 /// number, the inner by LocIdx. 951 void buildMLocValueMap(MachineFunction &MF, ValueIDNum **MInLocs, 952 ValueIDNum **MOutLocs, 953 SmallVectorImpl<MLocTransferMap> &MLocTransfer); 954 955 /// Examine the stack indexes (i.e. offsets within the stack) to find the 956 /// basic units of interference -- like reg units, but for the stack. 957 void findStackIndexInterference(SmallVectorImpl<unsigned> &Slots); 958 959 /// Install PHI values into the live-in array for each block, according to 960 /// the IDF of each register. 961 void placeMLocPHIs(MachineFunction &MF, 962 SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks, 963 ValueIDNum **MInLocs, 964 SmallVectorImpl<MLocTransferMap> &MLocTransfer); 965 966 /// Propagate variable values to blocks in the common case where there's 967 /// only one value assigned to the variable. This function has better 968 /// performance as it doesn't have to find the dominance frontier between 969 /// different assignments. 970 void placePHIsForSingleVarDefinition( 971 const SmallPtrSetImpl<MachineBasicBlock *> &InScopeBlocks, 972 MachineBasicBlock *MBB, SmallVectorImpl<VLocTracker> &AllTheVLocs, 973 const DebugVariable &Var, LiveInsT &Output); 974 975 /// Calculate the iterated-dominance-frontier for a set of defs, using the 976 /// existing LLVM facilities for this. Works for a single "value" or 977 /// machine/variable location. 978 /// \p AllBlocks Set of blocks where we might consume the value. 979 /// \p DefBlocks Set of blocks where the value/location is defined. 980 /// \p PHIBlocks Output set of blocks where PHIs must be placed. 981 void BlockPHIPlacement(const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks, 982 const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks, 983 SmallVectorImpl<MachineBasicBlock *> &PHIBlocks); 984 985 /// Perform a control flow join (lattice value meet) of the values in machine 986 /// locations at \p MBB. Follows the algorithm described in the file-comment, 987 /// reading live-outs of predecessors from \p OutLocs, the current live ins 988 /// from \p InLocs, and assigning the newly computed live ins back into 989 /// \p InLocs. \returns two bools -- the first indicates whether a change 990 /// was made, the second whether a lattice downgrade occurred. If the latter 991 /// is true, revisiting this block is necessary. 992 bool mlocJoin(MachineBasicBlock &MBB, 993 SmallPtrSet<const MachineBasicBlock *, 16> &Visited, 994 ValueIDNum **OutLocs, ValueIDNum *InLocs); 995 996 /// Solve the variable value dataflow problem, for a single lexical scope. 997 /// Uses the algorithm from the file comment to resolve control flow joins 998 /// using PHI placement and value propagation. Reads the locations of machine 999 /// values from the \p MInLocs and \p MOutLocs arrays (see buildMLocValueMap) 1000 /// and reads the variable values transfer function from \p AllTheVlocs. 1001 /// Live-in and Live-out variable values are stored locally, with the live-ins 1002 /// permanently stored to \p Output once a fixedpoint is reached. 1003 /// \p VarsWeCareAbout contains a collection of the variables in \p Scope 1004 /// that we should be tracking. 1005 /// \p AssignBlocks contains the set of blocks that aren't in \p DILoc's 1006 /// scope, but which do contain DBG_VALUEs, which VarLocBasedImpl tracks 1007 /// locations through. 1008 void buildVLocValueMap(const DILocation *DILoc, 1009 const SmallSet<DebugVariable, 4> &VarsWeCareAbout, 1010 SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, 1011 LiveInsT &Output, ValueIDNum **MOutLocs, 1012 ValueIDNum **MInLocs, 1013 SmallVectorImpl<VLocTracker> &AllTheVLocs); 1014 1015 /// Attempt to eliminate un-necessary PHIs on entry to a block. Examines the 1016 /// live-in values coming from predecessors live-outs, and replaces any PHIs 1017 /// already present in this blocks live-ins with a live-through value if the 1018 /// PHI isn't needed. 1019 /// \p LiveIn Old live-in value, overwritten with new one if live-in changes. 1020 /// \returns true if any live-ins change value, either from value propagation 1021 /// or PHI elimination. 1022 bool vlocJoin(MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs, 1023 SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore, 1024 DbgValue &LiveIn); 1025 1026 /// For the given block and live-outs feeding into it, try to find a 1027 /// machine location where all the variable values join together. 1028 /// \returns Value ID of a machine PHI if an appropriate one is available. 1029 Optional<ValueIDNum> 1030 pickVPHILoc(const MachineBasicBlock &MBB, const DebugVariable &Var, 1031 const LiveIdxT &LiveOuts, ValueIDNum **MOutLocs, 1032 const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders); 1033 1034 /// Given the solutions to the two dataflow problems, machine value locations 1035 /// in \p MInLocs and live-in variable values in \p SavedLiveIns, runs the 1036 /// TransferTracker class over the function to produce live-in and transfer 1037 /// DBG_VALUEs, then inserts them. Groups of DBG_VALUEs are inserted in the 1038 /// order given by AllVarsNumbering -- this could be any stable order, but 1039 /// right now "order of appearence in function, when explored in RPO", so 1040 /// that we can compare explictly against VarLocBasedImpl. 1041 void emitLocations(MachineFunction &MF, LiveInsT SavedLiveIns, 1042 ValueIDNum **MOutLocs, ValueIDNum **MInLocs, 1043 DenseMap<DebugVariable, unsigned> &AllVarsNumbering, 1044 const TargetPassConfig &TPC); 1045 1046 /// Boilerplate computation of some initial sets, artifical blocks and 1047 /// RPOT block ordering. 1048 void initialSetup(MachineFunction &MF); 1049 1050 bool ExtendRanges(MachineFunction &MF, MachineDominatorTree *DomTree, 1051 TargetPassConfig *TPC, unsigned InputBBLimit, 1052 unsigned InputDbgValLimit) override; 1053 1054 public: 1055 /// Default construct and initialize the pass. 1056 InstrRefBasedLDV(); 1057 1058 LLVM_DUMP_METHOD 1059 void dump_mloc_transfer(const MLocTransferMap &mloc_transfer) const; 1060 1061 bool isCalleeSaved(LocIdx L) const; 1062 1063 bool hasFoldedStackStore(const MachineInstr &MI) { 1064 // Instruction must have a memory operand that's a stack slot, and isn't 1065 // aliased, meaning it's a spill from regalloc instead of a variable. 1066 // If it's aliased, we can't guarantee its value. 1067 if (!MI.hasOneMemOperand()) 1068 return false; 1069 auto *MemOperand = *MI.memoperands_begin(); 1070 return MemOperand->isStore() && 1071 MemOperand->getPseudoValue() && 1072 MemOperand->getPseudoValue()->kind() == PseudoSourceValue::FixedStack 1073 && !MemOperand->getPseudoValue()->isAliased(MFI); 1074 } 1075 1076 Optional<LocIdx> findLocationForMemOperand(const MachineInstr &MI); 1077 }; 1078 1079 } // namespace LiveDebugValues 1080 1081 namespace llvm { 1082 using namespace LiveDebugValues; 1083 1084 template <> struct DenseMapInfo<LocIdx> { 1085 static inline LocIdx getEmptyKey() { return LocIdx::MakeIllegalLoc(); } 1086 static inline LocIdx getTombstoneKey() { return LocIdx::MakeTombstoneLoc(); } 1087 1088 static unsigned getHashValue(const LocIdx &Loc) { return Loc.asU64(); } 1089 1090 static bool isEqual(const LocIdx &A, const LocIdx &B) { return A == B; } 1091 }; 1092 1093 template <> struct DenseMapInfo<ValueIDNum> { 1094 static inline ValueIDNum getEmptyKey() { return ValueIDNum::EmptyValue; } 1095 static inline ValueIDNum getTombstoneKey() { 1096 return ValueIDNum::TombstoneValue; 1097 } 1098 1099 static unsigned getHashValue(const ValueIDNum &Val) { 1100 return hash_value(Val.asU64()); 1101 } 1102 1103 static bool isEqual(const ValueIDNum &A, const ValueIDNum &B) { 1104 return A == B; 1105 } 1106 }; 1107 1108 } // end namespace llvm 1109 1110 #endif /* LLVM_LIB_CODEGEN_LIVEDEBUGVALUES_INSTRREFBASEDLDV_H */ 1111