1 //===- InstrRefBasedImpl.cpp - 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 /// \file InstrRefBasedImpl.cpp 9 /// 10 /// This is a separate implementation of LiveDebugValues, see 11 /// LiveDebugValues.cpp and VarLocBasedImpl.cpp for more information. 12 /// 13 /// This pass propagates variable locations between basic blocks, resolving 14 /// control flow conflicts between them. The problem is much like SSA 15 /// construction, where each DBG_VALUE instruction assigns the *value* that 16 /// a variable has, and every instruction where the variable is in scope uses 17 /// that variable. The resulting map of instruction-to-value is then translated 18 /// into a register (or spill) location for each variable over each instruction. 19 /// 20 /// This pass determines which DBG_VALUE dominates which instructions, or if 21 /// none do, where values must be merged (like PHI nodes). The added 22 /// complication is that because codegen has already finished, a PHI node may 23 /// be needed for a variable location to be correct, but no register or spill 24 /// slot merges the necessary values. In these circumstances, the variable 25 /// location is dropped. 26 /// 27 /// What makes this analysis non-trivial is loops: we cannot tell in advance 28 /// whether a variable location is live throughout a loop, or whether its 29 /// location is clobbered (or redefined by another DBG_VALUE), without 30 /// exploring all the way through. 31 /// 32 /// To make this simpler we perform two kinds of analysis. First, we identify 33 /// every value defined by every instruction (ignoring those that only move 34 /// another value), then compute a map of which values are available for each 35 /// instruction. This is stronger than a reaching-def analysis, as we create 36 /// PHI values where other values merge. 37 /// 38 /// Secondly, for each variable, we effectively re-construct SSA using each 39 /// DBG_VALUE as a def. The DBG_VALUEs read a value-number computed by the 40 /// first analysis from the location they refer to. We can then compute the 41 /// dominance frontiers of where a variable has a value, and create PHI nodes 42 /// where they merge. 43 /// This isn't precisely SSA-construction though, because the function shape 44 /// is pre-defined. If a variable location requires a PHI node, but no 45 /// PHI for the relevant values is present in the function (as computed by the 46 /// first analysis), the location must be dropped. 47 /// 48 /// Once both are complete, we can pass back over all instructions knowing: 49 /// * What _value_ each variable should contain, either defined by an 50 /// instruction or where control flow merges 51 /// * What the location of that value is (if any). 52 /// Allowing us to create appropriate live-in DBG_VALUEs, and DBG_VALUEs when 53 /// a value moves location. After this pass runs, all variable locations within 54 /// a block should be specified by DBG_VALUEs within that block, allowing 55 /// DbgEntityHistoryCalculator to focus on individual blocks. 56 /// 57 /// This pass is able to go fast because the size of the first 58 /// reaching-definition analysis is proportional to the working-set size of 59 /// the function, which the compiler tries to keep small. (It's also 60 /// proportional to the number of blocks). Additionally, we repeatedly perform 61 /// the second reaching-definition analysis with only the variables and blocks 62 /// in a single lexical scope, exploiting their locality. 63 /// 64 /// Determining where PHIs happen is trickier with this approach, and it comes 65 /// to a head in the major problem for LiveDebugValues: is a value live-through 66 /// a loop, or not? Your garden-variety dataflow analysis aims to build a set of 67 /// facts about a function, however this analysis needs to generate new value 68 /// numbers at joins. 69 /// 70 /// To do this, consider a lattice of all definition values, from instructions 71 /// and from PHIs. Each PHI is characterised by the RPO number of the block it 72 /// occurs in. Each value pair A, B can be ordered by RPO(A) < RPO(B): 73 /// with non-PHI values at the top, and any PHI value in the last block (by RPO 74 /// order) at the bottom. 75 /// 76 /// (Awkwardly: lower-down-the _lattice_ means a greater RPO _number_. Below, 77 /// "rank" always refers to the former). 78 /// 79 /// At any join, for each register, we consider: 80 /// * All incoming values, and 81 /// * The PREVIOUS live-in value at this join. 82 /// If all incoming values agree: that's the live-in value. If they do not, the 83 /// incoming values are ranked according to the partial order, and the NEXT 84 /// LOWEST rank after the PREVIOUS live-in value is picked (multiple values of 85 /// the same rank are ignored as conflicting). If there are no candidate values, 86 /// or if the rank of the live-in would be lower than the rank of the current 87 /// blocks PHIs, create a new PHI value. 88 /// 89 /// Intuitively: if it's not immediately obvious what value a join should result 90 /// in, we iteratively descend from instruction-definitions down through PHI 91 /// values, getting closer to the current block each time. If the current block 92 /// is a loop head, this ordering is effectively searching outer levels of 93 /// loops, to find a value that's live-through the current loop. 94 /// 95 /// If there is no value that's live-through this loop, a PHI is created for 96 /// this location instead. We can't use a lower-ranked PHI because by definition 97 /// it doesn't dominate the current block. We can't create a PHI value any 98 /// earlier, because we risk creating a PHI value at a location where values do 99 /// not in fact merge, thus misrepresenting the truth, and not making the true 100 /// live-through value for variable locations. 101 /// 102 /// This algorithm applies to both calculating the availability of values in 103 /// the first analysis, and the location of variables in the second. However 104 /// for the second we add an extra dimension of pain: creating a variable 105 /// location PHI is only valid if, for each incoming edge, 106 /// * There is a value for the variable on the incoming edge, and 107 /// * All the edges have that value in the same register. 108 /// Or put another way: we can only create a variable-location PHI if there is 109 /// a matching machine-location PHI, each input to which is the variables value 110 /// in the predecessor block. 111 /// 112 /// To accommodate this difference, each point on the lattice is split in 113 /// two: a "proposed" PHI and "definite" PHI. Any PHI that can immediately 114 /// have a location determined are "definite" PHIs, and no further work is 115 /// needed. Otherwise, a location that all non-backedge predecessors agree 116 /// on is picked and propagated as a "proposed" PHI value. If that PHI value 117 /// is truly live-through, it'll appear on the loop backedges on the next 118 /// dataflow iteration, after which the block live-in moves to be a "definite" 119 /// PHI. If it's not truly live-through, the variable value will be downgraded 120 /// further as we explore the lattice, or remains "proposed" and is considered 121 /// invalid once dataflow completes. 122 /// 123 /// ### Terminology 124 /// 125 /// A machine location is a register or spill slot, a value is something that's 126 /// defined by an instruction or PHI node, while a variable value is the value 127 /// assigned to a variable. A variable location is a machine location, that must 128 /// contain the appropriate variable value. A value that is a PHI node is 129 /// occasionally called an mphi. 130 /// 131 /// The first dataflow problem is the "machine value location" problem, 132 /// because we're determining which machine locations contain which values. 133 /// The "locations" are constant: what's unknown is what value they contain. 134 /// 135 /// The second dataflow problem (the one for variables) is the "variable value 136 /// problem", because it's determining what values a variable has, rather than 137 /// what location those values are placed in. Unfortunately, it's not that 138 /// simple, because producing a PHI value always involves picking a location. 139 /// This is an imperfection that we just have to accept, at least for now. 140 /// 141 /// TODO: 142 /// Overlapping fragments 143 /// Entry values 144 /// Add back DEBUG statements for debugging this 145 /// Collect statistics 146 /// 147 //===----------------------------------------------------------------------===// 148 149 #include "llvm/ADT/DenseMap.h" 150 #include "llvm/ADT/PostOrderIterator.h" 151 #include "llvm/ADT/STLExtras.h" 152 #include "llvm/ADT/SmallPtrSet.h" 153 #include "llvm/ADT/SmallSet.h" 154 #include "llvm/ADT/SmallVector.h" 155 #include "llvm/ADT/Statistic.h" 156 #include "llvm/ADT/UniqueVector.h" 157 #include "llvm/CodeGen/LexicalScopes.h" 158 #include "llvm/CodeGen/MachineBasicBlock.h" 159 #include "llvm/CodeGen/MachineFrameInfo.h" 160 #include "llvm/CodeGen/MachineFunction.h" 161 #include "llvm/CodeGen/MachineFunctionPass.h" 162 #include "llvm/CodeGen/MachineInstr.h" 163 #include "llvm/CodeGen/MachineInstrBuilder.h" 164 #include "llvm/CodeGen/MachineInstrBundle.h" 165 #include "llvm/CodeGen/MachineMemOperand.h" 166 #include "llvm/CodeGen/MachineOperand.h" 167 #include "llvm/CodeGen/PseudoSourceValue.h" 168 #include "llvm/CodeGen/RegisterScavenging.h" 169 #include "llvm/CodeGen/TargetFrameLowering.h" 170 #include "llvm/CodeGen/TargetInstrInfo.h" 171 #include "llvm/CodeGen/TargetLowering.h" 172 #include "llvm/CodeGen/TargetPassConfig.h" 173 #include "llvm/CodeGen/TargetRegisterInfo.h" 174 #include "llvm/CodeGen/TargetSubtargetInfo.h" 175 #include "llvm/Config/llvm-config.h" 176 #include "llvm/IR/DIBuilder.h" 177 #include "llvm/IR/DebugInfoMetadata.h" 178 #include "llvm/IR/DebugLoc.h" 179 #include "llvm/IR/Function.h" 180 #include "llvm/IR/Module.h" 181 #include "llvm/InitializePasses.h" 182 #include "llvm/MC/MCRegisterInfo.h" 183 #include "llvm/Pass.h" 184 #include "llvm/Support/Casting.h" 185 #include "llvm/Support/Compiler.h" 186 #include "llvm/Support/Debug.h" 187 #include "llvm/Support/TypeSize.h" 188 #include "llvm/Support/raw_ostream.h" 189 #include "llvm/Target/TargetMachine.h" 190 #include "llvm/Transforms/Utils/SSAUpdaterImpl.h" 191 #include <algorithm> 192 #include <cassert> 193 #include <cstdint> 194 #include <functional> 195 #include <queue> 196 #include <tuple> 197 #include <utility> 198 #include <vector> 199 #include <limits.h> 200 #include <limits> 201 202 #include "LiveDebugValues.h" 203 204 using namespace llvm; 205 206 // SSAUpdaterImple sets DEBUG_TYPE, change it. 207 #undef DEBUG_TYPE 208 #define DEBUG_TYPE "livedebugvalues" 209 210 // Act more like the VarLoc implementation, by propagating some locations too 211 // far and ignoring some transfers. 212 static cl::opt<bool> EmulateOldLDV("emulate-old-livedebugvalues", cl::Hidden, 213 cl::desc("Act like old LiveDebugValues did"), 214 cl::init(false)); 215 216 // Rely on isStoreToStackSlotPostFE and similar to observe all stack spills. 217 static cl::opt<bool> 218 ObserveAllStackops("observe-all-stack-ops", cl::Hidden, 219 cl::desc("Allow non-kill spill and restores"), 220 cl::init(false)); 221 222 namespace { 223 224 // The location at which a spilled value resides. It consists of a register and 225 // an offset. 226 struct SpillLoc { 227 unsigned SpillBase; 228 StackOffset SpillOffset; 229 bool operator==(const SpillLoc &Other) const { 230 return std::make_pair(SpillBase, SpillOffset) == 231 std::make_pair(Other.SpillBase, Other.SpillOffset); 232 } 233 bool operator<(const SpillLoc &Other) const { 234 return std::make_tuple(SpillBase, SpillOffset.getFixed(), 235 SpillOffset.getScalable()) < 236 std::make_tuple(Other.SpillBase, Other.SpillOffset.getFixed(), 237 Other.SpillOffset.getScalable()); 238 } 239 }; 240 241 class LocIdx { 242 unsigned Location; 243 244 // Default constructor is private, initializing to an illegal location number. 245 // Use only for "not an entry" elements in IndexedMaps. 246 LocIdx() : Location(UINT_MAX) { } 247 248 public: 249 #define NUM_LOC_BITS 24 250 LocIdx(unsigned L) : Location(L) { 251 assert(L < (1 << NUM_LOC_BITS) && "Machine locations must fit in 24 bits"); 252 } 253 254 static LocIdx MakeIllegalLoc() { 255 return LocIdx(); 256 } 257 258 bool isIllegal() const { 259 return Location == UINT_MAX; 260 } 261 262 uint64_t asU64() const { 263 return Location; 264 } 265 266 bool operator==(unsigned L) const { 267 return Location == L; 268 } 269 270 bool operator==(const LocIdx &L) const { 271 return Location == L.Location; 272 } 273 274 bool operator!=(unsigned L) const { 275 return !(*this == L); 276 } 277 278 bool operator!=(const LocIdx &L) const { 279 return !(*this == L); 280 } 281 282 bool operator<(const LocIdx &Other) const { 283 return Location < Other.Location; 284 } 285 }; 286 287 class LocIdxToIndexFunctor { 288 public: 289 using argument_type = LocIdx; 290 unsigned operator()(const LocIdx &L) const { 291 return L.asU64(); 292 } 293 }; 294 295 /// Unique identifier for a value defined by an instruction, as a value type. 296 /// Casts back and forth to a uint64_t. Probably replacable with something less 297 /// bit-constrained. Each value identifies the instruction and machine location 298 /// where the value is defined, although there may be no corresponding machine 299 /// operand for it (ex: regmasks clobbering values). The instructions are 300 /// one-based, and definitions that are PHIs have instruction number zero. 301 /// 302 /// The obvious limits of a 1M block function or 1M instruction blocks are 303 /// problematic; but by that point we should probably have bailed out of 304 /// trying to analyse the function. 305 class ValueIDNum { 306 uint64_t BlockNo : 20; /// The block where the def happens. 307 uint64_t InstNo : 20; /// The Instruction where the def happens. 308 /// One based, is distance from start of block. 309 uint64_t LocNo : NUM_LOC_BITS; /// The machine location where the def happens. 310 311 public: 312 // XXX -- temporarily enabled while the live-in / live-out tables are moved 313 // to something more type-y 314 ValueIDNum() : BlockNo(0xFFFFF), 315 InstNo(0xFFFFF), 316 LocNo(0xFFFFFF) { } 317 318 ValueIDNum(uint64_t Block, uint64_t Inst, uint64_t Loc) 319 : BlockNo(Block), InstNo(Inst), LocNo(Loc) { } 320 321 ValueIDNum(uint64_t Block, uint64_t Inst, LocIdx Loc) 322 : BlockNo(Block), InstNo(Inst), LocNo(Loc.asU64()) { } 323 324 uint64_t getBlock() const { return BlockNo; } 325 uint64_t getInst() const { return InstNo; } 326 uint64_t getLoc() const { return LocNo; } 327 bool isPHI() const { return InstNo == 0; } 328 329 uint64_t asU64() const { 330 uint64_t TmpBlock = BlockNo; 331 uint64_t TmpInst = InstNo; 332 return TmpBlock << 44ull | TmpInst << NUM_LOC_BITS | LocNo; 333 } 334 335 static ValueIDNum fromU64(uint64_t v) { 336 uint64_t L = (v & 0x3FFF); 337 return {v >> 44ull, ((v >> NUM_LOC_BITS) & 0xFFFFF), L}; 338 } 339 340 bool operator<(const ValueIDNum &Other) const { 341 return asU64() < Other.asU64(); 342 } 343 344 bool operator==(const ValueIDNum &Other) const { 345 return std::tie(BlockNo, InstNo, LocNo) == 346 std::tie(Other.BlockNo, Other.InstNo, Other.LocNo); 347 } 348 349 bool operator!=(const ValueIDNum &Other) const { return !(*this == Other); } 350 351 std::string asString(const std::string &mlocname) const { 352 return Twine("Value{bb: ") 353 .concat(Twine(BlockNo).concat( 354 Twine(", inst: ") 355 .concat((InstNo ? Twine(InstNo) : Twine("live-in")) 356 .concat(Twine(", loc: ").concat(Twine(mlocname))) 357 .concat(Twine("}"))))) 358 .str(); 359 } 360 361 static ValueIDNum EmptyValue; 362 }; 363 364 } // end anonymous namespace 365 366 namespace { 367 368 /// Meta qualifiers for a value. Pair of whatever expression is used to qualify 369 /// the the value, and Boolean of whether or not it's indirect. 370 class DbgValueProperties { 371 public: 372 DbgValueProperties(const DIExpression *DIExpr, bool Indirect) 373 : DIExpr(DIExpr), Indirect(Indirect) {} 374 375 /// Extract properties from an existing DBG_VALUE instruction. 376 DbgValueProperties(const MachineInstr &MI) { 377 assert(MI.isDebugValue()); 378 DIExpr = MI.getDebugExpression(); 379 Indirect = MI.getOperand(1).isImm(); 380 } 381 382 bool operator==(const DbgValueProperties &Other) const { 383 return std::tie(DIExpr, Indirect) == std::tie(Other.DIExpr, Other.Indirect); 384 } 385 386 bool operator!=(const DbgValueProperties &Other) const { 387 return !(*this == Other); 388 } 389 390 const DIExpression *DIExpr; 391 bool Indirect; 392 }; 393 394 /// Tracker for what values are in machine locations. Listens to the Things 395 /// being Done by various instructions, and maintains a table of what machine 396 /// locations have what values (as defined by a ValueIDNum). 397 /// 398 /// There are potentially a much larger number of machine locations on the 399 /// target machine than the actual working-set size of the function. On x86 for 400 /// example, we're extremely unlikely to want to track values through control 401 /// or debug registers. To avoid doing so, MLocTracker has several layers of 402 /// indirection going on, with two kinds of ``location'': 403 /// * A LocID uniquely identifies a register or spill location, with a 404 /// predictable value. 405 /// * A LocIdx is a key (in the database sense) for a LocID and a ValueIDNum. 406 /// Whenever a location is def'd or used by a MachineInstr, we automagically 407 /// create a new LocIdx for a location, but not otherwise. This ensures we only 408 /// account for locations that are actually used or defined. The cost is another 409 /// vector lookup (of LocID -> LocIdx) over any other implementation. This is 410 /// fairly cheap, and the compiler tries to reduce the working-set at any one 411 /// time in the function anyway. 412 /// 413 /// Register mask operands completely blow this out of the water; I've just 414 /// piled hacks on top of hacks to get around that. 415 class MLocTracker { 416 public: 417 MachineFunction &MF; 418 const TargetInstrInfo &TII; 419 const TargetRegisterInfo &TRI; 420 const TargetLowering &TLI; 421 422 /// IndexedMap type, mapping from LocIdx to ValueIDNum. 423 using LocToValueType = IndexedMap<ValueIDNum, LocIdxToIndexFunctor>; 424 425 /// Map of LocIdxes to the ValueIDNums that they store. This is tightly 426 /// packed, entries only exist for locations that are being tracked. 427 LocToValueType LocIdxToIDNum; 428 429 /// "Map" of machine location IDs (i.e., raw register or spill number) to the 430 /// LocIdx key / number for that location. There are always at least as many 431 /// as the number of registers on the target -- if the value in the register 432 /// is not being tracked, then the LocIdx value will be zero. New entries are 433 /// appended if a new spill slot begins being tracked. 434 /// This, and the corresponding reverse map persist for the analysis of the 435 /// whole function, and is necessarying for decoding various vectors of 436 /// values. 437 std::vector<LocIdx> LocIDToLocIdx; 438 439 /// Inverse map of LocIDToLocIdx. 440 IndexedMap<unsigned, LocIdxToIndexFunctor> LocIdxToLocID; 441 442 /// Unique-ification of spill slots. Used to number them -- their LocID 443 /// number is the index in SpillLocs minus one plus NumRegs. 444 UniqueVector<SpillLoc> SpillLocs; 445 446 // If we discover a new machine location, assign it an mphi with this 447 // block number. 448 unsigned CurBB; 449 450 /// Cached local copy of the number of registers the target has. 451 unsigned NumRegs; 452 453 /// Collection of register mask operands that have been observed. Second part 454 /// of pair indicates the instruction that they happened in. Used to 455 /// reconstruct where defs happened if we start tracking a location later 456 /// on. 457 SmallVector<std::pair<const MachineOperand *, unsigned>, 32> Masks; 458 459 /// Iterator for locations and the values they contain. Dereferencing 460 /// produces a struct/pair containing the LocIdx key for this location, 461 /// and a reference to the value currently stored. Simplifies the process 462 /// of seeking a particular location. 463 class MLocIterator { 464 LocToValueType &ValueMap; 465 LocIdx Idx; 466 467 public: 468 class value_type { 469 public: 470 value_type(LocIdx Idx, ValueIDNum &Value) : Idx(Idx), Value(Value) { } 471 const LocIdx Idx; /// Read-only index of this location. 472 ValueIDNum &Value; /// Reference to the stored value at this location. 473 }; 474 475 MLocIterator(LocToValueType &ValueMap, LocIdx Idx) 476 : ValueMap(ValueMap), Idx(Idx) { } 477 478 bool operator==(const MLocIterator &Other) const { 479 assert(&ValueMap == &Other.ValueMap); 480 return Idx == Other.Idx; 481 } 482 483 bool operator!=(const MLocIterator &Other) const { 484 return !(*this == Other); 485 } 486 487 void operator++() { 488 Idx = LocIdx(Idx.asU64() + 1); 489 } 490 491 value_type operator*() { 492 return value_type(Idx, ValueMap[LocIdx(Idx)]); 493 } 494 }; 495 496 MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII, 497 const TargetRegisterInfo &TRI, const TargetLowering &TLI) 498 : MF(MF), TII(TII), TRI(TRI), TLI(TLI), 499 LocIdxToIDNum(ValueIDNum::EmptyValue), 500 LocIdxToLocID(0) { 501 NumRegs = TRI.getNumRegs(); 502 reset(); 503 LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc()); 504 assert(NumRegs < (1u << NUM_LOC_BITS)); // Detect bit packing failure 505 506 // Always track SP. This avoids the implicit clobbering caused by regmasks 507 // from affectings its values. (LiveDebugValues disbelieves calls and 508 // regmasks that claim to clobber SP). 509 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 510 if (SP) { 511 unsigned ID = getLocID(SP, false); 512 (void)lookupOrTrackRegister(ID); 513 } 514 } 515 516 /// Produce location ID number for indexing LocIDToLocIdx. Takes the register 517 /// or spill number, and flag for whether it's a spill or not. 518 unsigned getLocID(Register RegOrSpill, bool isSpill) { 519 return (isSpill) ? RegOrSpill.id() + NumRegs - 1 : RegOrSpill.id(); 520 } 521 522 /// Accessor for reading the value at Idx. 523 ValueIDNum getNumAtPos(LocIdx Idx) const { 524 assert(Idx.asU64() < LocIdxToIDNum.size()); 525 return LocIdxToIDNum[Idx]; 526 } 527 528 unsigned getNumLocs(void) const { return LocIdxToIDNum.size(); } 529 530 /// Reset all locations to contain a PHI value at the designated block. Used 531 /// sometimes for actual PHI values, othertimes to indicate the block entry 532 /// value (before any more information is known). 533 void setMPhis(unsigned NewCurBB) { 534 CurBB = NewCurBB; 535 for (auto Location : locations()) 536 Location.Value = {CurBB, 0, Location.Idx}; 537 } 538 539 /// Load values for each location from array of ValueIDNums. Take current 540 /// bbnum just in case we read a value from a hitherto untouched register. 541 void loadFromArray(ValueIDNum *Locs, unsigned NewCurBB) { 542 CurBB = NewCurBB; 543 // Iterate over all tracked locations, and load each locations live-in 544 // value into our local index. 545 for (auto Location : locations()) 546 Location.Value = Locs[Location.Idx.asU64()]; 547 } 548 549 /// Wipe any un-necessary location records after traversing a block. 550 void reset(void) { 551 // We could reset all the location values too; however either loadFromArray 552 // or setMPhis should be called before this object is re-used. Just 553 // clear Masks, they're definitely not needed. 554 Masks.clear(); 555 } 556 557 /// Clear all data. Destroys the LocID <=> LocIdx map, which makes most of 558 /// the information in this pass uninterpretable. 559 void clear(void) { 560 reset(); 561 LocIDToLocIdx.clear(); 562 LocIdxToLocID.clear(); 563 LocIdxToIDNum.clear(); 564 //SpillLocs.reset(); XXX UniqueVector::reset assumes a SpillLoc casts from 0 565 SpillLocs = decltype(SpillLocs)(); 566 567 LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc()); 568 } 569 570 /// Set a locaiton to a certain value. 571 void setMLoc(LocIdx L, ValueIDNum Num) { 572 assert(L.asU64() < LocIdxToIDNum.size()); 573 LocIdxToIDNum[L] = Num; 574 } 575 576 /// Create a LocIdx for an untracked register ID. Initialize it to either an 577 /// mphi value representing a live-in, or a recent register mask clobber. 578 LocIdx trackRegister(unsigned ID) { 579 assert(ID != 0); 580 LocIdx NewIdx = LocIdx(LocIdxToIDNum.size()); 581 LocIdxToIDNum.grow(NewIdx); 582 LocIdxToLocID.grow(NewIdx); 583 584 // Default: it's an mphi. 585 ValueIDNum ValNum = {CurBB, 0, NewIdx}; 586 // Was this reg ever touched by a regmask? 587 for (const auto &MaskPair : reverse(Masks)) { 588 if (MaskPair.first->clobbersPhysReg(ID)) { 589 // There was an earlier def we skipped. 590 ValNum = {CurBB, MaskPair.second, NewIdx}; 591 break; 592 } 593 } 594 595 LocIdxToIDNum[NewIdx] = ValNum; 596 LocIdxToLocID[NewIdx] = ID; 597 return NewIdx; 598 } 599 600 LocIdx lookupOrTrackRegister(unsigned ID) { 601 LocIdx &Index = LocIDToLocIdx[ID]; 602 if (Index.isIllegal()) 603 Index = trackRegister(ID); 604 return Index; 605 } 606 607 /// Record a definition of the specified register at the given block / inst. 608 /// This doesn't take a ValueIDNum, because the definition and its location 609 /// are synonymous. 610 void defReg(Register R, unsigned BB, unsigned Inst) { 611 unsigned ID = getLocID(R, false); 612 LocIdx Idx = lookupOrTrackRegister(ID); 613 ValueIDNum ValueID = {BB, Inst, Idx}; 614 LocIdxToIDNum[Idx] = ValueID; 615 } 616 617 /// Set a register to a value number. To be used if the value number is 618 /// known in advance. 619 void setReg(Register R, ValueIDNum ValueID) { 620 unsigned ID = getLocID(R, false); 621 LocIdx Idx = lookupOrTrackRegister(ID); 622 LocIdxToIDNum[Idx] = ValueID; 623 } 624 625 ValueIDNum readReg(Register R) { 626 unsigned ID = getLocID(R, false); 627 LocIdx Idx = lookupOrTrackRegister(ID); 628 return LocIdxToIDNum[Idx]; 629 } 630 631 /// Reset a register value to zero / empty. Needed to replicate the 632 /// VarLoc implementation where a copy to/from a register effectively 633 /// clears the contents of the source register. (Values can only have one 634 /// machine location in VarLocBasedImpl). 635 void wipeRegister(Register R) { 636 unsigned ID = getLocID(R, false); 637 LocIdx Idx = LocIDToLocIdx[ID]; 638 LocIdxToIDNum[Idx] = ValueIDNum::EmptyValue; 639 } 640 641 /// Determine the LocIdx of an existing register. 642 LocIdx getRegMLoc(Register R) { 643 unsigned ID = getLocID(R, false); 644 return LocIDToLocIdx[ID]; 645 } 646 647 /// Record a RegMask operand being executed. Defs any register we currently 648 /// track, stores a pointer to the mask in case we have to account for it 649 /// later. 650 void writeRegMask(const MachineOperand *MO, unsigned CurBB, unsigned InstID) { 651 // Ensure SP exists, so that we don't override it later. 652 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 653 654 // Def any register we track have that isn't preserved. The regmask 655 // terminates the liveness of a register, meaning its value can't be 656 // relied upon -- we represent this by giving it a new value. 657 for (auto Location : locations()) { 658 unsigned ID = LocIdxToLocID[Location.Idx]; 659 // Don't clobber SP, even if the mask says it's clobbered. 660 if (ID < NumRegs && ID != SP && MO->clobbersPhysReg(ID)) 661 defReg(ID, CurBB, InstID); 662 } 663 Masks.push_back(std::make_pair(MO, InstID)); 664 } 665 666 /// Find LocIdx for SpillLoc \p L, creating a new one if it's not tracked. 667 LocIdx getOrTrackSpillLoc(SpillLoc L) { 668 unsigned SpillID = SpillLocs.idFor(L); 669 if (SpillID == 0) { 670 SpillID = SpillLocs.insert(L); 671 unsigned L = getLocID(SpillID, true); 672 LocIdx Idx = LocIdx(LocIdxToIDNum.size()); // New idx 673 LocIdxToIDNum.grow(Idx); 674 LocIdxToLocID.grow(Idx); 675 LocIDToLocIdx.push_back(Idx); 676 LocIdxToLocID[Idx] = L; 677 return Idx; 678 } else { 679 unsigned L = getLocID(SpillID, true); 680 LocIdx Idx = LocIDToLocIdx[L]; 681 return Idx; 682 } 683 } 684 685 /// Set the value stored in a spill slot. 686 void setSpill(SpillLoc L, ValueIDNum ValueID) { 687 LocIdx Idx = getOrTrackSpillLoc(L); 688 LocIdxToIDNum[Idx] = ValueID; 689 } 690 691 /// Read whatever value is in a spill slot, or None if it isn't tracked. 692 Optional<ValueIDNum> readSpill(SpillLoc L) { 693 unsigned SpillID = SpillLocs.idFor(L); 694 if (SpillID == 0) 695 return None; 696 697 unsigned LocID = getLocID(SpillID, true); 698 LocIdx Idx = LocIDToLocIdx[LocID]; 699 return LocIdxToIDNum[Idx]; 700 } 701 702 /// Determine the LocIdx of a spill slot. Return None if it previously 703 /// hasn't had a value assigned. 704 Optional<LocIdx> getSpillMLoc(SpillLoc L) { 705 unsigned SpillID = SpillLocs.idFor(L); 706 if (SpillID == 0) 707 return None; 708 unsigned LocNo = getLocID(SpillID, true); 709 return LocIDToLocIdx[LocNo]; 710 } 711 712 /// Return true if Idx is a spill machine location. 713 bool isSpill(LocIdx Idx) const { 714 return LocIdxToLocID[Idx] >= NumRegs; 715 } 716 717 MLocIterator begin() { 718 return MLocIterator(LocIdxToIDNum, 0); 719 } 720 721 MLocIterator end() { 722 return MLocIterator(LocIdxToIDNum, LocIdxToIDNum.size()); 723 } 724 725 /// Return a range over all locations currently tracked. 726 iterator_range<MLocIterator> locations() { 727 return llvm::make_range(begin(), end()); 728 } 729 730 std::string LocIdxToName(LocIdx Idx) const { 731 unsigned ID = LocIdxToLocID[Idx]; 732 if (ID >= NumRegs) 733 return Twine("slot ").concat(Twine(ID - NumRegs)).str(); 734 else 735 return TRI.getRegAsmName(ID).str(); 736 } 737 738 std::string IDAsString(const ValueIDNum &Num) const { 739 std::string DefName = LocIdxToName(Num.getLoc()); 740 return Num.asString(DefName); 741 } 742 743 LLVM_DUMP_METHOD 744 void dump() { 745 for (auto Location : locations()) { 746 std::string MLocName = LocIdxToName(Location.Value.getLoc()); 747 std::string DefName = Location.Value.asString(MLocName); 748 dbgs() << LocIdxToName(Location.Idx) << " --> " << DefName << "\n"; 749 } 750 } 751 752 LLVM_DUMP_METHOD 753 void dump_mloc_map() { 754 for (auto Location : locations()) { 755 std::string foo = LocIdxToName(Location.Idx); 756 dbgs() << "Idx " << Location.Idx.asU64() << " " << foo << "\n"; 757 } 758 } 759 760 /// Create a DBG_VALUE based on machine location \p MLoc. Qualify it with the 761 /// information in \pProperties, for variable Var. Don't insert it anywhere, 762 /// just return the builder for it. 763 MachineInstrBuilder emitLoc(Optional<LocIdx> MLoc, const DebugVariable &Var, 764 const DbgValueProperties &Properties) { 765 DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0, 766 Var.getVariable()->getScope(), 767 const_cast<DILocation *>(Var.getInlinedAt())); 768 auto MIB = BuildMI(MF, DL, TII.get(TargetOpcode::DBG_VALUE)); 769 770 const DIExpression *Expr = Properties.DIExpr; 771 if (!MLoc) { 772 // No location -> DBG_VALUE $noreg 773 MIB.addReg(0, RegState::Debug); 774 MIB.addReg(0, RegState::Debug); 775 } else if (LocIdxToLocID[*MLoc] >= NumRegs) { 776 unsigned LocID = LocIdxToLocID[*MLoc]; 777 const SpillLoc &Spill = SpillLocs[LocID - NumRegs + 1]; 778 779 auto *TRI = MF.getSubtarget().getRegisterInfo(); 780 Expr = TRI->prependOffsetExpression(Expr, DIExpression::ApplyOffset, 781 Spill.SpillOffset); 782 unsigned Base = Spill.SpillBase; 783 MIB.addReg(Base, RegState::Debug); 784 MIB.addImm(0); 785 } else { 786 unsigned LocID = LocIdxToLocID[*MLoc]; 787 MIB.addReg(LocID, RegState::Debug); 788 if (Properties.Indirect) 789 MIB.addImm(0); 790 else 791 MIB.addReg(0, RegState::Debug); 792 } 793 794 MIB.addMetadata(Var.getVariable()); 795 MIB.addMetadata(Expr); 796 return MIB; 797 } 798 }; 799 800 /// Class recording the (high level) _value_ of a variable. Identifies either 801 /// the value of the variable as a ValueIDNum, or a constant MachineOperand. 802 /// This class also stores meta-information about how the value is qualified. 803 /// Used to reason about variable values when performing the second 804 /// (DebugVariable specific) dataflow analysis. 805 class DbgValue { 806 public: 807 union { 808 /// If Kind is Def, the value number that this value is based on. 809 ValueIDNum ID; 810 /// If Kind is Const, the MachineOperand defining this value. 811 MachineOperand MO; 812 /// For a NoVal DbgValue, which block it was generated in. 813 unsigned BlockNo; 814 }; 815 /// Qualifiers for the ValueIDNum above. 816 DbgValueProperties Properties; 817 818 typedef enum { 819 Undef, // Represents a DBG_VALUE $noreg in the transfer function only. 820 Def, // This value is defined by an inst, or is a PHI value. 821 Const, // A constant value contained in the MachineOperand field. 822 Proposed, // This is a tentative PHI value, which may be confirmed or 823 // invalidated later. 824 NoVal // Empty DbgValue, generated during dataflow. BlockNo stores 825 // which block this was generated in. 826 } KindT; 827 /// Discriminator for whether this is a constant or an in-program value. 828 KindT Kind; 829 830 DbgValue(const ValueIDNum &Val, const DbgValueProperties &Prop, KindT Kind) 831 : ID(Val), Properties(Prop), Kind(Kind) { 832 assert(Kind == Def || Kind == Proposed); 833 } 834 835 DbgValue(unsigned BlockNo, const DbgValueProperties &Prop, KindT Kind) 836 : BlockNo(BlockNo), Properties(Prop), Kind(Kind) { 837 assert(Kind == NoVal); 838 } 839 840 DbgValue(const MachineOperand &MO, const DbgValueProperties &Prop, KindT Kind) 841 : MO(MO), Properties(Prop), Kind(Kind) { 842 assert(Kind == Const); 843 } 844 845 DbgValue(const DbgValueProperties &Prop, KindT Kind) 846 : Properties(Prop), Kind(Kind) { 847 assert(Kind == Undef && 848 "Empty DbgValue constructor must pass in Undef kind"); 849 } 850 851 void dump(const MLocTracker *MTrack) const { 852 if (Kind == Const) { 853 MO.dump(); 854 } else if (Kind == NoVal) { 855 dbgs() << "NoVal(" << BlockNo << ")"; 856 } else if (Kind == Proposed) { 857 dbgs() << "VPHI(" << MTrack->IDAsString(ID) << ")"; 858 } else { 859 assert(Kind == Def); 860 dbgs() << MTrack->IDAsString(ID); 861 } 862 if (Properties.Indirect) 863 dbgs() << " indir"; 864 if (Properties.DIExpr) 865 dbgs() << " " << *Properties.DIExpr; 866 } 867 868 bool operator==(const DbgValue &Other) const { 869 if (std::tie(Kind, Properties) != std::tie(Other.Kind, Other.Properties)) 870 return false; 871 else if (Kind == Proposed && ID != Other.ID) 872 return false; 873 else if (Kind == Def && ID != Other.ID) 874 return false; 875 else if (Kind == NoVal && BlockNo != Other.BlockNo) 876 return false; 877 else if (Kind == Const) 878 return MO.isIdenticalTo(Other.MO); 879 880 return true; 881 } 882 883 bool operator!=(const DbgValue &Other) const { return !(*this == Other); } 884 }; 885 886 /// Types for recording sets of variable fragments that overlap. For a given 887 /// local variable, we record all other fragments of that variable that could 888 /// overlap it, to reduce search time. 889 using FragmentOfVar = 890 std::pair<const DILocalVariable *, DIExpression::FragmentInfo>; 891 using OverlapMap = 892 DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>; 893 894 /// Collection of DBG_VALUEs observed when traversing a block. Records each 895 /// variable and the value the DBG_VALUE refers to. Requires the machine value 896 /// location dataflow algorithm to have run already, so that values can be 897 /// identified. 898 class VLocTracker { 899 public: 900 /// Map DebugVariable to the latest Value it's defined to have. 901 /// Needs to be a MapVector because we determine order-in-the-input-MIR from 902 /// the order in this container. 903 /// We only retain the last DbgValue in each block for each variable, to 904 /// determine the blocks live-out variable value. The Vars container forms the 905 /// transfer function for this block, as part of the dataflow analysis. The 906 /// movement of values between locations inside of a block is handled at a 907 /// much later stage, in the TransferTracker class. 908 MapVector<DebugVariable, DbgValue> Vars; 909 DenseMap<DebugVariable, const DILocation *> Scopes; 910 MachineBasicBlock *MBB; 911 912 public: 913 VLocTracker() {} 914 915 void defVar(const MachineInstr &MI, const DbgValueProperties &Properties, 916 Optional<ValueIDNum> ID) { 917 assert(MI.isDebugValue() || MI.isDebugRef()); 918 DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(), 919 MI.getDebugLoc()->getInlinedAt()); 920 DbgValue Rec = (ID) ? DbgValue(*ID, Properties, DbgValue::Def) 921 : DbgValue(Properties, DbgValue::Undef); 922 923 // Attempt insertion; overwrite if it's already mapped. 924 auto Result = Vars.insert(std::make_pair(Var, Rec)); 925 if (!Result.second) 926 Result.first->second = Rec; 927 Scopes[Var] = MI.getDebugLoc().get(); 928 } 929 930 void defVar(const MachineInstr &MI, const MachineOperand &MO) { 931 // Only DBG_VALUEs can define constant-valued variables. 932 assert(MI.isDebugValue()); 933 DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(), 934 MI.getDebugLoc()->getInlinedAt()); 935 DbgValueProperties Properties(MI); 936 DbgValue Rec = DbgValue(MO, Properties, DbgValue::Const); 937 938 // Attempt insertion; overwrite if it's already mapped. 939 auto Result = Vars.insert(std::make_pair(Var, Rec)); 940 if (!Result.second) 941 Result.first->second = Rec; 942 Scopes[Var] = MI.getDebugLoc().get(); 943 } 944 }; 945 946 /// Tracker for converting machine value locations and variable values into 947 /// variable locations (the output of LiveDebugValues), recorded as DBG_VALUEs 948 /// specifying block live-in locations and transfers within blocks. 949 /// 950 /// Operating on a per-block basis, this class takes a (pre-loaded) MLocTracker 951 /// and must be initialized with the set of variable values that are live-in to 952 /// the block. The caller then repeatedly calls process(). TransferTracker picks 953 /// out variable locations for the live-in variable values (if there _is_ a 954 /// location) and creates the corresponding DBG_VALUEs. Then, as the block is 955 /// stepped through, transfers of values between machine locations are 956 /// identified and if profitable, a DBG_VALUE created. 957 /// 958 /// This is where debug use-before-defs would be resolved: a variable with an 959 /// unavailable value could materialize in the middle of a block, when the 960 /// value becomes available. Or, we could detect clobbers and re-specify the 961 /// variable in a backup location. (XXX these are unimplemented). 962 class TransferTracker { 963 public: 964 const TargetInstrInfo *TII; 965 const TargetLowering *TLI; 966 /// This machine location tracker is assumed to always contain the up-to-date 967 /// value mapping for all machine locations. TransferTracker only reads 968 /// information from it. (XXX make it const?) 969 MLocTracker *MTracker; 970 MachineFunction &MF; 971 bool ShouldEmitDebugEntryValues; 972 973 /// Record of all changes in variable locations at a block position. Awkwardly 974 /// we allow inserting either before or after the point: MBB != nullptr 975 /// indicates it's before, otherwise after. 976 struct Transfer { 977 MachineBasicBlock::instr_iterator Pos; /// Position to insert DBG_VALUes 978 MachineBasicBlock *MBB; /// non-null if we should insert after. 979 SmallVector<MachineInstr *, 4> Insts; /// Vector of DBG_VALUEs to insert. 980 }; 981 982 struct LocAndProperties { 983 LocIdx Loc; 984 DbgValueProperties Properties; 985 }; 986 987 /// Collection of transfers (DBG_VALUEs) to be inserted. 988 SmallVector<Transfer, 32> Transfers; 989 990 /// Local cache of what-value-is-in-what-LocIdx. Used to identify differences 991 /// between TransferTrackers view of variable locations and MLocTrackers. For 992 /// example, MLocTracker observes all clobbers, but TransferTracker lazily 993 /// does not. 994 std::vector<ValueIDNum> VarLocs; 995 996 /// Map from LocIdxes to which DebugVariables are based that location. 997 /// Mantained while stepping through the block. Not accurate if 998 /// VarLocs[Idx] != MTracker->LocIdxToIDNum[Idx]. 999 std::map<LocIdx, SmallSet<DebugVariable, 4>> ActiveMLocs; 1000 1001 /// Map from DebugVariable to it's current location and qualifying meta 1002 /// information. To be used in conjunction with ActiveMLocs to construct 1003 /// enough information for the DBG_VALUEs for a particular LocIdx. 1004 DenseMap<DebugVariable, LocAndProperties> ActiveVLocs; 1005 1006 /// Temporary cache of DBG_VALUEs to be entered into the Transfers collection. 1007 SmallVector<MachineInstr *, 4> PendingDbgValues; 1008 1009 /// Record of a use-before-def: created when a value that's live-in to the 1010 /// current block isn't available in any machine location, but it will be 1011 /// defined in this block. 1012 struct UseBeforeDef { 1013 /// Value of this variable, def'd in block. 1014 ValueIDNum ID; 1015 /// Identity of this variable. 1016 DebugVariable Var; 1017 /// Additional variable properties. 1018 DbgValueProperties Properties; 1019 }; 1020 1021 /// Map from instruction index (within the block) to the set of UseBeforeDefs 1022 /// that become defined at that instruction. 1023 DenseMap<unsigned, SmallVector<UseBeforeDef, 1>> UseBeforeDefs; 1024 1025 /// The set of variables that are in UseBeforeDefs and can become a location 1026 /// once the relevant value is defined. An element being erased from this 1027 /// collection prevents the use-before-def materializing. 1028 DenseSet<DebugVariable> UseBeforeDefVariables; 1029 1030 const TargetRegisterInfo &TRI; 1031 const BitVector &CalleeSavedRegs; 1032 1033 TransferTracker(const TargetInstrInfo *TII, MLocTracker *MTracker, 1034 MachineFunction &MF, const TargetRegisterInfo &TRI, 1035 const BitVector &CalleeSavedRegs, const TargetPassConfig &TPC) 1036 : TII(TII), MTracker(MTracker), MF(MF), TRI(TRI), 1037 CalleeSavedRegs(CalleeSavedRegs) { 1038 TLI = MF.getSubtarget().getTargetLowering(); 1039 auto &TM = TPC.getTM<TargetMachine>(); 1040 ShouldEmitDebugEntryValues = TM.Options.ShouldEmitDebugEntryValues(); 1041 } 1042 1043 /// Load object with live-in variable values. \p mlocs contains the live-in 1044 /// values in each machine location, while \p vlocs the live-in variable 1045 /// values. This method picks variable locations for the live-in variables, 1046 /// creates DBG_VALUEs and puts them in #Transfers, then prepares the other 1047 /// object fields to track variable locations as we step through the block. 1048 /// FIXME: could just examine mloctracker instead of passing in \p mlocs? 1049 void loadInlocs(MachineBasicBlock &MBB, ValueIDNum *MLocs, 1050 SmallVectorImpl<std::pair<DebugVariable, DbgValue>> &VLocs, 1051 unsigned NumLocs) { 1052 ActiveMLocs.clear(); 1053 ActiveVLocs.clear(); 1054 VarLocs.clear(); 1055 VarLocs.reserve(NumLocs); 1056 UseBeforeDefs.clear(); 1057 UseBeforeDefVariables.clear(); 1058 1059 auto isCalleeSaved = [&](LocIdx L) { 1060 unsigned Reg = MTracker->LocIdxToLocID[L]; 1061 if (Reg >= MTracker->NumRegs) 1062 return false; 1063 for (MCRegAliasIterator RAI(Reg, &TRI, true); RAI.isValid(); ++RAI) 1064 if (CalleeSavedRegs.test(*RAI)) 1065 return true; 1066 return false; 1067 }; 1068 1069 // Map of the preferred location for each value. 1070 std::map<ValueIDNum, LocIdx> ValueToLoc; 1071 1072 // Produce a map of value numbers to the current machine locs they live 1073 // in. When emulating VarLocBasedImpl, there should only be one 1074 // location; when not, we get to pick. 1075 for (auto Location : MTracker->locations()) { 1076 LocIdx Idx = Location.Idx; 1077 ValueIDNum &VNum = MLocs[Idx.asU64()]; 1078 VarLocs.push_back(VNum); 1079 auto it = ValueToLoc.find(VNum); 1080 // In order of preference, pick: 1081 // * Callee saved registers, 1082 // * Other registers, 1083 // * Spill slots. 1084 if (it == ValueToLoc.end() || MTracker->isSpill(it->second) || 1085 (!isCalleeSaved(it->second) && isCalleeSaved(Idx.asU64()))) { 1086 // Insert, or overwrite if insertion failed. 1087 auto PrefLocRes = ValueToLoc.insert(std::make_pair(VNum, Idx)); 1088 if (!PrefLocRes.second) 1089 PrefLocRes.first->second = Idx; 1090 } 1091 } 1092 1093 // Now map variables to their picked LocIdxes. 1094 for (auto Var : VLocs) { 1095 if (Var.second.Kind == DbgValue::Const) { 1096 PendingDbgValues.push_back( 1097 emitMOLoc(Var.second.MO, Var.first, Var.second.Properties)); 1098 continue; 1099 } 1100 1101 // If the value has no location, we can't make a variable location. 1102 const ValueIDNum &Num = Var.second.ID; 1103 auto ValuesPreferredLoc = ValueToLoc.find(Num); 1104 if (ValuesPreferredLoc == ValueToLoc.end()) { 1105 // If it's a def that occurs in this block, register it as a 1106 // use-before-def to be resolved as we step through the block. 1107 if (Num.getBlock() == (unsigned)MBB.getNumber() && !Num.isPHI()) 1108 addUseBeforeDef(Var.first, Var.second.Properties, Num); 1109 else 1110 recoverAsEntryValue(Var.first, Var.second.Properties, Num); 1111 continue; 1112 } 1113 1114 LocIdx M = ValuesPreferredLoc->second; 1115 auto NewValue = LocAndProperties{M, Var.second.Properties}; 1116 auto Result = ActiveVLocs.insert(std::make_pair(Var.first, NewValue)); 1117 if (!Result.second) 1118 Result.first->second = NewValue; 1119 ActiveMLocs[M].insert(Var.first); 1120 PendingDbgValues.push_back( 1121 MTracker->emitLoc(M, Var.first, Var.second.Properties)); 1122 } 1123 flushDbgValues(MBB.begin(), &MBB); 1124 } 1125 1126 /// Record that \p Var has value \p ID, a value that becomes available 1127 /// later in the function. 1128 void addUseBeforeDef(const DebugVariable &Var, 1129 const DbgValueProperties &Properties, ValueIDNum ID) { 1130 UseBeforeDef UBD = {ID, Var, Properties}; 1131 UseBeforeDefs[ID.getInst()].push_back(UBD); 1132 UseBeforeDefVariables.insert(Var); 1133 } 1134 1135 /// After the instruction at index \p Inst and position \p pos has been 1136 /// processed, check whether it defines a variable value in a use-before-def. 1137 /// If so, and the variable value hasn't changed since the start of the 1138 /// block, create a DBG_VALUE. 1139 void checkInstForNewValues(unsigned Inst, MachineBasicBlock::iterator pos) { 1140 auto MIt = UseBeforeDefs.find(Inst); 1141 if (MIt == UseBeforeDefs.end()) 1142 return; 1143 1144 for (auto &Use : MIt->second) { 1145 LocIdx L = Use.ID.getLoc(); 1146 1147 // If something goes very wrong, we might end up labelling a COPY 1148 // instruction or similar with an instruction number, where it doesn't 1149 // actually define a new value, instead it moves a value. In case this 1150 // happens, discard. 1151 if (MTracker->LocIdxToIDNum[L] != Use.ID) 1152 continue; 1153 1154 // If a different debug instruction defined the variable value / location 1155 // since the start of the block, don't materialize this use-before-def. 1156 if (!UseBeforeDefVariables.count(Use.Var)) 1157 continue; 1158 1159 PendingDbgValues.push_back(MTracker->emitLoc(L, Use.Var, Use.Properties)); 1160 } 1161 flushDbgValues(pos, nullptr); 1162 } 1163 1164 /// Helper to move created DBG_VALUEs into Transfers collection. 1165 void flushDbgValues(MachineBasicBlock::iterator Pos, MachineBasicBlock *MBB) { 1166 if (PendingDbgValues.size() == 0) 1167 return; 1168 1169 // Pick out the instruction start position. 1170 MachineBasicBlock::instr_iterator BundleStart; 1171 if (MBB && Pos == MBB->begin()) 1172 BundleStart = MBB->instr_begin(); 1173 else 1174 BundleStart = getBundleStart(Pos->getIterator()); 1175 1176 Transfers.push_back({BundleStart, MBB, PendingDbgValues}); 1177 PendingDbgValues.clear(); 1178 } 1179 1180 bool isEntryValueVariable(const DebugVariable &Var, 1181 const DIExpression *Expr) const { 1182 if (!Var.getVariable()->isParameter()) 1183 return false; 1184 1185 if (Var.getInlinedAt()) 1186 return false; 1187 1188 if (Expr->getNumElements() > 0) 1189 return false; 1190 1191 return true; 1192 } 1193 1194 bool isEntryValueValue(const ValueIDNum &Val) const { 1195 // Must be in entry block (block number zero), and be a PHI / live-in value. 1196 if (Val.getBlock() || !Val.isPHI()) 1197 return false; 1198 1199 // Entry values must enter in a register. 1200 if (MTracker->isSpill(Val.getLoc())) 1201 return false; 1202 1203 Register SP = TLI->getStackPointerRegisterToSaveRestore(); 1204 Register FP = TRI.getFrameRegister(MF); 1205 Register Reg = MTracker->LocIdxToLocID[Val.getLoc()]; 1206 return Reg != SP && Reg != FP; 1207 } 1208 1209 bool recoverAsEntryValue(const DebugVariable &Var, DbgValueProperties &Prop, 1210 const ValueIDNum &Num) { 1211 // Is this variable location a candidate to be an entry value. First, 1212 // should we be trying this at all? 1213 if (!ShouldEmitDebugEntryValues) 1214 return false; 1215 1216 // Is the variable appropriate for entry values (i.e., is a parameter). 1217 if (!isEntryValueVariable(Var, Prop.DIExpr)) 1218 return false; 1219 1220 // Is the value assigned to this variable still the entry value? 1221 if (!isEntryValueValue(Num)) 1222 return false; 1223 1224 // Emit a variable location using an entry value expression. 1225 DIExpression *NewExpr = 1226 DIExpression::prepend(Prop.DIExpr, DIExpression::EntryValue); 1227 Register Reg = MTracker->LocIdxToLocID[Num.getLoc()]; 1228 MachineOperand MO = MachineOperand::CreateReg(Reg, false); 1229 MO.setIsDebug(true); 1230 1231 PendingDbgValues.push_back(emitMOLoc(MO, Var, {NewExpr, Prop.Indirect})); 1232 return true; 1233 } 1234 1235 /// Change a variable value after encountering a DBG_VALUE inside a block. 1236 void redefVar(const MachineInstr &MI) { 1237 DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(), 1238 MI.getDebugLoc()->getInlinedAt()); 1239 DbgValueProperties Properties(MI); 1240 1241 const MachineOperand &MO = MI.getOperand(0); 1242 1243 // Ignore non-register locations, we don't transfer those. 1244 if (!MO.isReg() || MO.getReg() == 0) { 1245 auto It = ActiveVLocs.find(Var); 1246 if (It != ActiveVLocs.end()) { 1247 ActiveMLocs[It->second.Loc].erase(Var); 1248 ActiveVLocs.erase(It); 1249 } 1250 // Any use-before-defs no longer apply. 1251 UseBeforeDefVariables.erase(Var); 1252 return; 1253 } 1254 1255 Register Reg = MO.getReg(); 1256 LocIdx NewLoc = MTracker->getRegMLoc(Reg); 1257 redefVar(MI, Properties, NewLoc); 1258 } 1259 1260 /// Handle a change in variable location within a block. Terminate the 1261 /// variables current location, and record the value it now refers to, so 1262 /// that we can detect location transfers later on. 1263 void redefVar(const MachineInstr &MI, const DbgValueProperties &Properties, 1264 Optional<LocIdx> OptNewLoc) { 1265 DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(), 1266 MI.getDebugLoc()->getInlinedAt()); 1267 // Any use-before-defs no longer apply. 1268 UseBeforeDefVariables.erase(Var); 1269 1270 // Erase any previous location, 1271 auto It = ActiveVLocs.find(Var); 1272 if (It != ActiveVLocs.end()) 1273 ActiveMLocs[It->second.Loc].erase(Var); 1274 1275 // If there _is_ no new location, all we had to do was erase. 1276 if (!OptNewLoc) 1277 return; 1278 LocIdx NewLoc = *OptNewLoc; 1279 1280 // Check whether our local copy of values-by-location in #VarLocs is out of 1281 // date. Wipe old tracking data for the location if it's been clobbered in 1282 // the meantime. 1283 if (MTracker->getNumAtPos(NewLoc) != VarLocs[NewLoc.asU64()]) { 1284 for (auto &P : ActiveMLocs[NewLoc]) { 1285 ActiveVLocs.erase(P); 1286 } 1287 ActiveMLocs[NewLoc.asU64()].clear(); 1288 VarLocs[NewLoc.asU64()] = MTracker->getNumAtPos(NewLoc); 1289 } 1290 1291 ActiveMLocs[NewLoc].insert(Var); 1292 if (It == ActiveVLocs.end()) { 1293 ActiveVLocs.insert( 1294 std::make_pair(Var, LocAndProperties{NewLoc, Properties})); 1295 } else { 1296 It->second.Loc = NewLoc; 1297 It->second.Properties = Properties; 1298 } 1299 } 1300 1301 /// Account for a location \p mloc being clobbered. Examine the variable 1302 /// locations that will be terminated: and try to recover them by using 1303 /// another location. Optionally, given \p MakeUndef, emit a DBG_VALUE to 1304 /// explicitly terminate a location if it can't be recovered. 1305 void clobberMloc(LocIdx MLoc, MachineBasicBlock::iterator Pos, 1306 bool MakeUndef = true) { 1307 auto ActiveMLocIt = ActiveMLocs.find(MLoc); 1308 if (ActiveMLocIt == ActiveMLocs.end()) 1309 return; 1310 1311 // What was the old variable value? 1312 ValueIDNum OldValue = VarLocs[MLoc.asU64()]; 1313 VarLocs[MLoc.asU64()] = ValueIDNum::EmptyValue; 1314 1315 // Examine the remaining variable locations: if we can find the same value 1316 // again, we can recover the location. 1317 Optional<LocIdx> NewLoc = None; 1318 for (auto Loc : MTracker->locations()) 1319 if (Loc.Value == OldValue) 1320 NewLoc = Loc.Idx; 1321 1322 // If there is no location, and we weren't asked to make the variable 1323 // explicitly undef, then stop here. 1324 if (!NewLoc && !MakeUndef) { 1325 // Try and recover a few more locations with entry values. 1326 for (auto &Var : ActiveMLocIt->second) { 1327 auto &Prop = ActiveVLocs.find(Var)->second.Properties; 1328 recoverAsEntryValue(Var, Prop, OldValue); 1329 } 1330 flushDbgValues(Pos, nullptr); 1331 return; 1332 } 1333 1334 // Examine all the variables based on this location. 1335 DenseSet<DebugVariable> NewMLocs; 1336 for (auto &Var : ActiveMLocIt->second) { 1337 auto ActiveVLocIt = ActiveVLocs.find(Var); 1338 // Re-state the variable location: if there's no replacement then NewLoc 1339 // is None and a $noreg DBG_VALUE will be created. Otherwise, a DBG_VALUE 1340 // identifying the alternative location will be emitted. 1341 const DIExpression *Expr = ActiveVLocIt->second.Properties.DIExpr; 1342 DbgValueProperties Properties(Expr, false); 1343 PendingDbgValues.push_back(MTracker->emitLoc(NewLoc, Var, Properties)); 1344 1345 // Update machine locations <=> variable locations maps. Defer updating 1346 // ActiveMLocs to avoid invalidaing the ActiveMLocIt iterator. 1347 if (!NewLoc) { 1348 ActiveVLocs.erase(ActiveVLocIt); 1349 } else { 1350 ActiveVLocIt->second.Loc = *NewLoc; 1351 NewMLocs.insert(Var); 1352 } 1353 } 1354 1355 // Commit any deferred ActiveMLoc changes. 1356 if (!NewMLocs.empty()) 1357 for (auto &Var : NewMLocs) 1358 ActiveMLocs[*NewLoc].insert(Var); 1359 1360 // We lazily track what locations have which values; if we've found a new 1361 // location for the clobbered value, remember it. 1362 if (NewLoc) 1363 VarLocs[NewLoc->asU64()] = OldValue; 1364 1365 flushDbgValues(Pos, nullptr); 1366 1367 ActiveMLocIt->second.clear(); 1368 } 1369 1370 /// Transfer variables based on \p Src to be based on \p Dst. This handles 1371 /// both register copies as well as spills and restores. Creates DBG_VALUEs 1372 /// describing the movement. 1373 void transferMlocs(LocIdx Src, LocIdx Dst, MachineBasicBlock::iterator Pos) { 1374 // Does Src still contain the value num we expect? If not, it's been 1375 // clobbered in the meantime, and our variable locations are stale. 1376 if (VarLocs[Src.asU64()] != MTracker->getNumAtPos(Src)) 1377 return; 1378 1379 // assert(ActiveMLocs[Dst].size() == 0); 1380 //^^^ Legitimate scenario on account of un-clobbered slot being assigned to? 1381 ActiveMLocs[Dst] = ActiveMLocs[Src]; 1382 VarLocs[Dst.asU64()] = VarLocs[Src.asU64()]; 1383 1384 // For each variable based on Src; create a location at Dst. 1385 for (auto &Var : ActiveMLocs[Src]) { 1386 auto ActiveVLocIt = ActiveVLocs.find(Var); 1387 assert(ActiveVLocIt != ActiveVLocs.end()); 1388 ActiveVLocIt->second.Loc = Dst; 1389 1390 assert(Dst != 0); 1391 MachineInstr *MI = 1392 MTracker->emitLoc(Dst, Var, ActiveVLocIt->second.Properties); 1393 PendingDbgValues.push_back(MI); 1394 } 1395 ActiveMLocs[Src].clear(); 1396 flushDbgValues(Pos, nullptr); 1397 1398 // XXX XXX XXX "pretend to be old LDV" means dropping all tracking data 1399 // about the old location. 1400 if (EmulateOldLDV) 1401 VarLocs[Src.asU64()] = ValueIDNum::EmptyValue; 1402 } 1403 1404 MachineInstrBuilder emitMOLoc(const MachineOperand &MO, 1405 const DebugVariable &Var, 1406 const DbgValueProperties &Properties) { 1407 DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0, 1408 Var.getVariable()->getScope(), 1409 const_cast<DILocation *>(Var.getInlinedAt())); 1410 auto MIB = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE)); 1411 MIB.add(MO); 1412 if (Properties.Indirect) 1413 MIB.addImm(0); 1414 else 1415 MIB.addReg(0); 1416 MIB.addMetadata(Var.getVariable()); 1417 MIB.addMetadata(Properties.DIExpr); 1418 return MIB; 1419 } 1420 }; 1421 1422 class InstrRefBasedLDV : public LDVImpl { 1423 private: 1424 using FragmentInfo = DIExpression::FragmentInfo; 1425 using OptFragmentInfo = Optional<DIExpression::FragmentInfo>; 1426 1427 // Helper while building OverlapMap, a map of all fragments seen for a given 1428 // DILocalVariable. 1429 using VarToFragments = 1430 DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>; 1431 1432 /// Machine location/value transfer function, a mapping of which locations 1433 /// are assigned which new values. 1434 using MLocTransferMap = std::map<LocIdx, ValueIDNum>; 1435 1436 /// Live in/out structure for the variable values: a per-block map of 1437 /// variables to their values. XXX, better name? 1438 using LiveIdxT = 1439 DenseMap<const MachineBasicBlock *, DenseMap<DebugVariable, DbgValue> *>; 1440 1441 using VarAndLoc = std::pair<DebugVariable, DbgValue>; 1442 1443 /// Type for a live-in value: the predecessor block, and its value. 1444 using InValueT = std::pair<MachineBasicBlock *, DbgValue *>; 1445 1446 /// Vector (per block) of a collection (inner smallvector) of live-ins. 1447 /// Used as the result type for the variable value dataflow problem. 1448 using LiveInsT = SmallVector<SmallVector<VarAndLoc, 8>, 8>; 1449 1450 const TargetRegisterInfo *TRI; 1451 const TargetInstrInfo *TII; 1452 const TargetFrameLowering *TFI; 1453 const MachineFrameInfo *MFI; 1454 BitVector CalleeSavedRegs; 1455 LexicalScopes LS; 1456 TargetPassConfig *TPC; 1457 1458 /// Object to track machine locations as we step through a block. Could 1459 /// probably be a field rather than a pointer, as it's always used. 1460 MLocTracker *MTracker; 1461 1462 /// Number of the current block LiveDebugValues is stepping through. 1463 unsigned CurBB; 1464 1465 /// Number of the current instruction LiveDebugValues is evaluating. 1466 unsigned CurInst; 1467 1468 /// Variable tracker -- listens to DBG_VALUEs occurring as InstrRefBasedImpl 1469 /// steps through a block. Reads the values at each location from the 1470 /// MLocTracker object. 1471 VLocTracker *VTracker; 1472 1473 /// Tracker for transfers, listens to DBG_VALUEs and transfers of values 1474 /// between locations during stepping, creates new DBG_VALUEs when values move 1475 /// location. 1476 TransferTracker *TTracker; 1477 1478 /// Blocks which are artificial, i.e. blocks which exclusively contain 1479 /// instructions without DebugLocs, or with line 0 locations. 1480 SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks; 1481 1482 // Mapping of blocks to and from their RPOT order. 1483 DenseMap<unsigned int, MachineBasicBlock *> OrderToBB; 1484 DenseMap<MachineBasicBlock *, unsigned int> BBToOrder; 1485 DenseMap<unsigned, unsigned> BBNumToRPO; 1486 1487 /// Pair of MachineInstr, and its 1-based offset into the containing block. 1488 using InstAndNum = std::pair<const MachineInstr *, unsigned>; 1489 /// Map from debug instruction number to the MachineInstr labelled with that 1490 /// number, and its location within the function. Used to transform 1491 /// instruction numbers in DBG_INSTR_REFs into machine value numbers. 1492 std::map<uint64_t, InstAndNum> DebugInstrNumToInstr; 1493 1494 /// Record of where we observed a DBG_PHI instruction. 1495 class DebugPHIRecord { 1496 public: 1497 uint64_t InstrNum; ///< Instruction number of this DBG_PHI. 1498 MachineBasicBlock *MBB; ///< Block where DBG_PHI occurred. 1499 ValueIDNum ValueRead; ///< The value number read by the DBG_PHI. 1500 LocIdx ReadLoc; ///< Register/Stack location the DBG_PHI reads. 1501 1502 operator unsigned() const { return InstrNum; } 1503 }; 1504 1505 /// Map from instruction numbers defined by DBG_PHIs to a record of what that 1506 /// DBG_PHI read and where. Populated and edited during the machine value 1507 /// location problem -- we use LLVMs SSA Updater to fix changes by 1508 /// optimizations that destroy PHI instructions. 1509 SmallVector<DebugPHIRecord, 32> DebugPHINumToValue; 1510 1511 // Map of overlapping variable fragments. 1512 OverlapMap OverlapFragments; 1513 VarToFragments SeenFragments; 1514 1515 /// Tests whether this instruction is a spill to a stack slot. 1516 bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF); 1517 1518 /// Decide if @MI is a spill instruction and return true if it is. We use 2 1519 /// criteria to make this decision: 1520 /// - Is this instruction a store to a spill slot? 1521 /// - Is there a register operand that is both used and killed? 1522 /// TODO: Store optimization can fold spills into other stores (including 1523 /// other spills). We do not handle this yet (more than one memory operand). 1524 bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF, 1525 unsigned &Reg); 1526 1527 /// If a given instruction is identified as a spill, return the spill slot 1528 /// and set \p Reg to the spilled register. 1529 Optional<SpillLoc> isRestoreInstruction(const MachineInstr &MI, 1530 MachineFunction *MF, unsigned &Reg); 1531 1532 /// Given a spill instruction, extract the register and offset used to 1533 /// address the spill slot in a target independent way. 1534 SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI); 1535 1536 /// Observe a single instruction while stepping through a block. 1537 void process(MachineInstr &MI, ValueIDNum **MLiveOuts = nullptr, 1538 ValueIDNum **MLiveIns = nullptr); 1539 1540 /// Examines whether \p MI is a DBG_VALUE and notifies trackers. 1541 /// \returns true if MI was recognized and processed. 1542 bool transferDebugValue(const MachineInstr &MI); 1543 1544 /// Examines whether \p MI is a DBG_INSTR_REF and notifies trackers. 1545 /// \returns true if MI was recognized and processed. 1546 bool transferDebugInstrRef(MachineInstr &MI, ValueIDNum **MLiveOuts, 1547 ValueIDNum **MLiveIns); 1548 1549 /// Stores value-information about where this PHI occurred, and what 1550 /// instruction number is associated with it. 1551 /// \returns true if MI was recognized and processed. 1552 bool transferDebugPHI(MachineInstr &MI); 1553 1554 /// Examines whether \p MI is copy instruction, and notifies trackers. 1555 /// \returns true if MI was recognized and processed. 1556 bool transferRegisterCopy(MachineInstr &MI); 1557 1558 /// Examines whether \p MI is stack spill or restore instruction, and 1559 /// notifies trackers. \returns true if MI was recognized and processed. 1560 bool transferSpillOrRestoreInst(MachineInstr &MI); 1561 1562 /// Examines \p MI for any registers that it defines, and notifies trackers. 1563 void transferRegisterDef(MachineInstr &MI); 1564 1565 /// Copy one location to the other, accounting for movement of subregisters 1566 /// too. 1567 void performCopy(Register Src, Register Dst); 1568 1569 void accumulateFragmentMap(MachineInstr &MI); 1570 1571 /// Determine the machine value number referred to by (potentially several) 1572 /// DBG_PHI instructions. Block duplication and tail folding can duplicate 1573 /// DBG_PHIs, shifting the position where values in registers merge, and 1574 /// forming another mini-ssa problem to solve. 1575 /// \p Here the position of a DBG_INSTR_REF seeking a machine value number 1576 /// \p InstrNum Debug instruction number defined by DBG_PHI instructions. 1577 /// \returns The machine value number at position Here, or None. 1578 Optional<ValueIDNum> resolveDbgPHIs(MachineFunction &MF, 1579 ValueIDNum **MLiveOuts, 1580 ValueIDNum **MLiveIns, MachineInstr &Here, 1581 uint64_t InstrNum); 1582 1583 /// Step through the function, recording register definitions and movements 1584 /// in an MLocTracker. Convert the observations into a per-block transfer 1585 /// function in \p MLocTransfer, suitable for using with the machine value 1586 /// location dataflow problem. 1587 void 1588 produceMLocTransferFunction(MachineFunction &MF, 1589 SmallVectorImpl<MLocTransferMap> &MLocTransfer, 1590 unsigned MaxNumBlocks); 1591 1592 /// Solve the machine value location dataflow problem. Takes as input the 1593 /// transfer functions in \p MLocTransfer. Writes the output live-in and 1594 /// live-out arrays to the (initialized to zero) multidimensional arrays in 1595 /// \p MInLocs and \p MOutLocs. The outer dimension is indexed by block 1596 /// number, the inner by LocIdx. 1597 void mlocDataflow(ValueIDNum **MInLocs, ValueIDNum **MOutLocs, 1598 SmallVectorImpl<MLocTransferMap> &MLocTransfer); 1599 1600 /// Perform a control flow join (lattice value meet) of the values in machine 1601 /// locations at \p MBB. Follows the algorithm described in the file-comment, 1602 /// reading live-outs of predecessors from \p OutLocs, the current live ins 1603 /// from \p InLocs, and assigning the newly computed live ins back into 1604 /// \p InLocs. \returns two bools -- the first indicates whether a change 1605 /// was made, the second whether a lattice downgrade occurred. If the latter 1606 /// is true, revisiting this block is necessary. 1607 std::tuple<bool, bool> 1608 mlocJoin(MachineBasicBlock &MBB, 1609 SmallPtrSet<const MachineBasicBlock *, 16> &Visited, 1610 ValueIDNum **OutLocs, ValueIDNum *InLocs); 1611 1612 /// Solve the variable value dataflow problem, for a single lexical scope. 1613 /// Uses the algorithm from the file comment to resolve control flow joins, 1614 /// although there are extra hacks, see vlocJoin. Reads the 1615 /// locations of values from the \p MInLocs and \p MOutLocs arrays (see 1616 /// mlocDataflow) and reads the variable values transfer function from 1617 /// \p AllTheVlocs. Live-in and Live-out variable values are stored locally, 1618 /// with the live-ins permanently stored to \p Output once the fixedpoint is 1619 /// reached. 1620 /// \p VarsWeCareAbout contains a collection of the variables in \p Scope 1621 /// that we should be tracking. 1622 /// \p AssignBlocks contains the set of blocks that aren't in \p Scope, but 1623 /// which do contain DBG_VALUEs, which VarLocBasedImpl tracks locations 1624 /// through. 1625 void vlocDataflow(const LexicalScope *Scope, const DILocation *DILoc, 1626 const SmallSet<DebugVariable, 4> &VarsWeCareAbout, 1627 SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, 1628 LiveInsT &Output, ValueIDNum **MOutLocs, 1629 ValueIDNum **MInLocs, 1630 SmallVectorImpl<VLocTracker> &AllTheVLocs); 1631 1632 /// Compute the live-ins to a block, considering control flow merges according 1633 /// to the method in the file comment. Live out and live in variable values 1634 /// are stored in \p VLOCOutLocs and \p VLOCInLocs. The live-ins for \p MBB 1635 /// are computed and stored into \p VLOCInLocs. \returns true if the live-ins 1636 /// are modified. 1637 /// \p InLocsT Output argument, storage for calculated live-ins. 1638 /// \returns two bools -- the first indicates whether a change 1639 /// was made, the second whether a lattice downgrade occurred. If the latter 1640 /// is true, revisiting this block is necessary. 1641 std::tuple<bool, bool> 1642 vlocJoin(MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs, LiveIdxT &VLOCInLocs, 1643 SmallPtrSet<const MachineBasicBlock *, 16> *VLOCVisited, 1644 unsigned BBNum, const SmallSet<DebugVariable, 4> &AllVars, 1645 ValueIDNum **MOutLocs, ValueIDNum **MInLocs, 1646 SmallPtrSet<const MachineBasicBlock *, 8> &InScopeBlocks, 1647 SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore, 1648 DenseMap<DebugVariable, DbgValue> &InLocsT); 1649 1650 /// Continue exploration of the variable-value lattice, as explained in the 1651 /// file-level comment. \p OldLiveInLocation contains the current 1652 /// exploration position, from which we need to descend further. \p Values 1653 /// contains the set of live-in values, \p CurBlockRPONum the RPO number of 1654 /// the current block, and \p CandidateLocations a set of locations that 1655 /// should be considered as PHI locations, if we reach the bottom of the 1656 /// lattice. \returns true if we should downgrade; the value is the agreeing 1657 /// value number in a non-backedge predecessor. 1658 bool vlocDowngradeLattice(const MachineBasicBlock &MBB, 1659 const DbgValue &OldLiveInLocation, 1660 const SmallVectorImpl<InValueT> &Values, 1661 unsigned CurBlockRPONum); 1662 1663 /// For the given block and live-outs feeding into it, try to find a 1664 /// machine location where they all join. If a solution for all predecessors 1665 /// can't be found, a location where all non-backedge-predecessors join 1666 /// will be returned instead. While this method finds a join location, this 1667 /// says nothing as to whether it should be used. 1668 /// \returns Pair of value ID if found, and true when the correct value 1669 /// is available on all predecessor edges, or false if it's only available 1670 /// for non-backedge predecessors. 1671 std::tuple<Optional<ValueIDNum>, bool> 1672 pickVPHILoc(MachineBasicBlock &MBB, const DebugVariable &Var, 1673 const LiveIdxT &LiveOuts, ValueIDNum **MOutLocs, 1674 ValueIDNum **MInLocs, 1675 const SmallVectorImpl<MachineBasicBlock *> &BlockOrders); 1676 1677 /// Given the solutions to the two dataflow problems, machine value locations 1678 /// in \p MInLocs and live-in variable values in \p SavedLiveIns, runs the 1679 /// TransferTracker class over the function to produce live-in and transfer 1680 /// DBG_VALUEs, then inserts them. Groups of DBG_VALUEs are inserted in the 1681 /// order given by AllVarsNumbering -- this could be any stable order, but 1682 /// right now "order of appearence in function, when explored in RPO", so 1683 /// that we can compare explictly against VarLocBasedImpl. 1684 void emitLocations(MachineFunction &MF, LiveInsT SavedLiveIns, 1685 ValueIDNum **MOutLocs, ValueIDNum **MInLocs, 1686 DenseMap<DebugVariable, unsigned> &AllVarsNumbering, 1687 const TargetPassConfig &TPC); 1688 1689 /// Boilerplate computation of some initial sets, artifical blocks and 1690 /// RPOT block ordering. 1691 void initialSetup(MachineFunction &MF); 1692 1693 bool ExtendRanges(MachineFunction &MF, TargetPassConfig *TPC) override; 1694 1695 public: 1696 /// Default construct and initialize the pass. 1697 InstrRefBasedLDV(); 1698 1699 LLVM_DUMP_METHOD 1700 void dump_mloc_transfer(const MLocTransferMap &mloc_transfer) const; 1701 1702 bool isCalleeSaved(LocIdx L) { 1703 unsigned Reg = MTracker->LocIdxToLocID[L]; 1704 for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI) 1705 if (CalleeSavedRegs.test(*RAI)) 1706 return true; 1707 return false; 1708 } 1709 }; 1710 1711 } // end anonymous namespace 1712 1713 //===----------------------------------------------------------------------===// 1714 // Implementation 1715 //===----------------------------------------------------------------------===// 1716 1717 ValueIDNum ValueIDNum::EmptyValue = {UINT_MAX, UINT_MAX, UINT_MAX}; 1718 1719 /// Default construct and initialize the pass. 1720 InstrRefBasedLDV::InstrRefBasedLDV() {} 1721 1722 //===----------------------------------------------------------------------===// 1723 // Debug Range Extension Implementation 1724 //===----------------------------------------------------------------------===// 1725 1726 #ifndef NDEBUG 1727 // Something to restore in the future. 1728 // void InstrRefBasedLDV::printVarLocInMBB(..) 1729 #endif 1730 1731 SpillLoc 1732 InstrRefBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) { 1733 assert(MI.hasOneMemOperand() && 1734 "Spill instruction does not have exactly one memory operand?"); 1735 auto MMOI = MI.memoperands_begin(); 1736 const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue(); 1737 assert(PVal->kind() == PseudoSourceValue::FixedStack && 1738 "Inconsistent memory operand in spill instruction"); 1739 int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex(); 1740 const MachineBasicBlock *MBB = MI.getParent(); 1741 Register Reg; 1742 StackOffset Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg); 1743 return {Reg, Offset}; 1744 } 1745 1746 /// End all previous ranges related to @MI and start a new range from @MI 1747 /// if it is a DBG_VALUE instr. 1748 bool InstrRefBasedLDV::transferDebugValue(const MachineInstr &MI) { 1749 if (!MI.isDebugValue()) 1750 return false; 1751 1752 const DILocalVariable *Var = MI.getDebugVariable(); 1753 const DIExpression *Expr = MI.getDebugExpression(); 1754 const DILocation *DebugLoc = MI.getDebugLoc(); 1755 const DILocation *InlinedAt = DebugLoc->getInlinedAt(); 1756 assert(Var->isValidLocationForIntrinsic(DebugLoc) && 1757 "Expected inlined-at fields to agree"); 1758 1759 DebugVariable V(Var, Expr, InlinedAt); 1760 DbgValueProperties Properties(MI); 1761 1762 // If there are no instructions in this lexical scope, do no location tracking 1763 // at all, this variable shouldn't get a legitimate location range. 1764 auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get()); 1765 if (Scope == nullptr) 1766 return true; // handled it; by doing nothing 1767 1768 const MachineOperand &MO = MI.getOperand(0); 1769 1770 // MLocTracker needs to know that this register is read, even if it's only 1771 // read by a debug inst. 1772 if (MO.isReg() && MO.getReg() != 0) 1773 (void)MTracker->readReg(MO.getReg()); 1774 1775 // If we're preparing for the second analysis (variables), the machine value 1776 // locations are already solved, and we report this DBG_VALUE and the value 1777 // it refers to to VLocTracker. 1778 if (VTracker) { 1779 if (MO.isReg()) { 1780 // Feed defVar the new variable location, or if this is a 1781 // DBG_VALUE $noreg, feed defVar None. 1782 if (MO.getReg()) 1783 VTracker->defVar(MI, Properties, MTracker->readReg(MO.getReg())); 1784 else 1785 VTracker->defVar(MI, Properties, None); 1786 } else if (MI.getOperand(0).isImm() || MI.getOperand(0).isFPImm() || 1787 MI.getOperand(0).isCImm()) { 1788 VTracker->defVar(MI, MI.getOperand(0)); 1789 } 1790 } 1791 1792 // If performing final tracking of transfers, report this variable definition 1793 // to the TransferTracker too. 1794 if (TTracker) 1795 TTracker->redefVar(MI); 1796 return true; 1797 } 1798 1799 bool InstrRefBasedLDV::transferDebugInstrRef(MachineInstr &MI, 1800 ValueIDNum **MLiveOuts, 1801 ValueIDNum **MLiveIns) { 1802 if (!MI.isDebugRef()) 1803 return false; 1804 1805 // Only handle this instruction when we are building the variable value 1806 // transfer function. 1807 if (!VTracker) 1808 return false; 1809 1810 unsigned InstNo = MI.getOperand(0).getImm(); 1811 unsigned OpNo = MI.getOperand(1).getImm(); 1812 1813 const DILocalVariable *Var = MI.getDebugVariable(); 1814 const DIExpression *Expr = MI.getDebugExpression(); 1815 const DILocation *DebugLoc = MI.getDebugLoc(); 1816 const DILocation *InlinedAt = DebugLoc->getInlinedAt(); 1817 assert(Var->isValidLocationForIntrinsic(DebugLoc) && 1818 "Expected inlined-at fields to agree"); 1819 1820 DebugVariable V(Var, Expr, InlinedAt); 1821 1822 auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get()); 1823 if (Scope == nullptr) 1824 return true; // Handled by doing nothing. This variable is never in scope. 1825 1826 const MachineFunction &MF = *MI.getParent()->getParent(); 1827 1828 // Various optimizations may have happened to the value during codegen, 1829 // recorded in the value substitution table. Apply any substitutions to 1830 // the instruction / operand number in this DBG_INSTR_REF. 1831 auto Sub = MF.DebugValueSubstitutions.find(std::make_pair(InstNo, OpNo)); 1832 while (Sub != MF.DebugValueSubstitutions.end()) { 1833 InstNo = Sub->second.first; 1834 OpNo = Sub->second.second; 1835 Sub = MF.DebugValueSubstitutions.find(std::make_pair(InstNo, OpNo)); 1836 } 1837 1838 // Default machine value number is <None> -- if no instruction defines 1839 // the corresponding value, it must have been optimized out. 1840 Optional<ValueIDNum> NewID = None; 1841 1842 // Try to lookup the instruction number, and find the machine value number 1843 // that it defines. It could be an instruction, or a PHI. 1844 auto InstrIt = DebugInstrNumToInstr.find(InstNo); 1845 auto PHIIt = std::lower_bound(DebugPHINumToValue.begin(), 1846 DebugPHINumToValue.end(), InstNo); 1847 if (InstrIt != DebugInstrNumToInstr.end()) { 1848 const MachineInstr &TargetInstr = *InstrIt->second.first; 1849 uint64_t BlockNo = TargetInstr.getParent()->getNumber(); 1850 1851 // Pick out the designated operand. 1852 assert(OpNo < TargetInstr.getNumOperands()); 1853 const MachineOperand &MO = TargetInstr.getOperand(OpNo); 1854 1855 // Today, this can only be a register. 1856 assert(MO.isReg() && MO.isDef()); 1857 1858 unsigned LocID = MTracker->getLocID(MO.getReg(), false); 1859 LocIdx L = MTracker->LocIDToLocIdx[LocID]; 1860 NewID = ValueIDNum(BlockNo, InstrIt->second.second, L); 1861 } else if (PHIIt != DebugPHINumToValue.end() && PHIIt->InstrNum == InstNo) { 1862 // It's actually a PHI value. Which value it is might not be obvious, use 1863 // the resolver helper to find out. 1864 NewID = resolveDbgPHIs(*MI.getParent()->getParent(), MLiveOuts, MLiveIns, 1865 MI, InstNo); 1866 } 1867 1868 // We, we have a value number or None. Tell the variable value tracker about 1869 // it. The rest of this LiveDebugValues implementation acts exactly the same 1870 // for DBG_INSTR_REFs as DBG_VALUEs (just, the former can refer to values that 1871 // aren't immediately available). 1872 DbgValueProperties Properties(Expr, false); 1873 VTracker->defVar(MI, Properties, NewID); 1874 1875 // If we're on the final pass through the function, decompose this INSTR_REF 1876 // into a plain DBG_VALUE. 1877 if (!TTracker) 1878 return true; 1879 1880 // Pick a location for the machine value number, if such a location exists. 1881 // (This information could be stored in TransferTracker to make it faster). 1882 Optional<LocIdx> FoundLoc = None; 1883 for (auto Location : MTracker->locations()) { 1884 LocIdx CurL = Location.Idx; 1885 ValueIDNum ID = MTracker->LocIdxToIDNum[CurL]; 1886 if (NewID && ID == NewID) { 1887 // If this is the first location with that value, pick it. Otherwise, 1888 // consider whether it's a "longer term" location. 1889 if (!FoundLoc) { 1890 FoundLoc = CurL; 1891 continue; 1892 } 1893 1894 if (MTracker->isSpill(CurL)) 1895 FoundLoc = CurL; // Spills are a longer term location. 1896 else if (!MTracker->isSpill(*FoundLoc) && 1897 !MTracker->isSpill(CurL) && 1898 !isCalleeSaved(*FoundLoc) && 1899 isCalleeSaved(CurL)) 1900 FoundLoc = CurL; // Callee saved regs are longer term than normal. 1901 } 1902 } 1903 1904 // Tell transfer tracker that the variable value has changed. 1905 TTracker->redefVar(MI, Properties, FoundLoc); 1906 1907 // If there was a value with no location; but the value is defined in a 1908 // later instruction in this block, this is a block-local use-before-def. 1909 if (!FoundLoc && NewID && NewID->getBlock() == CurBB && 1910 NewID->getInst() > CurInst) 1911 TTracker->addUseBeforeDef(V, {MI.getDebugExpression(), false}, *NewID); 1912 1913 // Produce a DBG_VALUE representing what this DBG_INSTR_REF meant. 1914 // This DBG_VALUE is potentially a $noreg / undefined location, if 1915 // FoundLoc is None. 1916 // (XXX -- could morph the DBG_INSTR_REF in the future). 1917 MachineInstr *DbgMI = MTracker->emitLoc(FoundLoc, V, Properties); 1918 TTracker->PendingDbgValues.push_back(DbgMI); 1919 TTracker->flushDbgValues(MI.getIterator(), nullptr); 1920 return true; 1921 } 1922 1923 bool InstrRefBasedLDV::transferDebugPHI(MachineInstr &MI) { 1924 if (!MI.isDebugPHI()) 1925 return false; 1926 1927 // Analyse these only when solving the machine value location problem. 1928 if (VTracker || TTracker) 1929 return true; 1930 1931 // First operand is the value location, either a stack slot or register. 1932 // Second is the debug instruction number of the original PHI. 1933 const MachineOperand &MO = MI.getOperand(0); 1934 unsigned InstrNum = MI.getOperand(1).getImm(); 1935 1936 if (MO.isReg()) { 1937 // The value is whatever's currently in the register. Read and record it, 1938 // to be analysed later. 1939 Register Reg = MO.getReg(); 1940 ValueIDNum Num = MTracker->readReg(Reg); 1941 auto PHIRec = DebugPHIRecord( 1942 {InstrNum, MI.getParent(), Num, MTracker->lookupOrTrackRegister(Reg)}); 1943 DebugPHINumToValue.push_back(PHIRec); 1944 } else { 1945 // The value is whatever's in this stack slot. 1946 assert(MO.isFI()); 1947 unsigned FI = MO.getIndex(); 1948 1949 // If the stack slot is dead, then this was optimized away. 1950 // FIXME: stack slot colouring should account for slots that get merged. 1951 if (MFI->isDeadObjectIndex(FI)) 1952 return true; 1953 1954 // Identify this spill slot. 1955 Register Base; 1956 StackOffset Offs = TFI->getFrameIndexReference(*MI.getMF(), FI, Base); 1957 SpillLoc SL = {Base, Offs}; 1958 Optional<ValueIDNum> Num = MTracker->readSpill(SL); 1959 1960 if (!Num) 1961 // Nothing ever writes to this slot. Curious, but nothing we can do. 1962 return true; 1963 1964 // Record this DBG_PHI for later analysis. 1965 auto DbgPHI = DebugPHIRecord( 1966 {InstrNum, MI.getParent(), *Num, *MTracker->getSpillMLoc(SL)}); 1967 DebugPHINumToValue.push_back(DbgPHI); 1968 } 1969 1970 return true; 1971 } 1972 1973 void InstrRefBasedLDV::transferRegisterDef(MachineInstr &MI) { 1974 // Meta Instructions do not affect the debug liveness of any register they 1975 // define. 1976 if (MI.isImplicitDef()) { 1977 // Except when there's an implicit def, and the location it's defining has 1978 // no value number. The whole point of an implicit def is to announce that 1979 // the register is live, without be specific about it's value. So define 1980 // a value if there isn't one already. 1981 ValueIDNum Num = MTracker->readReg(MI.getOperand(0).getReg()); 1982 // Has a legitimate value -> ignore the implicit def. 1983 if (Num.getLoc() != 0) 1984 return; 1985 // Otherwise, def it here. 1986 } else if (MI.isMetaInstruction()) 1987 return; 1988 1989 MachineFunction *MF = MI.getMF(); 1990 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering(); 1991 Register SP = TLI->getStackPointerRegisterToSaveRestore(); 1992 1993 // Find the regs killed by MI, and find regmasks of preserved regs. 1994 // Max out the number of statically allocated elements in `DeadRegs`, as this 1995 // prevents fallback to std::set::count() operations. 1996 SmallSet<uint32_t, 32> DeadRegs; 1997 SmallVector<const uint32_t *, 4> RegMasks; 1998 SmallVector<const MachineOperand *, 4> RegMaskPtrs; 1999 for (const MachineOperand &MO : MI.operands()) { 2000 // Determine whether the operand is a register def. 2001 if (MO.isReg() && MO.isDef() && MO.getReg() && 2002 Register::isPhysicalRegister(MO.getReg()) && 2003 !(MI.isCall() && MO.getReg() == SP)) { 2004 // Remove ranges of all aliased registers. 2005 for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI) 2006 // FIXME: Can we break out of this loop early if no insertion occurs? 2007 DeadRegs.insert(*RAI); 2008 } else if (MO.isRegMask()) { 2009 RegMasks.push_back(MO.getRegMask()); 2010 RegMaskPtrs.push_back(&MO); 2011 } 2012 } 2013 2014 // Tell MLocTracker about all definitions, of regmasks and otherwise. 2015 for (uint32_t DeadReg : DeadRegs) 2016 MTracker->defReg(DeadReg, CurBB, CurInst); 2017 2018 for (auto *MO : RegMaskPtrs) 2019 MTracker->writeRegMask(MO, CurBB, CurInst); 2020 2021 if (!TTracker) 2022 return; 2023 2024 // When committing variable values to locations: tell transfer tracker that 2025 // we've clobbered things. It may be able to recover the variable from a 2026 // different location. 2027 2028 // Inform TTracker about any direct clobbers. 2029 for (uint32_t DeadReg : DeadRegs) { 2030 LocIdx Loc = MTracker->lookupOrTrackRegister(DeadReg); 2031 TTracker->clobberMloc(Loc, MI.getIterator(), false); 2032 } 2033 2034 // Look for any clobbers performed by a register mask. Only test locations 2035 // that are actually being tracked. 2036 for (auto L : MTracker->locations()) { 2037 // Stack locations can't be clobbered by regmasks. 2038 if (MTracker->isSpill(L.Idx)) 2039 continue; 2040 2041 Register Reg = MTracker->LocIdxToLocID[L.Idx]; 2042 for (auto *MO : RegMaskPtrs) 2043 if (MO->clobbersPhysReg(Reg)) 2044 TTracker->clobberMloc(L.Idx, MI.getIterator(), false); 2045 } 2046 } 2047 2048 void InstrRefBasedLDV::performCopy(Register SrcRegNum, Register DstRegNum) { 2049 ValueIDNum SrcValue = MTracker->readReg(SrcRegNum); 2050 2051 MTracker->setReg(DstRegNum, SrcValue); 2052 2053 // In all circumstances, re-def the super registers. It's definitely a new 2054 // value now. This doesn't uniquely identify the composition of subregs, for 2055 // example, two identical values in subregisters composed in different 2056 // places would not get equal value numbers. 2057 for (MCSuperRegIterator SRI(DstRegNum, TRI); SRI.isValid(); ++SRI) 2058 MTracker->defReg(*SRI, CurBB, CurInst); 2059 2060 // If we're emulating VarLocBasedImpl, just define all the subregisters. 2061 // DBG_VALUEs of them will expect to be tracked from the DBG_VALUE, not 2062 // through prior copies. 2063 if (EmulateOldLDV) { 2064 for (MCSubRegIndexIterator DRI(DstRegNum, TRI); DRI.isValid(); ++DRI) 2065 MTracker->defReg(DRI.getSubReg(), CurBB, CurInst); 2066 return; 2067 } 2068 2069 // Otherwise, actually copy subregisters from one location to another. 2070 // XXX: in addition, any subregisters of DstRegNum that don't line up with 2071 // the source register should be def'd. 2072 for (MCSubRegIndexIterator SRI(SrcRegNum, TRI); SRI.isValid(); ++SRI) { 2073 unsigned SrcSubReg = SRI.getSubReg(); 2074 unsigned SubRegIdx = SRI.getSubRegIndex(); 2075 unsigned DstSubReg = TRI->getSubReg(DstRegNum, SubRegIdx); 2076 if (!DstSubReg) 2077 continue; 2078 2079 // Do copy. There are two matching subregisters, the source value should 2080 // have been def'd when the super-reg was, the latter might not be tracked 2081 // yet. 2082 // This will force SrcSubReg to be tracked, if it isn't yet. 2083 (void)MTracker->readReg(SrcSubReg); 2084 LocIdx SrcL = MTracker->getRegMLoc(SrcSubReg); 2085 assert(SrcL.asU64()); 2086 (void)MTracker->readReg(DstSubReg); 2087 LocIdx DstL = MTracker->getRegMLoc(DstSubReg); 2088 assert(DstL.asU64()); 2089 (void)DstL; 2090 ValueIDNum CpyValue = {SrcValue.getBlock(), SrcValue.getInst(), SrcL}; 2091 2092 MTracker->setReg(DstSubReg, CpyValue); 2093 } 2094 } 2095 2096 bool InstrRefBasedLDV::isSpillInstruction(const MachineInstr &MI, 2097 MachineFunction *MF) { 2098 // TODO: Handle multiple stores folded into one. 2099 if (!MI.hasOneMemOperand()) 2100 return false; 2101 2102 if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII)) 2103 return false; // This is not a spill instruction, since no valid size was 2104 // returned from either function. 2105 2106 return true; 2107 } 2108 2109 bool InstrRefBasedLDV::isLocationSpill(const MachineInstr &MI, 2110 MachineFunction *MF, unsigned &Reg) { 2111 if (!isSpillInstruction(MI, MF)) 2112 return false; 2113 2114 // XXX FIXME: On x86, isStoreToStackSlotPostFE returns '1' instead of an 2115 // actual register number. 2116 if (ObserveAllStackops) { 2117 int FI; 2118 Reg = TII->isStoreToStackSlotPostFE(MI, FI); 2119 return Reg != 0; 2120 } 2121 2122 auto isKilledReg = [&](const MachineOperand MO, unsigned &Reg) { 2123 if (!MO.isReg() || !MO.isUse()) { 2124 Reg = 0; 2125 return false; 2126 } 2127 Reg = MO.getReg(); 2128 return MO.isKill(); 2129 }; 2130 2131 for (const MachineOperand &MO : MI.operands()) { 2132 // In a spill instruction generated by the InlineSpiller the spilled 2133 // register has its kill flag set. 2134 if (isKilledReg(MO, Reg)) 2135 return true; 2136 if (Reg != 0) { 2137 // Check whether next instruction kills the spilled register. 2138 // FIXME: Current solution does not cover search for killed register in 2139 // bundles and instructions further down the chain. 2140 auto NextI = std::next(MI.getIterator()); 2141 // Skip next instruction that points to basic block end iterator. 2142 if (MI.getParent()->end() == NextI) 2143 continue; 2144 unsigned RegNext; 2145 for (const MachineOperand &MONext : NextI->operands()) { 2146 // Return true if we came across the register from the 2147 // previous spill instruction that is killed in NextI. 2148 if (isKilledReg(MONext, RegNext) && RegNext == Reg) 2149 return true; 2150 } 2151 } 2152 } 2153 // Return false if we didn't find spilled register. 2154 return false; 2155 } 2156 2157 Optional<SpillLoc> 2158 InstrRefBasedLDV::isRestoreInstruction(const MachineInstr &MI, 2159 MachineFunction *MF, unsigned &Reg) { 2160 if (!MI.hasOneMemOperand()) 2161 return None; 2162 2163 // FIXME: Handle folded restore instructions with more than one memory 2164 // operand. 2165 if (MI.getRestoreSize(TII)) { 2166 Reg = MI.getOperand(0).getReg(); 2167 return extractSpillBaseRegAndOffset(MI); 2168 } 2169 return None; 2170 } 2171 2172 bool InstrRefBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI) { 2173 // XXX -- it's too difficult to implement VarLocBasedImpl's stack location 2174 // limitations under the new model. Therefore, when comparing them, compare 2175 // versions that don't attempt spills or restores at all. 2176 if (EmulateOldLDV) 2177 return false; 2178 2179 MachineFunction *MF = MI.getMF(); 2180 unsigned Reg; 2181 Optional<SpillLoc> Loc; 2182 2183 LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump();); 2184 2185 // First, if there are any DBG_VALUEs pointing at a spill slot that is 2186 // written to, terminate that variable location. The value in memory 2187 // will have changed. DbgEntityHistoryCalculator doesn't try to detect this. 2188 if (isSpillInstruction(MI, MF)) { 2189 Loc = extractSpillBaseRegAndOffset(MI); 2190 2191 if (TTracker) { 2192 Optional<LocIdx> MLoc = MTracker->getSpillMLoc(*Loc); 2193 if (MLoc) { 2194 // Un-set this location before clobbering, so that we don't salvage 2195 // the variable location back to the same place. 2196 MTracker->setMLoc(*MLoc, ValueIDNum::EmptyValue); 2197 TTracker->clobberMloc(*MLoc, MI.getIterator()); 2198 } 2199 } 2200 } 2201 2202 // Try to recognise spill and restore instructions that may transfer a value. 2203 if (isLocationSpill(MI, MF, Reg)) { 2204 Loc = extractSpillBaseRegAndOffset(MI); 2205 auto ValueID = MTracker->readReg(Reg); 2206 2207 // If the location is empty, produce a phi, signify it's the live-in value. 2208 if (ValueID.getLoc() == 0) 2209 ValueID = {CurBB, 0, MTracker->getRegMLoc(Reg)}; 2210 2211 MTracker->setSpill(*Loc, ValueID); 2212 auto OptSpillLocIdx = MTracker->getSpillMLoc(*Loc); 2213 assert(OptSpillLocIdx && "Spill slot set but has no LocIdx?"); 2214 LocIdx SpillLocIdx = *OptSpillLocIdx; 2215 2216 // Tell TransferTracker about this spill, produce DBG_VALUEs for it. 2217 if (TTracker) 2218 TTracker->transferMlocs(MTracker->getRegMLoc(Reg), SpillLocIdx, 2219 MI.getIterator()); 2220 } else { 2221 if (!(Loc = isRestoreInstruction(MI, MF, Reg))) 2222 return false; 2223 2224 // Is there a value to be restored? 2225 auto OptValueID = MTracker->readSpill(*Loc); 2226 if (OptValueID) { 2227 ValueIDNum ValueID = *OptValueID; 2228 LocIdx SpillLocIdx = *MTracker->getSpillMLoc(*Loc); 2229 // XXX -- can we recover sub-registers of this value? Until we can, first 2230 // overwrite all defs of the register being restored to. 2231 for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI) 2232 MTracker->defReg(*RAI, CurBB, CurInst); 2233 2234 // Now override the reg we're restoring to. 2235 MTracker->setReg(Reg, ValueID); 2236 2237 // Report this restore to the transfer tracker too. 2238 if (TTracker) 2239 TTracker->transferMlocs(SpillLocIdx, MTracker->getRegMLoc(Reg), 2240 MI.getIterator()); 2241 } else { 2242 // There isn't anything in the location; not clear if this is a code path 2243 // that still runs. Def this register anyway just in case. 2244 for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI) 2245 MTracker->defReg(*RAI, CurBB, CurInst); 2246 2247 // Force the spill slot to be tracked. 2248 LocIdx L = MTracker->getOrTrackSpillLoc(*Loc); 2249 2250 // Set the restored value to be a machine phi number, signifying that it's 2251 // whatever the spills live-in value is in this block. Definitely has 2252 // a LocIdx due to the setSpill above. 2253 ValueIDNum ValueID = {CurBB, 0, L}; 2254 MTracker->setReg(Reg, ValueID); 2255 MTracker->setSpill(*Loc, ValueID); 2256 } 2257 } 2258 return true; 2259 } 2260 2261 bool InstrRefBasedLDV::transferRegisterCopy(MachineInstr &MI) { 2262 auto DestSrc = TII->isCopyInstr(MI); 2263 if (!DestSrc) 2264 return false; 2265 2266 const MachineOperand *DestRegOp = DestSrc->Destination; 2267 const MachineOperand *SrcRegOp = DestSrc->Source; 2268 2269 auto isCalleeSavedReg = [&](unsigned Reg) { 2270 for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI) 2271 if (CalleeSavedRegs.test(*RAI)) 2272 return true; 2273 return false; 2274 }; 2275 2276 Register SrcReg = SrcRegOp->getReg(); 2277 Register DestReg = DestRegOp->getReg(); 2278 2279 // Ignore identity copies. Yep, these make it as far as LiveDebugValues. 2280 if (SrcReg == DestReg) 2281 return true; 2282 2283 // For emulating VarLocBasedImpl: 2284 // We want to recognize instructions where destination register is callee 2285 // saved register. If register that could be clobbered by the call is 2286 // included, there would be a great chance that it is going to be clobbered 2287 // soon. It is more likely that previous register, which is callee saved, is 2288 // going to stay unclobbered longer, even if it is killed. 2289 // 2290 // For InstrRefBasedImpl, we can track multiple locations per value, so 2291 // ignore this condition. 2292 if (EmulateOldLDV && !isCalleeSavedReg(DestReg)) 2293 return false; 2294 2295 // InstrRefBasedImpl only followed killing copies. 2296 if (EmulateOldLDV && !SrcRegOp->isKill()) 2297 return false; 2298 2299 // Copy MTracker info, including subregs if available. 2300 InstrRefBasedLDV::performCopy(SrcReg, DestReg); 2301 2302 // Only produce a transfer of DBG_VALUE within a block where old LDV 2303 // would have. We might make use of the additional value tracking in some 2304 // other way, later. 2305 if (TTracker && isCalleeSavedReg(DestReg) && SrcRegOp->isKill()) 2306 TTracker->transferMlocs(MTracker->getRegMLoc(SrcReg), 2307 MTracker->getRegMLoc(DestReg), MI.getIterator()); 2308 2309 // VarLocBasedImpl would quit tracking the old location after copying. 2310 if (EmulateOldLDV && SrcReg != DestReg) 2311 MTracker->defReg(SrcReg, CurBB, CurInst); 2312 2313 // Finally, the copy might have clobbered variables based on the destination 2314 // register. Tell TTracker about it, in case a backup location exists. 2315 if (TTracker) { 2316 for (MCRegAliasIterator RAI(DestReg, TRI, true); RAI.isValid(); ++RAI) { 2317 LocIdx ClobberedLoc = MTracker->getRegMLoc(*RAI); 2318 TTracker->clobberMloc(ClobberedLoc, MI.getIterator(), false); 2319 } 2320 } 2321 2322 return true; 2323 } 2324 2325 /// Accumulate a mapping between each DILocalVariable fragment and other 2326 /// fragments of that DILocalVariable which overlap. This reduces work during 2327 /// the data-flow stage from "Find any overlapping fragments" to "Check if the 2328 /// known-to-overlap fragments are present". 2329 /// \param MI A previously unprocessed DEBUG_VALUE instruction to analyze for 2330 /// fragment usage. 2331 void InstrRefBasedLDV::accumulateFragmentMap(MachineInstr &MI) { 2332 DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(), 2333 MI.getDebugLoc()->getInlinedAt()); 2334 FragmentInfo ThisFragment = MIVar.getFragmentOrDefault(); 2335 2336 // If this is the first sighting of this variable, then we are guaranteed 2337 // there are currently no overlapping fragments either. Initialize the set 2338 // of seen fragments, record no overlaps for the current one, and return. 2339 auto SeenIt = SeenFragments.find(MIVar.getVariable()); 2340 if (SeenIt == SeenFragments.end()) { 2341 SmallSet<FragmentInfo, 4> OneFragment; 2342 OneFragment.insert(ThisFragment); 2343 SeenFragments.insert({MIVar.getVariable(), OneFragment}); 2344 2345 OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}}); 2346 return; 2347 } 2348 2349 // If this particular Variable/Fragment pair already exists in the overlap 2350 // map, it has already been accounted for. 2351 auto IsInOLapMap = 2352 OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}}); 2353 if (!IsInOLapMap.second) 2354 return; 2355 2356 auto &ThisFragmentsOverlaps = IsInOLapMap.first->second; 2357 auto &AllSeenFragments = SeenIt->second; 2358 2359 // Otherwise, examine all other seen fragments for this variable, with "this" 2360 // fragment being a previously unseen fragment. Record any pair of 2361 // overlapping fragments. 2362 for (auto &ASeenFragment : AllSeenFragments) { 2363 // Does this previously seen fragment overlap? 2364 if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) { 2365 // Yes: Mark the current fragment as being overlapped. 2366 ThisFragmentsOverlaps.push_back(ASeenFragment); 2367 // Mark the previously seen fragment as being overlapped by the current 2368 // one. 2369 auto ASeenFragmentsOverlaps = 2370 OverlapFragments.find({MIVar.getVariable(), ASeenFragment}); 2371 assert(ASeenFragmentsOverlaps != OverlapFragments.end() && 2372 "Previously seen var fragment has no vector of overlaps"); 2373 ASeenFragmentsOverlaps->second.push_back(ThisFragment); 2374 } 2375 } 2376 2377 AllSeenFragments.insert(ThisFragment); 2378 } 2379 2380 void InstrRefBasedLDV::process(MachineInstr &MI, ValueIDNum **MLiveOuts, 2381 ValueIDNum **MLiveIns) { 2382 // Try to interpret an MI as a debug or transfer instruction. Only if it's 2383 // none of these should we interpret it's register defs as new value 2384 // definitions. 2385 if (transferDebugValue(MI)) 2386 return; 2387 if (transferDebugInstrRef(MI, MLiveOuts, MLiveIns)) 2388 return; 2389 if (transferDebugPHI(MI)) 2390 return; 2391 if (transferRegisterCopy(MI)) 2392 return; 2393 if (transferSpillOrRestoreInst(MI)) 2394 return; 2395 transferRegisterDef(MI); 2396 } 2397 2398 void InstrRefBasedLDV::produceMLocTransferFunction( 2399 MachineFunction &MF, SmallVectorImpl<MLocTransferMap> &MLocTransfer, 2400 unsigned MaxNumBlocks) { 2401 // Because we try to optimize around register mask operands by ignoring regs 2402 // that aren't currently tracked, we set up something ugly for later: RegMask 2403 // operands that are seen earlier than the first use of a register, still need 2404 // to clobber that register in the transfer function. But this information 2405 // isn't actively recorded. Instead, we track each RegMask used in each block, 2406 // and accumulated the clobbered but untracked registers in each block into 2407 // the following bitvector. Later, if new values are tracked, we can add 2408 // appropriate clobbers. 2409 SmallVector<BitVector, 32> BlockMasks; 2410 BlockMasks.resize(MaxNumBlocks); 2411 2412 // Reserve one bit per register for the masks described above. 2413 unsigned BVWords = MachineOperand::getRegMaskSize(TRI->getNumRegs()); 2414 for (auto &BV : BlockMasks) 2415 BV.resize(TRI->getNumRegs(), true); 2416 2417 // Step through all instructions and inhale the transfer function. 2418 for (auto &MBB : MF) { 2419 // Object fields that are read by trackers to know where we are in the 2420 // function. 2421 CurBB = MBB.getNumber(); 2422 CurInst = 1; 2423 2424 // Set all machine locations to a PHI value. For transfer function 2425 // production only, this signifies the live-in value to the block. 2426 MTracker->reset(); 2427 MTracker->setMPhis(CurBB); 2428 2429 // Step through each instruction in this block. 2430 for (auto &MI : MBB) { 2431 process(MI); 2432 // Also accumulate fragment map. 2433 if (MI.isDebugValue()) 2434 accumulateFragmentMap(MI); 2435 2436 // Create a map from the instruction number (if present) to the 2437 // MachineInstr and its position. 2438 if (uint64_t InstrNo = MI.peekDebugInstrNum()) { 2439 auto InstrAndPos = std::make_pair(&MI, CurInst); 2440 auto InsertResult = 2441 DebugInstrNumToInstr.insert(std::make_pair(InstrNo, InstrAndPos)); 2442 2443 // There should never be duplicate instruction numbers. 2444 assert(InsertResult.second); 2445 (void)InsertResult; 2446 } 2447 2448 ++CurInst; 2449 } 2450 2451 // Produce the transfer function, a map of machine location to new value. If 2452 // any machine location has the live-in phi value from the start of the 2453 // block, it's live-through and doesn't need recording in the transfer 2454 // function. 2455 for (auto Location : MTracker->locations()) { 2456 LocIdx Idx = Location.Idx; 2457 ValueIDNum &P = Location.Value; 2458 if (P.isPHI() && P.getLoc() == Idx.asU64()) 2459 continue; 2460 2461 // Insert-or-update. 2462 auto &TransferMap = MLocTransfer[CurBB]; 2463 auto Result = TransferMap.insert(std::make_pair(Idx.asU64(), P)); 2464 if (!Result.second) 2465 Result.first->second = P; 2466 } 2467 2468 // Accumulate any bitmask operands into the clobberred reg mask for this 2469 // block. 2470 for (auto &P : MTracker->Masks) { 2471 BlockMasks[CurBB].clearBitsNotInMask(P.first->getRegMask(), BVWords); 2472 } 2473 } 2474 2475 // Compute a bitvector of all the registers that are tracked in this block. 2476 const TargetLowering *TLI = MF.getSubtarget().getTargetLowering(); 2477 Register SP = TLI->getStackPointerRegisterToSaveRestore(); 2478 BitVector UsedRegs(TRI->getNumRegs()); 2479 for (auto Location : MTracker->locations()) { 2480 unsigned ID = MTracker->LocIdxToLocID[Location.Idx]; 2481 if (ID >= TRI->getNumRegs() || ID == SP) 2482 continue; 2483 UsedRegs.set(ID); 2484 } 2485 2486 // Check that any regmask-clobber of a register that gets tracked, is not 2487 // live-through in the transfer function. It needs to be clobbered at the 2488 // very least. 2489 for (unsigned int I = 0; I < MaxNumBlocks; ++I) { 2490 BitVector &BV = BlockMasks[I]; 2491 BV.flip(); 2492 BV &= UsedRegs; 2493 // This produces all the bits that we clobber, but also use. Check that 2494 // they're all clobbered or at least set in the designated transfer 2495 // elem. 2496 for (unsigned Bit : BV.set_bits()) { 2497 unsigned ID = MTracker->getLocID(Bit, false); 2498 LocIdx Idx = MTracker->LocIDToLocIdx[ID]; 2499 auto &TransferMap = MLocTransfer[I]; 2500 2501 // Install a value representing the fact that this location is effectively 2502 // written to in this block. As there's no reserved value, instead use 2503 // a value number that is never generated. Pick the value number for the 2504 // first instruction in the block, def'ing this location, which we know 2505 // this block never used anyway. 2506 ValueIDNum NotGeneratedNum = ValueIDNum(I, 1, Idx); 2507 auto Result = 2508 TransferMap.insert(std::make_pair(Idx.asU64(), NotGeneratedNum)); 2509 if (!Result.second) { 2510 ValueIDNum &ValueID = Result.first->second; 2511 if (ValueID.getBlock() == I && ValueID.isPHI()) 2512 // It was left as live-through. Set it to clobbered. 2513 ValueID = NotGeneratedNum; 2514 } 2515 } 2516 } 2517 } 2518 2519 std::tuple<bool, bool> 2520 InstrRefBasedLDV::mlocJoin(MachineBasicBlock &MBB, 2521 SmallPtrSet<const MachineBasicBlock *, 16> &Visited, 2522 ValueIDNum **OutLocs, ValueIDNum *InLocs) { 2523 LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n"); 2524 bool Changed = false; 2525 bool DowngradeOccurred = false; 2526 2527 // Collect predecessors that have been visited. Anything that hasn't been 2528 // visited yet is a backedge on the first iteration, and the meet of it's 2529 // lattice value for all locations will be unaffected. 2530 SmallVector<const MachineBasicBlock *, 8> BlockOrders; 2531 for (auto Pred : MBB.predecessors()) { 2532 if (Visited.count(Pred)) { 2533 BlockOrders.push_back(Pred); 2534 } 2535 } 2536 2537 // Visit predecessors in RPOT order. 2538 auto Cmp = [&](const MachineBasicBlock *A, const MachineBasicBlock *B) { 2539 return BBToOrder.find(A)->second < BBToOrder.find(B)->second; 2540 }; 2541 llvm::sort(BlockOrders, Cmp); 2542 2543 // Skip entry block. 2544 if (BlockOrders.size() == 0) 2545 return std::tuple<bool, bool>(false, false); 2546 2547 // Step through all machine locations, then look at each predecessor and 2548 // detect disagreements. 2549 unsigned ThisBlockRPO = BBToOrder.find(&MBB)->second; 2550 for (auto Location : MTracker->locations()) { 2551 LocIdx Idx = Location.Idx; 2552 // Pick out the first predecessors live-out value for this location. It's 2553 // guaranteed to be not a backedge, as we order by RPO. 2554 ValueIDNum BaseVal = OutLocs[BlockOrders[0]->getNumber()][Idx.asU64()]; 2555 2556 // Some flags for whether there's a disagreement, and whether it's a 2557 // disagreement with a backedge or not. 2558 bool Disagree = false; 2559 bool NonBackEdgeDisagree = false; 2560 2561 // Loop around everything that wasn't 'base'. 2562 for (unsigned int I = 1; I < BlockOrders.size(); ++I) { 2563 auto *MBB = BlockOrders[I]; 2564 if (BaseVal != OutLocs[MBB->getNumber()][Idx.asU64()]) { 2565 // Live-out of a predecessor disagrees with the first predecessor. 2566 Disagree = true; 2567 2568 // Test whether it's a disagreemnt in the backedges or not. 2569 if (BBToOrder.find(MBB)->second < ThisBlockRPO) // might be self b/e 2570 NonBackEdgeDisagree = true; 2571 } 2572 } 2573 2574 bool OverRide = false; 2575 if (Disagree && !NonBackEdgeDisagree) { 2576 // Only the backedges disagree. Consider demoting the livein 2577 // lattice value, as per the file level comment. The value we consider 2578 // demoting to is the value that the non-backedge predecessors agree on. 2579 // The order of values is that non-PHIs are \top, a PHI at this block 2580 // \bot, and phis between the two are ordered by their RPO number. 2581 // If there's no agreement, or we've already demoted to this PHI value 2582 // before, replace with a PHI value at this block. 2583 2584 // Calculate order numbers: zero means normal def, nonzero means RPO 2585 // number. 2586 unsigned BaseBlockRPONum = BBNumToRPO[BaseVal.getBlock()] + 1; 2587 if (!BaseVal.isPHI()) 2588 BaseBlockRPONum = 0; 2589 2590 ValueIDNum &InLocID = InLocs[Idx.asU64()]; 2591 unsigned InLocRPONum = BBNumToRPO[InLocID.getBlock()] + 1; 2592 if (!InLocID.isPHI()) 2593 InLocRPONum = 0; 2594 2595 // Should we ignore the disagreeing backedges, and override with the 2596 // value the other predecessors agree on (in "base")? 2597 unsigned ThisBlockRPONum = BBNumToRPO[MBB.getNumber()] + 1; 2598 if (BaseBlockRPONum > InLocRPONum && BaseBlockRPONum < ThisBlockRPONum) { 2599 // Override. 2600 OverRide = true; 2601 DowngradeOccurred = true; 2602 } 2603 } 2604 // else: if we disagree in the non-backedges, then this is definitely 2605 // a control flow merge where different values merge. Make it a PHI. 2606 2607 // Generate a phi... 2608 ValueIDNum PHI = {(uint64_t)MBB.getNumber(), 0, Idx}; 2609 ValueIDNum NewVal = (Disagree && !OverRide) ? PHI : BaseVal; 2610 if (InLocs[Idx.asU64()] != NewVal) { 2611 Changed |= true; 2612 InLocs[Idx.asU64()] = NewVal; 2613 } 2614 } 2615 2616 // TODO: Reimplement NumInserted and NumRemoved. 2617 return std::tuple<bool, bool>(Changed, DowngradeOccurred); 2618 } 2619 2620 void InstrRefBasedLDV::mlocDataflow( 2621 ValueIDNum **MInLocs, ValueIDNum **MOutLocs, 2622 SmallVectorImpl<MLocTransferMap> &MLocTransfer) { 2623 std::priority_queue<unsigned int, std::vector<unsigned int>, 2624 std::greater<unsigned int>> 2625 Worklist, Pending; 2626 2627 // We track what is on the current and pending worklist to avoid inserting 2628 // the same thing twice. We could avoid this with a custom priority queue, 2629 // but this is probably not worth it. 2630 SmallPtrSet<MachineBasicBlock *, 16> OnPending, OnWorklist; 2631 2632 // Initialize worklist with every block to be visited. 2633 for (unsigned int I = 0; I < BBToOrder.size(); ++I) { 2634 Worklist.push(I); 2635 OnWorklist.insert(OrderToBB[I]); 2636 } 2637 2638 MTracker->reset(); 2639 2640 // Set inlocs for entry block -- each as a PHI at the entry block. Represents 2641 // the incoming value to the function. 2642 MTracker->setMPhis(0); 2643 for (auto Location : MTracker->locations()) 2644 MInLocs[0][Location.Idx.asU64()] = Location.Value; 2645 2646 SmallPtrSet<const MachineBasicBlock *, 16> Visited; 2647 while (!Worklist.empty() || !Pending.empty()) { 2648 // Vector for storing the evaluated block transfer function. 2649 SmallVector<std::pair<LocIdx, ValueIDNum>, 32> ToRemap; 2650 2651 while (!Worklist.empty()) { 2652 MachineBasicBlock *MBB = OrderToBB[Worklist.top()]; 2653 CurBB = MBB->getNumber(); 2654 Worklist.pop(); 2655 2656 // Join the values in all predecessor blocks. 2657 bool InLocsChanged, DowngradeOccurred; 2658 std::tie(InLocsChanged, DowngradeOccurred) = 2659 mlocJoin(*MBB, Visited, MOutLocs, MInLocs[CurBB]); 2660 InLocsChanged |= Visited.insert(MBB).second; 2661 2662 // If a downgrade occurred, book us in for re-examination on the next 2663 // iteration. 2664 if (DowngradeOccurred && OnPending.insert(MBB).second) 2665 Pending.push(BBToOrder[MBB]); 2666 2667 // Don't examine transfer function if we've visited this loc at least 2668 // once, and inlocs haven't changed. 2669 if (!InLocsChanged) 2670 continue; 2671 2672 // Load the current set of live-ins into MLocTracker. 2673 MTracker->loadFromArray(MInLocs[CurBB], CurBB); 2674 2675 // Each element of the transfer function can be a new def, or a read of 2676 // a live-in value. Evaluate each element, and store to "ToRemap". 2677 ToRemap.clear(); 2678 for (auto &P : MLocTransfer[CurBB]) { 2679 if (P.second.getBlock() == CurBB && P.second.isPHI()) { 2680 // This is a movement of whatever was live in. Read it. 2681 ValueIDNum NewID = MTracker->getNumAtPos(P.second.getLoc()); 2682 ToRemap.push_back(std::make_pair(P.first, NewID)); 2683 } else { 2684 // It's a def. Just set it. 2685 assert(P.second.getBlock() == CurBB); 2686 ToRemap.push_back(std::make_pair(P.first, P.second)); 2687 } 2688 } 2689 2690 // Commit the transfer function changes into mloc tracker, which 2691 // transforms the contents of the MLocTracker into the live-outs. 2692 for (auto &P : ToRemap) 2693 MTracker->setMLoc(P.first, P.second); 2694 2695 // Now copy out-locs from mloc tracker into out-loc vector, checking 2696 // whether changes have occurred. These changes can have come from both 2697 // the transfer function, and mlocJoin. 2698 bool OLChanged = false; 2699 for (auto Location : MTracker->locations()) { 2700 OLChanged |= MOutLocs[CurBB][Location.Idx.asU64()] != Location.Value; 2701 MOutLocs[CurBB][Location.Idx.asU64()] = Location.Value; 2702 } 2703 2704 MTracker->reset(); 2705 2706 // No need to examine successors again if out-locs didn't change. 2707 if (!OLChanged) 2708 continue; 2709 2710 // All successors should be visited: put any back-edges on the pending 2711 // list for the next dataflow iteration, and any other successors to be 2712 // visited this iteration, if they're not going to be already. 2713 for (auto s : MBB->successors()) { 2714 // Does branching to this successor represent a back-edge? 2715 if (BBToOrder[s] > BBToOrder[MBB]) { 2716 // No: visit it during this dataflow iteration. 2717 if (OnWorklist.insert(s).second) 2718 Worklist.push(BBToOrder[s]); 2719 } else { 2720 // Yes: visit it on the next iteration. 2721 if (OnPending.insert(s).second) 2722 Pending.push(BBToOrder[s]); 2723 } 2724 } 2725 } 2726 2727 Worklist.swap(Pending); 2728 std::swap(OnPending, OnWorklist); 2729 OnPending.clear(); 2730 // At this point, pending must be empty, since it was just the empty 2731 // worklist 2732 assert(Pending.empty() && "Pending should be empty"); 2733 } 2734 2735 // Once all the live-ins don't change on mlocJoin(), we've reached a 2736 // fixedpoint. 2737 } 2738 2739 bool InstrRefBasedLDV::vlocDowngradeLattice( 2740 const MachineBasicBlock &MBB, const DbgValue &OldLiveInLocation, 2741 const SmallVectorImpl<InValueT> &Values, unsigned CurBlockRPONum) { 2742 // Ranking value preference: see file level comment, the highest rank is 2743 // a plain def, followed by PHI values in reverse post-order. Numerically, 2744 // we assign all defs the rank '0', all PHIs their blocks RPO number plus 2745 // one, and consider the lowest value the highest ranked. 2746 int OldLiveInRank = BBNumToRPO[OldLiveInLocation.ID.getBlock()] + 1; 2747 if (!OldLiveInLocation.ID.isPHI()) 2748 OldLiveInRank = 0; 2749 2750 // Allow any unresolvable conflict to be over-ridden. 2751 if (OldLiveInLocation.Kind == DbgValue::NoVal) { 2752 // Although if it was an unresolvable conflict from _this_ block, then 2753 // all other seeking of downgrades and PHIs must have failed before hand. 2754 if (OldLiveInLocation.BlockNo == (unsigned)MBB.getNumber()) 2755 return false; 2756 OldLiveInRank = INT_MIN; 2757 } 2758 2759 auto &InValue = *Values[0].second; 2760 2761 if (InValue.Kind == DbgValue::Const || InValue.Kind == DbgValue::NoVal) 2762 return false; 2763 2764 unsigned ThisRPO = BBNumToRPO[InValue.ID.getBlock()]; 2765 int ThisRank = ThisRPO + 1; 2766 if (!InValue.ID.isPHI()) 2767 ThisRank = 0; 2768 2769 // Too far down the lattice? 2770 if (ThisRPO >= CurBlockRPONum) 2771 return false; 2772 2773 // Higher in the lattice than what we've already explored? 2774 if (ThisRank <= OldLiveInRank) 2775 return false; 2776 2777 return true; 2778 } 2779 2780 std::tuple<Optional<ValueIDNum>, bool> InstrRefBasedLDV::pickVPHILoc( 2781 MachineBasicBlock &MBB, const DebugVariable &Var, const LiveIdxT &LiveOuts, 2782 ValueIDNum **MOutLocs, ValueIDNum **MInLocs, 2783 const SmallVectorImpl<MachineBasicBlock *> &BlockOrders) { 2784 // Collect a set of locations from predecessor where its live-out value can 2785 // be found. 2786 SmallVector<SmallVector<LocIdx, 4>, 8> Locs; 2787 unsigned NumLocs = MTracker->getNumLocs(); 2788 unsigned BackEdgesStart = 0; 2789 2790 for (auto p : BlockOrders) { 2791 // Pick out where backedges start in the list of predecessors. Relies on 2792 // BlockOrders being sorted by RPO. 2793 if (BBToOrder[p] < BBToOrder[&MBB]) 2794 ++BackEdgesStart; 2795 2796 // For each predecessor, create a new set of locations. 2797 Locs.resize(Locs.size() + 1); 2798 unsigned ThisBBNum = p->getNumber(); 2799 auto LiveOutMap = LiveOuts.find(p); 2800 if (LiveOutMap == LiveOuts.end()) 2801 // This predecessor isn't in scope, it must have no live-in/live-out 2802 // locations. 2803 continue; 2804 2805 auto It = LiveOutMap->second->find(Var); 2806 if (It == LiveOutMap->second->end()) 2807 // There's no value recorded for this variable in this predecessor, 2808 // leave an empty set of locations. 2809 continue; 2810 2811 const DbgValue &OutVal = It->second; 2812 2813 if (OutVal.Kind == DbgValue::Const || OutVal.Kind == DbgValue::NoVal) 2814 // Consts and no-values cannot have locations we can join on. 2815 continue; 2816 2817 assert(OutVal.Kind == DbgValue::Proposed || OutVal.Kind == DbgValue::Def); 2818 ValueIDNum ValToLookFor = OutVal.ID; 2819 2820 // Search the live-outs of the predecessor for the specified value. 2821 for (unsigned int I = 0; I < NumLocs; ++I) { 2822 if (MOutLocs[ThisBBNum][I] == ValToLookFor) 2823 Locs.back().push_back(LocIdx(I)); 2824 } 2825 } 2826 2827 // If there were no locations at all, return an empty result. 2828 if (Locs.empty()) 2829 return std::tuple<Optional<ValueIDNum>, bool>(None, false); 2830 2831 // Lambda for seeking a common location within a range of location-sets. 2832 using LocsIt = SmallVector<SmallVector<LocIdx, 4>, 8>::iterator; 2833 auto SeekLocation = 2834 [&Locs](llvm::iterator_range<LocsIt> SearchRange) -> Optional<LocIdx> { 2835 // Starting with the first set of locations, take the intersection with 2836 // subsequent sets. 2837 SmallVector<LocIdx, 4> base = Locs[0]; 2838 for (auto &S : SearchRange) { 2839 SmallVector<LocIdx, 4> new_base; 2840 std::set_intersection(base.begin(), base.end(), S.begin(), S.end(), 2841 std::inserter(new_base, new_base.begin())); 2842 base = new_base; 2843 } 2844 if (base.empty()) 2845 return None; 2846 2847 // We now have a set of LocIdxes that contain the right output value in 2848 // each of the predecessors. Pick the lowest; if there's a register loc, 2849 // that'll be it. 2850 return *base.begin(); 2851 }; 2852 2853 // Search for a common location for all predecessors. If we can't, then fall 2854 // back to only finding a common location between non-backedge predecessors. 2855 bool ValidForAllLocs = true; 2856 auto TheLoc = SeekLocation(Locs); 2857 if (!TheLoc) { 2858 ValidForAllLocs = false; 2859 TheLoc = 2860 SeekLocation(make_range(Locs.begin(), Locs.begin() + BackEdgesStart)); 2861 } 2862 2863 if (!TheLoc) 2864 return std::tuple<Optional<ValueIDNum>, bool>(None, false); 2865 2866 // Return a PHI-value-number for the found location. 2867 LocIdx L = *TheLoc; 2868 ValueIDNum PHIVal = {(unsigned)MBB.getNumber(), 0, L}; 2869 return std::tuple<Optional<ValueIDNum>, bool>(PHIVal, ValidForAllLocs); 2870 } 2871 2872 std::tuple<bool, bool> InstrRefBasedLDV::vlocJoin( 2873 MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs, LiveIdxT &VLOCInLocs, 2874 SmallPtrSet<const MachineBasicBlock *, 16> *VLOCVisited, unsigned BBNum, 2875 const SmallSet<DebugVariable, 4> &AllVars, ValueIDNum **MOutLocs, 2876 ValueIDNum **MInLocs, 2877 SmallPtrSet<const MachineBasicBlock *, 8> &InScopeBlocks, 2878 SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore, 2879 DenseMap<DebugVariable, DbgValue> &InLocsT) { 2880 bool DowngradeOccurred = false; 2881 2882 // To emulate VarLocBasedImpl, process this block if it's not in scope but 2883 // _does_ assign a variable value. No live-ins for this scope are transferred 2884 // in though, so we can return immediately. 2885 if (InScopeBlocks.count(&MBB) == 0 && !ArtificialBlocks.count(&MBB)) { 2886 if (VLOCVisited) 2887 return std::tuple<bool, bool>(true, false); 2888 return std::tuple<bool, bool>(false, false); 2889 } 2890 2891 LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n"); 2892 bool Changed = false; 2893 2894 // Find any live-ins computed in a prior iteration. 2895 auto ILSIt = VLOCInLocs.find(&MBB); 2896 assert(ILSIt != VLOCInLocs.end()); 2897 auto &ILS = *ILSIt->second; 2898 2899 // Order predecessors by RPOT order, for exploring them in that order. 2900 SmallVector<MachineBasicBlock *, 8> BlockOrders(MBB.predecessors()); 2901 2902 auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 2903 return BBToOrder[A] < BBToOrder[B]; 2904 }; 2905 2906 llvm::sort(BlockOrders, Cmp); 2907 2908 unsigned CurBlockRPONum = BBToOrder[&MBB]; 2909 2910 // Force a re-visit to loop heads in the first dataflow iteration. 2911 // FIXME: if we could "propose" Const values this wouldn't be needed, 2912 // because they'd need to be confirmed before being emitted. 2913 if (!BlockOrders.empty() && 2914 BBToOrder[BlockOrders[BlockOrders.size() - 1]] >= CurBlockRPONum && 2915 VLOCVisited) 2916 DowngradeOccurred = true; 2917 2918 auto ConfirmValue = [&InLocsT](const DebugVariable &DV, DbgValue VR) { 2919 auto Result = InLocsT.insert(std::make_pair(DV, VR)); 2920 (void)Result; 2921 assert(Result.second); 2922 }; 2923 2924 auto ConfirmNoVal = [&ConfirmValue, &MBB](const DebugVariable &Var, const DbgValueProperties &Properties) { 2925 DbgValue NoLocPHIVal(MBB.getNumber(), Properties, DbgValue::NoVal); 2926 2927 ConfirmValue(Var, NoLocPHIVal); 2928 }; 2929 2930 // Attempt to join the values for each variable. 2931 for (auto &Var : AllVars) { 2932 // Collect all the DbgValues for this variable. 2933 SmallVector<InValueT, 8> Values; 2934 bool Bail = false; 2935 unsigned BackEdgesStart = 0; 2936 for (auto p : BlockOrders) { 2937 // If the predecessor isn't in scope / to be explored, we'll never be 2938 // able to join any locations. 2939 if (!BlocksToExplore.contains(p)) { 2940 Bail = true; 2941 break; 2942 } 2943 2944 // Don't attempt to handle unvisited predecessors: they're implicitly 2945 // "unknown"s in the lattice. 2946 if (VLOCVisited && !VLOCVisited->count(p)) 2947 continue; 2948 2949 // If the predecessors OutLocs is absent, there's not much we can do. 2950 auto OL = VLOCOutLocs.find(p); 2951 if (OL == VLOCOutLocs.end()) { 2952 Bail = true; 2953 break; 2954 } 2955 2956 // No live-out value for this predecessor also means we can't produce 2957 // a joined value. 2958 auto VIt = OL->second->find(Var); 2959 if (VIt == OL->second->end()) { 2960 Bail = true; 2961 break; 2962 } 2963 2964 // Keep track of where back-edges begin in the Values vector. Relies on 2965 // BlockOrders being sorted by RPO. 2966 unsigned ThisBBRPONum = BBToOrder[p]; 2967 if (ThisBBRPONum < CurBlockRPONum) 2968 ++BackEdgesStart; 2969 2970 Values.push_back(std::make_pair(p, &VIt->second)); 2971 } 2972 2973 // If there were no values, or one of the predecessors couldn't have a 2974 // value, then give up immediately. It's not safe to produce a live-in 2975 // value. 2976 if (Bail || Values.size() == 0) 2977 continue; 2978 2979 // Enumeration identifying the current state of the predecessors values. 2980 enum { 2981 Unset = 0, 2982 Agreed, // All preds agree on the variable value. 2983 PropDisagree, // All preds agree, but the value kind is Proposed in some. 2984 BEDisagree, // Only back-edges disagree on variable value. 2985 PHINeeded, // Non-back-edge predecessors have conflicing values. 2986 NoSolution // Conflicting Value metadata makes solution impossible. 2987 } OurState = Unset; 2988 2989 // All (non-entry) blocks have at least one non-backedge predecessor. 2990 // Pick the variable value from the first of these, to compare against 2991 // all others. 2992 const DbgValue &FirstVal = *Values[0].second; 2993 const ValueIDNum &FirstID = FirstVal.ID; 2994 2995 // Scan for variable values that can't be resolved: if they have different 2996 // DIExpressions, different indirectness, or are mixed constants / 2997 // non-constants. 2998 for (auto &V : Values) { 2999 if (V.second->Properties != FirstVal.Properties) 3000 OurState = NoSolution; 3001 if (V.second->Kind == DbgValue::Const && FirstVal.Kind != DbgValue::Const) 3002 OurState = NoSolution; 3003 } 3004 3005 // Flags diagnosing _how_ the values disagree. 3006 bool NonBackEdgeDisagree = false; 3007 bool DisagreeOnPHINess = false; 3008 bool IDDisagree = false; 3009 bool Disagree = false; 3010 if (OurState == Unset) { 3011 for (auto &V : Values) { 3012 if (*V.second == FirstVal) 3013 continue; // No disagreement. 3014 3015 Disagree = true; 3016 3017 // Flag whether the value number actually diagrees. 3018 if (V.second->ID != FirstID) 3019 IDDisagree = true; 3020 3021 // Distinguish whether disagreement happens in backedges or not. 3022 // Relies on Values (and BlockOrders) being sorted by RPO. 3023 unsigned ThisBBRPONum = BBToOrder[V.first]; 3024 if (ThisBBRPONum < CurBlockRPONum) 3025 NonBackEdgeDisagree = true; 3026 3027 // Is there a difference in whether the value is definite or only 3028 // proposed? 3029 if (V.second->Kind != FirstVal.Kind && 3030 (V.second->Kind == DbgValue::Proposed || 3031 V.second->Kind == DbgValue::Def) && 3032 (FirstVal.Kind == DbgValue::Proposed || 3033 FirstVal.Kind == DbgValue::Def)) 3034 DisagreeOnPHINess = true; 3035 } 3036 3037 // Collect those flags together and determine an overall state for 3038 // what extend the predecessors agree on a live-in value. 3039 if (!Disagree) 3040 OurState = Agreed; 3041 else if (!IDDisagree && DisagreeOnPHINess) 3042 OurState = PropDisagree; 3043 else if (!NonBackEdgeDisagree) 3044 OurState = BEDisagree; 3045 else 3046 OurState = PHINeeded; 3047 } 3048 3049 // An extra indicator: if we only disagree on whether the value is a 3050 // Def, or proposed, then also flag whether that disagreement happens 3051 // in backedges only. 3052 bool PropOnlyInBEs = Disagree && !IDDisagree && DisagreeOnPHINess && 3053 !NonBackEdgeDisagree && FirstVal.Kind == DbgValue::Def; 3054 3055 const auto &Properties = FirstVal.Properties; 3056 3057 auto OldLiveInIt = ILS.find(Var); 3058 const DbgValue *OldLiveInLocation = 3059 (OldLiveInIt != ILS.end()) ? &OldLiveInIt->second : nullptr; 3060 3061 bool OverRide = false; 3062 if (OurState == BEDisagree && OldLiveInLocation) { 3063 // Only backedges disagree: we can consider downgrading. If there was a 3064 // previous live-in value, use it to work out whether the current 3065 // incoming value represents a lattice downgrade or not. 3066 OverRide = 3067 vlocDowngradeLattice(MBB, *OldLiveInLocation, Values, CurBlockRPONum); 3068 } 3069 3070 // Use the current state of predecessor agreement and other flags to work 3071 // out what to do next. Possibilities include: 3072 // * Accept a value all predecessors agree on, or accept one that 3073 // represents a step down the exploration lattice, 3074 // * Use a PHI value number, if one can be found, 3075 // * Propose a PHI value number, and see if it gets confirmed later, 3076 // * Emit a 'NoVal' value, indicating we couldn't resolve anything. 3077 if (OurState == Agreed) { 3078 // Easiest solution: all predecessors agree on the variable value. 3079 ConfirmValue(Var, FirstVal); 3080 } else if (OurState == BEDisagree && OverRide) { 3081 // Only backedges disagree, and the other predecessors have produced 3082 // a new live-in value further down the exploration lattice. 3083 DowngradeOccurred = true; 3084 ConfirmValue(Var, FirstVal); 3085 } else if (OurState == PropDisagree) { 3086 // Predecessors agree on value, but some say it's only a proposed value. 3087 // Propagate it as proposed: unless it was proposed in this block, in 3088 // which case we're able to confirm the value. 3089 if (FirstID.getBlock() == (uint64_t)MBB.getNumber() && FirstID.isPHI()) { 3090 ConfirmValue(Var, DbgValue(FirstID, Properties, DbgValue::Def)); 3091 } else if (PropOnlyInBEs) { 3092 // If only backedges disagree, a higher (in RPO) block confirmed this 3093 // location, and we need to propagate it into this loop. 3094 ConfirmValue(Var, DbgValue(FirstID, Properties, DbgValue::Def)); 3095 } else { 3096 // Otherwise; a Def meeting a Proposed is still a Proposed. 3097 ConfirmValue(Var, DbgValue(FirstID, Properties, DbgValue::Proposed)); 3098 } 3099 } else if ((OurState == PHINeeded || OurState == BEDisagree)) { 3100 // Predecessors disagree and can't be downgraded: this can only be 3101 // solved with a PHI. Use pickVPHILoc to go look for one. 3102 Optional<ValueIDNum> VPHI; 3103 bool AllEdgesVPHI = false; 3104 std::tie(VPHI, AllEdgesVPHI) = 3105 pickVPHILoc(MBB, Var, VLOCOutLocs, MOutLocs, MInLocs, BlockOrders); 3106 3107 if (VPHI && AllEdgesVPHI) { 3108 // There's a PHI value that's valid for all predecessors -- we can use 3109 // it. If any of the non-backedge predecessors have proposed values 3110 // though, this PHI is also only proposed, until the predecessors are 3111 // confirmed. 3112 DbgValue::KindT K = DbgValue::Def; 3113 for (unsigned int I = 0; I < BackEdgesStart; ++I) 3114 if (Values[I].second->Kind == DbgValue::Proposed) 3115 K = DbgValue::Proposed; 3116 3117 ConfirmValue(Var, DbgValue(*VPHI, Properties, K)); 3118 } else if (VPHI) { 3119 // There's a PHI value, but it's only legal for backedges. Leave this 3120 // as a proposed PHI value: it might come back on the backedges, 3121 // and allow us to confirm it in the future. 3122 DbgValue NoBEValue = DbgValue(*VPHI, Properties, DbgValue::Proposed); 3123 ConfirmValue(Var, NoBEValue); 3124 } else { 3125 ConfirmNoVal(Var, Properties); 3126 } 3127 } else { 3128 // Otherwise: we don't know. Emit a "phi but no real loc" phi. 3129 ConfirmNoVal(Var, Properties); 3130 } 3131 } 3132 3133 // Store newly calculated in-locs into VLOCInLocs, if they've changed. 3134 Changed = ILS != InLocsT; 3135 if (Changed) 3136 ILS = InLocsT; 3137 3138 return std::tuple<bool, bool>(Changed, DowngradeOccurred); 3139 } 3140 3141 void InstrRefBasedLDV::vlocDataflow( 3142 const LexicalScope *Scope, const DILocation *DILoc, 3143 const SmallSet<DebugVariable, 4> &VarsWeCareAbout, 3144 SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, LiveInsT &Output, 3145 ValueIDNum **MOutLocs, ValueIDNum **MInLocs, 3146 SmallVectorImpl<VLocTracker> &AllTheVLocs) { 3147 // This method is much like mlocDataflow: but focuses on a single 3148 // LexicalScope at a time. Pick out a set of blocks and variables that are 3149 // to have their value assignments solved, then run our dataflow algorithm 3150 // until a fixedpoint is reached. 3151 std::priority_queue<unsigned int, std::vector<unsigned int>, 3152 std::greater<unsigned int>> 3153 Worklist, Pending; 3154 SmallPtrSet<MachineBasicBlock *, 16> OnWorklist, OnPending; 3155 3156 // The set of blocks we'll be examining. 3157 SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore; 3158 3159 // The order in which to examine them (RPO). 3160 SmallVector<MachineBasicBlock *, 8> BlockOrders; 3161 3162 // RPO ordering function. 3163 auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 3164 return BBToOrder[A] < BBToOrder[B]; 3165 }; 3166 3167 LS.getMachineBasicBlocks(DILoc, BlocksToExplore); 3168 3169 // A separate container to distinguish "blocks we're exploring" versus 3170 // "blocks that are potentially in scope. See comment at start of vlocJoin. 3171 SmallPtrSet<const MachineBasicBlock *, 8> InScopeBlocks = BlocksToExplore; 3172 3173 // Old LiveDebugValues tracks variable locations that come out of blocks 3174 // not in scope, where DBG_VALUEs occur. This is something we could 3175 // legitimately ignore, but lets allow it for now. 3176 if (EmulateOldLDV) 3177 BlocksToExplore.insert(AssignBlocks.begin(), AssignBlocks.end()); 3178 3179 // We also need to propagate variable values through any artificial blocks 3180 // that immediately follow blocks in scope. 3181 DenseSet<const MachineBasicBlock *> ToAdd; 3182 3183 // Helper lambda: For a given block in scope, perform a depth first search 3184 // of all the artificial successors, adding them to the ToAdd collection. 3185 auto AccumulateArtificialBlocks = 3186 [this, &ToAdd, &BlocksToExplore, 3187 &InScopeBlocks](const MachineBasicBlock *MBB) { 3188 // Depth-first-search state: each node is a block and which successor 3189 // we're currently exploring. 3190 SmallVector<std::pair<const MachineBasicBlock *, 3191 MachineBasicBlock::const_succ_iterator>, 3192 8> 3193 DFS; 3194 3195 // Find any artificial successors not already tracked. 3196 for (auto *succ : MBB->successors()) { 3197 if (BlocksToExplore.count(succ) || InScopeBlocks.count(succ)) 3198 continue; 3199 if (!ArtificialBlocks.count(succ)) 3200 continue; 3201 DFS.push_back(std::make_pair(succ, succ->succ_begin())); 3202 ToAdd.insert(succ); 3203 } 3204 3205 // Search all those blocks, depth first. 3206 while (!DFS.empty()) { 3207 const MachineBasicBlock *CurBB = DFS.back().first; 3208 MachineBasicBlock::const_succ_iterator &CurSucc = DFS.back().second; 3209 // Walk back if we've explored this blocks successors to the end. 3210 if (CurSucc == CurBB->succ_end()) { 3211 DFS.pop_back(); 3212 continue; 3213 } 3214 3215 // If the current successor is artificial and unexplored, descend into 3216 // it. 3217 if (!ToAdd.count(*CurSucc) && ArtificialBlocks.count(*CurSucc)) { 3218 DFS.push_back(std::make_pair(*CurSucc, (*CurSucc)->succ_begin())); 3219 ToAdd.insert(*CurSucc); 3220 continue; 3221 } 3222 3223 ++CurSucc; 3224 } 3225 }; 3226 3227 // Search in-scope blocks and those containing a DBG_VALUE from this scope 3228 // for artificial successors. 3229 for (auto *MBB : BlocksToExplore) 3230 AccumulateArtificialBlocks(MBB); 3231 for (auto *MBB : InScopeBlocks) 3232 AccumulateArtificialBlocks(MBB); 3233 3234 BlocksToExplore.insert(ToAdd.begin(), ToAdd.end()); 3235 InScopeBlocks.insert(ToAdd.begin(), ToAdd.end()); 3236 3237 // Single block scope: not interesting! No propagation at all. Note that 3238 // this could probably go above ArtificialBlocks without damage, but 3239 // that then produces output differences from original-live-debug-values, 3240 // which propagates from a single block into many artificial ones. 3241 if (BlocksToExplore.size() == 1) 3242 return; 3243 3244 // Picks out relevants blocks RPO order and sort them. 3245 for (auto *MBB : BlocksToExplore) 3246 BlockOrders.push_back(const_cast<MachineBasicBlock *>(MBB)); 3247 3248 llvm::sort(BlockOrders, Cmp); 3249 unsigned NumBlocks = BlockOrders.size(); 3250 3251 // Allocate some vectors for storing the live ins and live outs. Large. 3252 SmallVector<DenseMap<DebugVariable, DbgValue>, 32> LiveIns, LiveOuts; 3253 LiveIns.resize(NumBlocks); 3254 LiveOuts.resize(NumBlocks); 3255 3256 // Produce by-MBB indexes of live-in/live-outs, to ease lookup within 3257 // vlocJoin. 3258 LiveIdxT LiveOutIdx, LiveInIdx; 3259 LiveOutIdx.reserve(NumBlocks); 3260 LiveInIdx.reserve(NumBlocks); 3261 for (unsigned I = 0; I < NumBlocks; ++I) { 3262 LiveOutIdx[BlockOrders[I]] = &LiveOuts[I]; 3263 LiveInIdx[BlockOrders[I]] = &LiveIns[I]; 3264 } 3265 3266 for (auto *MBB : BlockOrders) { 3267 Worklist.push(BBToOrder[MBB]); 3268 OnWorklist.insert(MBB); 3269 } 3270 3271 // Iterate over all the blocks we selected, propagating variable values. 3272 bool FirstTrip = true; 3273 SmallPtrSet<const MachineBasicBlock *, 16> VLOCVisited; 3274 while (!Worklist.empty() || !Pending.empty()) { 3275 while (!Worklist.empty()) { 3276 auto *MBB = OrderToBB[Worklist.top()]; 3277 CurBB = MBB->getNumber(); 3278 Worklist.pop(); 3279 3280 DenseMap<DebugVariable, DbgValue> JoinedInLocs; 3281 3282 // Join values from predecessors. Updates LiveInIdx, and writes output 3283 // into JoinedInLocs. 3284 bool InLocsChanged, DowngradeOccurred; 3285 std::tie(InLocsChanged, DowngradeOccurred) = vlocJoin( 3286 *MBB, LiveOutIdx, LiveInIdx, (FirstTrip) ? &VLOCVisited : nullptr, 3287 CurBB, VarsWeCareAbout, MOutLocs, MInLocs, InScopeBlocks, 3288 BlocksToExplore, JoinedInLocs); 3289 3290 bool FirstVisit = VLOCVisited.insert(MBB).second; 3291 3292 // Always explore transfer function if inlocs changed, or if we've not 3293 // visited this block before. 3294 InLocsChanged |= FirstVisit; 3295 3296 // If a downgrade occurred, book us in for re-examination on the next 3297 // iteration. 3298 if (DowngradeOccurred && OnPending.insert(MBB).second) 3299 Pending.push(BBToOrder[MBB]); 3300 3301 if (!InLocsChanged) 3302 continue; 3303 3304 // Do transfer function. 3305 auto &VTracker = AllTheVLocs[MBB->getNumber()]; 3306 for (auto &Transfer : VTracker.Vars) { 3307 // Is this var we're mangling in this scope? 3308 if (VarsWeCareAbout.count(Transfer.first)) { 3309 // Erase on empty transfer (DBG_VALUE $noreg). 3310 if (Transfer.second.Kind == DbgValue::Undef) { 3311 JoinedInLocs.erase(Transfer.first); 3312 } else { 3313 // Insert new variable value; or overwrite. 3314 auto NewValuePair = std::make_pair(Transfer.first, Transfer.second); 3315 auto Result = JoinedInLocs.insert(NewValuePair); 3316 if (!Result.second) 3317 Result.first->second = Transfer.second; 3318 } 3319 } 3320 } 3321 3322 // Did the live-out locations change? 3323 bool OLChanged = JoinedInLocs != *LiveOutIdx[MBB]; 3324 3325 // If they haven't changed, there's no need to explore further. 3326 if (!OLChanged) 3327 continue; 3328 3329 // Commit to the live-out record. 3330 *LiveOutIdx[MBB] = JoinedInLocs; 3331 3332 // We should visit all successors. Ensure we'll visit any non-backedge 3333 // successors during this dataflow iteration; book backedge successors 3334 // to be visited next time around. 3335 for (auto s : MBB->successors()) { 3336 // Ignore out of scope / not-to-be-explored successors. 3337 if (LiveInIdx.find(s) == LiveInIdx.end()) 3338 continue; 3339 3340 if (BBToOrder[s] > BBToOrder[MBB]) { 3341 if (OnWorklist.insert(s).second) 3342 Worklist.push(BBToOrder[s]); 3343 } else if (OnPending.insert(s).second && (FirstTrip || OLChanged)) { 3344 Pending.push(BBToOrder[s]); 3345 } 3346 } 3347 } 3348 Worklist.swap(Pending); 3349 std::swap(OnWorklist, OnPending); 3350 OnPending.clear(); 3351 assert(Pending.empty()); 3352 FirstTrip = false; 3353 } 3354 3355 // Dataflow done. Now what? Save live-ins. Ignore any that are still marked 3356 // as being variable-PHIs, because those did not have their machine-PHI 3357 // value confirmed. Such variable values are places that could have been 3358 // PHIs, but are not. 3359 for (auto *MBB : BlockOrders) { 3360 auto &VarMap = *LiveInIdx[MBB]; 3361 for (auto &P : VarMap) { 3362 if (P.second.Kind == DbgValue::Proposed || 3363 P.second.Kind == DbgValue::NoVal) 3364 continue; 3365 Output[MBB->getNumber()].push_back(P); 3366 } 3367 } 3368 3369 BlockOrders.clear(); 3370 BlocksToExplore.clear(); 3371 } 3372 3373 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 3374 void InstrRefBasedLDV::dump_mloc_transfer( 3375 const MLocTransferMap &mloc_transfer) const { 3376 for (auto &P : mloc_transfer) { 3377 std::string foo = MTracker->LocIdxToName(P.first); 3378 std::string bar = MTracker->IDAsString(P.second); 3379 dbgs() << "Loc " << foo << " --> " << bar << "\n"; 3380 } 3381 } 3382 #endif 3383 3384 void InstrRefBasedLDV::emitLocations( 3385 MachineFunction &MF, LiveInsT SavedLiveIns, ValueIDNum **MOutLocs, 3386 ValueIDNum **MInLocs, DenseMap<DebugVariable, unsigned> &AllVarsNumbering, 3387 const TargetPassConfig &TPC) { 3388 TTracker = new TransferTracker(TII, MTracker, MF, *TRI, CalleeSavedRegs, TPC); 3389 unsigned NumLocs = MTracker->getNumLocs(); 3390 3391 // For each block, load in the machine value locations and variable value 3392 // live-ins, then step through each instruction in the block. New DBG_VALUEs 3393 // to be inserted will be created along the way. 3394 for (MachineBasicBlock &MBB : MF) { 3395 unsigned bbnum = MBB.getNumber(); 3396 MTracker->reset(); 3397 MTracker->loadFromArray(MInLocs[bbnum], bbnum); 3398 TTracker->loadInlocs(MBB, MInLocs[bbnum], SavedLiveIns[MBB.getNumber()], 3399 NumLocs); 3400 3401 CurBB = bbnum; 3402 CurInst = 1; 3403 for (auto &MI : MBB) { 3404 process(MI, MOutLocs, MInLocs); 3405 TTracker->checkInstForNewValues(CurInst, MI.getIterator()); 3406 ++CurInst; 3407 } 3408 } 3409 3410 // We have to insert DBG_VALUEs in a consistent order, otherwise they appeaer 3411 // in DWARF in different orders. Use the order that they appear when walking 3412 // through each block / each instruction, stored in AllVarsNumbering. 3413 auto OrderDbgValues = [&](const MachineInstr *A, 3414 const MachineInstr *B) -> bool { 3415 DebugVariable VarA(A->getDebugVariable(), A->getDebugExpression(), 3416 A->getDebugLoc()->getInlinedAt()); 3417 DebugVariable VarB(B->getDebugVariable(), B->getDebugExpression(), 3418 B->getDebugLoc()->getInlinedAt()); 3419 return AllVarsNumbering.find(VarA)->second < 3420 AllVarsNumbering.find(VarB)->second; 3421 }; 3422 3423 // Go through all the transfers recorded in the TransferTracker -- this is 3424 // both the live-ins to a block, and any movements of values that happen 3425 // in the middle. 3426 for (auto &P : TTracker->Transfers) { 3427 // Sort them according to appearance order. 3428 llvm::sort(P.Insts, OrderDbgValues); 3429 // Insert either before or after the designated point... 3430 if (P.MBB) { 3431 MachineBasicBlock &MBB = *P.MBB; 3432 for (auto *MI : P.Insts) { 3433 MBB.insert(P.Pos, MI); 3434 } 3435 } else { 3436 // Terminators, like tail calls, can clobber things. Don't try and place 3437 // transfers after them. 3438 if (P.Pos->isTerminator()) 3439 continue; 3440 3441 MachineBasicBlock &MBB = *P.Pos->getParent(); 3442 for (auto *MI : P.Insts) { 3443 MBB.insertAfterBundle(P.Pos, MI); 3444 } 3445 } 3446 } 3447 } 3448 3449 void InstrRefBasedLDV::initialSetup(MachineFunction &MF) { 3450 // Build some useful data structures. 3451 auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool { 3452 if (const DebugLoc &DL = MI.getDebugLoc()) 3453 return DL.getLine() != 0; 3454 return false; 3455 }; 3456 // Collect a set of all the artificial blocks. 3457 for (auto &MBB : MF) 3458 if (none_of(MBB.instrs(), hasNonArtificialLocation)) 3459 ArtificialBlocks.insert(&MBB); 3460 3461 // Compute mappings of block <=> RPO order. 3462 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF); 3463 unsigned int RPONumber = 0; 3464 for (MachineBasicBlock *MBB : RPOT) { 3465 OrderToBB[RPONumber] = MBB; 3466 BBToOrder[MBB] = RPONumber; 3467 BBNumToRPO[MBB->getNumber()] = RPONumber; 3468 ++RPONumber; 3469 } 3470 } 3471 3472 /// Calculate the liveness information for the given machine function and 3473 /// extend ranges across basic blocks. 3474 bool InstrRefBasedLDV::ExtendRanges(MachineFunction &MF, 3475 TargetPassConfig *TPC) { 3476 // No subprogram means this function contains no debuginfo. 3477 if (!MF.getFunction().getSubprogram()) 3478 return false; 3479 3480 LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n"); 3481 this->TPC = TPC; 3482 3483 TRI = MF.getSubtarget().getRegisterInfo(); 3484 TII = MF.getSubtarget().getInstrInfo(); 3485 TFI = MF.getSubtarget().getFrameLowering(); 3486 TFI->getCalleeSaves(MF, CalleeSavedRegs); 3487 MFI = &MF.getFrameInfo(); 3488 LS.initialize(MF); 3489 3490 MTracker = 3491 new MLocTracker(MF, *TII, *TRI, *MF.getSubtarget().getTargetLowering()); 3492 VTracker = nullptr; 3493 TTracker = nullptr; 3494 3495 SmallVector<MLocTransferMap, 32> MLocTransfer; 3496 SmallVector<VLocTracker, 8> vlocs; 3497 LiveInsT SavedLiveIns; 3498 3499 int MaxNumBlocks = -1; 3500 for (auto &MBB : MF) 3501 MaxNumBlocks = std::max(MBB.getNumber(), MaxNumBlocks); 3502 assert(MaxNumBlocks >= 0); 3503 ++MaxNumBlocks; 3504 3505 MLocTransfer.resize(MaxNumBlocks); 3506 vlocs.resize(MaxNumBlocks); 3507 SavedLiveIns.resize(MaxNumBlocks); 3508 3509 initialSetup(MF); 3510 3511 produceMLocTransferFunction(MF, MLocTransfer, MaxNumBlocks); 3512 3513 // Allocate and initialize two array-of-arrays for the live-in and live-out 3514 // machine values. The outer dimension is the block number; while the inner 3515 // dimension is a LocIdx from MLocTracker. 3516 ValueIDNum **MOutLocs = new ValueIDNum *[MaxNumBlocks]; 3517 ValueIDNum **MInLocs = new ValueIDNum *[MaxNumBlocks]; 3518 unsigned NumLocs = MTracker->getNumLocs(); 3519 for (int i = 0; i < MaxNumBlocks; ++i) { 3520 MOutLocs[i] = new ValueIDNum[NumLocs]; 3521 MInLocs[i] = new ValueIDNum[NumLocs]; 3522 } 3523 3524 // Solve the machine value dataflow problem using the MLocTransfer function, 3525 // storing the computed live-ins / live-outs into the array-of-arrays. We use 3526 // both live-ins and live-outs for decision making in the variable value 3527 // dataflow problem. 3528 mlocDataflow(MInLocs, MOutLocs, MLocTransfer); 3529 3530 // Patch up debug phi numbers, turning unknown block-live-in values into 3531 // either live-through machine values, or PHIs. 3532 for (auto &DBG_PHI : DebugPHINumToValue) { 3533 // Identify unresolved block-live-ins. 3534 ValueIDNum &Num = DBG_PHI.ValueRead; 3535 if (!Num.isPHI()) 3536 continue; 3537 3538 unsigned BlockNo = Num.getBlock(); 3539 LocIdx LocNo = Num.getLoc(); 3540 Num = MInLocs[BlockNo][LocNo.asU64()]; 3541 } 3542 // Later, we'll be looking up ranges of instruction numbers. 3543 llvm::sort(DebugPHINumToValue); 3544 3545 // Walk back through each block / instruction, collecting DBG_VALUE 3546 // instructions and recording what machine value their operands refer to. 3547 for (auto &OrderPair : OrderToBB) { 3548 MachineBasicBlock &MBB = *OrderPair.second; 3549 CurBB = MBB.getNumber(); 3550 VTracker = &vlocs[CurBB]; 3551 VTracker->MBB = &MBB; 3552 MTracker->loadFromArray(MInLocs[CurBB], CurBB); 3553 CurInst = 1; 3554 for (auto &MI : MBB) { 3555 process(MI, MOutLocs, MInLocs); 3556 ++CurInst; 3557 } 3558 MTracker->reset(); 3559 } 3560 3561 // Number all variables in the order that they appear, to be used as a stable 3562 // insertion order later. 3563 DenseMap<DebugVariable, unsigned> AllVarsNumbering; 3564 3565 // Map from one LexicalScope to all the variables in that scope. 3566 DenseMap<const LexicalScope *, SmallSet<DebugVariable, 4>> ScopeToVars; 3567 3568 // Map from One lexical scope to all blocks in that scope. 3569 DenseMap<const LexicalScope *, SmallPtrSet<MachineBasicBlock *, 4>> 3570 ScopeToBlocks; 3571 3572 // Store a DILocation that describes a scope. 3573 DenseMap<const LexicalScope *, const DILocation *> ScopeToDILocation; 3574 3575 // To mirror old LiveDebugValues, enumerate variables in RPOT order. Otherwise 3576 // the order is unimportant, it just has to be stable. 3577 for (unsigned int I = 0; I < OrderToBB.size(); ++I) { 3578 auto *MBB = OrderToBB[I]; 3579 auto *VTracker = &vlocs[MBB->getNumber()]; 3580 // Collect each variable with a DBG_VALUE in this block. 3581 for (auto &idx : VTracker->Vars) { 3582 const auto &Var = idx.first; 3583 const DILocation *ScopeLoc = VTracker->Scopes[Var]; 3584 assert(ScopeLoc != nullptr); 3585 auto *Scope = LS.findLexicalScope(ScopeLoc); 3586 3587 // No insts in scope -> shouldn't have been recorded. 3588 assert(Scope != nullptr); 3589 3590 AllVarsNumbering.insert(std::make_pair(Var, AllVarsNumbering.size())); 3591 ScopeToVars[Scope].insert(Var); 3592 ScopeToBlocks[Scope].insert(VTracker->MBB); 3593 ScopeToDILocation[Scope] = ScopeLoc; 3594 } 3595 } 3596 3597 // OK. Iterate over scopes: there might be something to be said for 3598 // ordering them by size/locality, but that's for the future. For each scope, 3599 // solve the variable value problem, producing a map of variables to values 3600 // in SavedLiveIns. 3601 for (auto &P : ScopeToVars) { 3602 vlocDataflow(P.first, ScopeToDILocation[P.first], P.second, 3603 ScopeToBlocks[P.first], SavedLiveIns, MOutLocs, MInLocs, 3604 vlocs); 3605 } 3606 3607 // Using the computed value locations and variable values for each block, 3608 // create the DBG_VALUE instructions representing the extended variable 3609 // locations. 3610 emitLocations(MF, SavedLiveIns, MOutLocs, MInLocs, AllVarsNumbering, *TPC); 3611 3612 for (int Idx = 0; Idx < MaxNumBlocks; ++Idx) { 3613 delete[] MOutLocs[Idx]; 3614 delete[] MInLocs[Idx]; 3615 } 3616 delete[] MOutLocs; 3617 delete[] MInLocs; 3618 3619 // Did we actually make any changes? If we created any DBG_VALUEs, then yes. 3620 bool Changed = TTracker->Transfers.size() != 0; 3621 3622 delete MTracker; 3623 delete TTracker; 3624 MTracker = nullptr; 3625 VTracker = nullptr; 3626 TTracker = nullptr; 3627 3628 ArtificialBlocks.clear(); 3629 OrderToBB.clear(); 3630 BBToOrder.clear(); 3631 BBNumToRPO.clear(); 3632 DebugInstrNumToInstr.clear(); 3633 DebugPHINumToValue.clear(); 3634 3635 return Changed; 3636 } 3637 3638 LDVImpl *llvm::makeInstrRefBasedLiveDebugValues() { 3639 return new InstrRefBasedLDV(); 3640 } 3641 3642 namespace { 3643 class LDVSSABlock; 3644 class LDVSSAUpdater; 3645 3646 // Pick a type to identify incoming block values as we construct SSA. We 3647 // can't use anything more robust than an integer unfortunately, as SSAUpdater 3648 // expects to zero-initialize the type. 3649 typedef uint64_t BlockValueNum; 3650 3651 /// Represents an SSA PHI node for the SSA updater class. Contains the block 3652 /// this PHI is in, the value number it would have, and the expected incoming 3653 /// values from parent blocks. 3654 class LDVSSAPhi { 3655 public: 3656 SmallVector<std::pair<LDVSSABlock *, BlockValueNum>, 4> IncomingValues; 3657 LDVSSABlock *ParentBlock; 3658 BlockValueNum PHIValNum; 3659 LDVSSAPhi(BlockValueNum PHIValNum, LDVSSABlock *ParentBlock) 3660 : ParentBlock(ParentBlock), PHIValNum(PHIValNum) {} 3661 3662 LDVSSABlock *getParent() { return ParentBlock; } 3663 }; 3664 3665 /// Thin wrapper around a block predecessor iterator. Only difference from a 3666 /// normal block iterator is that it dereferences to an LDVSSABlock. 3667 class LDVSSABlockIterator { 3668 public: 3669 MachineBasicBlock::pred_iterator PredIt; 3670 LDVSSAUpdater &Updater; 3671 3672 LDVSSABlockIterator(MachineBasicBlock::pred_iterator PredIt, 3673 LDVSSAUpdater &Updater) 3674 : PredIt(PredIt), Updater(Updater) {} 3675 3676 bool operator!=(const LDVSSABlockIterator &OtherIt) const { 3677 return OtherIt.PredIt != PredIt; 3678 } 3679 3680 LDVSSABlockIterator &operator++() { 3681 ++PredIt; 3682 return *this; 3683 } 3684 3685 LDVSSABlock *operator*(); 3686 }; 3687 3688 /// Thin wrapper around a block for SSA Updater interface. Necessary because 3689 /// we need to track the PHI value(s) that we may have observed as necessary 3690 /// in this block. 3691 class LDVSSABlock { 3692 public: 3693 MachineBasicBlock &BB; 3694 LDVSSAUpdater &Updater; 3695 using PHIListT = SmallVector<LDVSSAPhi, 1>; 3696 /// List of PHIs in this block. There should only ever be one. 3697 PHIListT PHIList; 3698 3699 LDVSSABlock(MachineBasicBlock &BB, LDVSSAUpdater &Updater) 3700 : BB(BB), Updater(Updater) {} 3701 3702 LDVSSABlockIterator succ_begin() { 3703 return LDVSSABlockIterator(BB.succ_begin(), Updater); 3704 } 3705 3706 LDVSSABlockIterator succ_end() { 3707 return LDVSSABlockIterator(BB.succ_end(), Updater); 3708 } 3709 3710 /// SSAUpdater has requested a PHI: create that within this block record. 3711 LDVSSAPhi *newPHI(BlockValueNum Value) { 3712 PHIList.emplace_back(Value, this); 3713 return &PHIList.back(); 3714 } 3715 3716 /// SSAUpdater wishes to know what PHIs already exist in this block. 3717 PHIListT &phis() { return PHIList; } 3718 }; 3719 3720 /// Utility class for the SSAUpdater interface: tracks blocks, PHIs and values 3721 /// while SSAUpdater is exploring the CFG. It's passed as a handle / baton to 3722 // SSAUpdaterTraits<LDVSSAUpdater>. 3723 class LDVSSAUpdater { 3724 public: 3725 /// Map of value numbers to PHI records. 3726 DenseMap<BlockValueNum, LDVSSAPhi *> PHIs; 3727 /// Map of which blocks generate Undef values -- blocks that are not 3728 /// dominated by any Def. 3729 DenseMap<MachineBasicBlock *, BlockValueNum> UndefMap; 3730 /// Map of machine blocks to our own records of them. 3731 DenseMap<MachineBasicBlock *, LDVSSABlock *> BlockMap; 3732 /// Machine location where any PHI must occur. 3733 LocIdx Loc; 3734 /// Table of live-in machine value numbers for blocks / locations. 3735 ValueIDNum **MLiveIns; 3736 3737 LDVSSAUpdater(LocIdx L, ValueIDNum **MLiveIns) : Loc(L), MLiveIns(MLiveIns) {} 3738 3739 void reset() { 3740 for (auto &Block : BlockMap) 3741 delete Block.second; 3742 3743 PHIs.clear(); 3744 UndefMap.clear(); 3745 BlockMap.clear(); 3746 } 3747 3748 ~LDVSSAUpdater() { reset(); } 3749 3750 /// For a given MBB, create a wrapper block for it. Stores it in the 3751 /// LDVSSAUpdater block map. 3752 LDVSSABlock *getSSALDVBlock(MachineBasicBlock *BB) { 3753 auto it = BlockMap.find(BB); 3754 if (it == BlockMap.end()) { 3755 BlockMap[BB] = new LDVSSABlock(*BB, *this); 3756 it = BlockMap.find(BB); 3757 } 3758 return it->second; 3759 } 3760 3761 /// Find the live-in value number for the given block. Looks up the value at 3762 /// the PHI location on entry. 3763 BlockValueNum getValue(LDVSSABlock *LDVBB) { 3764 return MLiveIns[LDVBB->BB.getNumber()][Loc.asU64()].asU64(); 3765 } 3766 }; 3767 3768 LDVSSABlock *LDVSSABlockIterator::operator*() { 3769 return Updater.getSSALDVBlock(*PredIt); 3770 } 3771 3772 #ifndef NDEBUG 3773 3774 raw_ostream &operator<<(raw_ostream &out, const LDVSSAPhi &PHI) { 3775 out << "SSALDVPHI " << PHI.PHIValNum; 3776 return out; 3777 } 3778 3779 #endif 3780 3781 } // namespace 3782 3783 namespace llvm { 3784 3785 /// Template specialization to give SSAUpdater access to CFG and value 3786 /// information. SSAUpdater calls methods in these traits, passing in the 3787 /// LDVSSAUpdater object, to learn about blocks and the values they define. 3788 /// It also provides methods to create PHI nodes and track them. 3789 template <> class SSAUpdaterTraits<LDVSSAUpdater> { 3790 public: 3791 using BlkT = LDVSSABlock; 3792 using ValT = BlockValueNum; 3793 using PhiT = LDVSSAPhi; 3794 using BlkSucc_iterator = LDVSSABlockIterator; 3795 3796 // Methods to access block successors -- dereferencing to our wrapper class. 3797 static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); } 3798 static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); } 3799 3800 /// Iterator for PHI operands. 3801 class PHI_iterator { 3802 private: 3803 LDVSSAPhi *PHI; 3804 unsigned Idx; 3805 3806 public: 3807 explicit PHI_iterator(LDVSSAPhi *P) // begin iterator 3808 : PHI(P), Idx(0) {} 3809 PHI_iterator(LDVSSAPhi *P, bool) // end iterator 3810 : PHI(P), Idx(PHI->IncomingValues.size()) {} 3811 3812 PHI_iterator &operator++() { 3813 Idx++; 3814 return *this; 3815 } 3816 bool operator==(const PHI_iterator &X) const { return Idx == X.Idx; } 3817 bool operator!=(const PHI_iterator &X) const { return !operator==(X); } 3818 3819 BlockValueNum getIncomingValue() { return PHI->IncomingValues[Idx].second; } 3820 3821 LDVSSABlock *getIncomingBlock() { return PHI->IncomingValues[Idx].first; } 3822 }; 3823 3824 static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); } 3825 3826 static inline PHI_iterator PHI_end(PhiT *PHI) { 3827 return PHI_iterator(PHI, true); 3828 } 3829 3830 /// FindPredecessorBlocks - Put the predecessors of BB into the Preds 3831 /// vector. 3832 static void FindPredecessorBlocks(LDVSSABlock *BB, 3833 SmallVectorImpl<LDVSSABlock *> *Preds) { 3834 for (MachineBasicBlock::pred_iterator PI = BB->BB.pred_begin(), 3835 E = BB->BB.pred_end(); 3836 PI != E; ++PI) 3837 Preds->push_back(BB->Updater.getSSALDVBlock(*PI)); 3838 } 3839 3840 /// GetUndefVal - Normally creates an IMPLICIT_DEF instruction with a new 3841 /// register. For LiveDebugValues, represents a block identified as not having 3842 /// any DBG_PHI predecessors. 3843 static BlockValueNum GetUndefVal(LDVSSABlock *BB, LDVSSAUpdater *Updater) { 3844 // Create a value number for this block -- it needs to be unique and in the 3845 // "undef" collection, so that we know it's not real. Use a number 3846 // representing a PHI into this block. 3847 BlockValueNum Num = ValueIDNum(BB->BB.getNumber(), 0, Updater->Loc).asU64(); 3848 Updater->UndefMap[&BB->BB] = Num; 3849 return Num; 3850 } 3851 3852 /// CreateEmptyPHI - Create a (representation of a) PHI in the given block. 3853 /// SSAUpdater will populate it with information about incoming values. The 3854 /// value number of this PHI is whatever the machine value number problem 3855 /// solution determined it to be. This includes non-phi values if SSAUpdater 3856 /// tries to create a PHI where the incoming values are identical. 3857 static BlockValueNum CreateEmptyPHI(LDVSSABlock *BB, unsigned NumPreds, 3858 LDVSSAUpdater *Updater) { 3859 BlockValueNum PHIValNum = Updater->getValue(BB); 3860 LDVSSAPhi *PHI = BB->newPHI(PHIValNum); 3861 Updater->PHIs[PHIValNum] = PHI; 3862 return PHIValNum; 3863 } 3864 3865 /// AddPHIOperand - Add the specified value as an operand of the PHI for 3866 /// the specified predecessor block. 3867 static void AddPHIOperand(LDVSSAPhi *PHI, BlockValueNum Val, LDVSSABlock *Pred) { 3868 PHI->IncomingValues.push_back(std::make_pair(Pred, Val)); 3869 } 3870 3871 /// ValueIsPHI - Check if the instruction that defines the specified value 3872 /// is a PHI instruction. 3873 static LDVSSAPhi *ValueIsPHI(BlockValueNum Val, LDVSSAUpdater *Updater) { 3874 auto PHIIt = Updater->PHIs.find(Val); 3875 if (PHIIt == Updater->PHIs.end()) 3876 return nullptr; 3877 return PHIIt->second; 3878 } 3879 3880 /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source 3881 /// operands, i.e., it was just added. 3882 static LDVSSAPhi *ValueIsNewPHI(BlockValueNum Val, LDVSSAUpdater *Updater) { 3883 LDVSSAPhi *PHI = ValueIsPHI(Val, Updater); 3884 if (PHI && PHI->IncomingValues.size() == 0) 3885 return PHI; 3886 return nullptr; 3887 } 3888 3889 /// GetPHIValue - For the specified PHI instruction, return the value 3890 /// that it defines. 3891 static BlockValueNum GetPHIValue(LDVSSAPhi *PHI) { return PHI->PHIValNum; } 3892 }; 3893 3894 } // end namespace llvm 3895 3896 Optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIs(MachineFunction &MF, 3897 ValueIDNum **MLiveOuts, 3898 ValueIDNum **MLiveIns, 3899 MachineInstr &Here, 3900 uint64_t InstrNum) { 3901 // Pick out records of DBG_PHI instructions that have been observed. If there 3902 // are none, then we cannot compute a value number. 3903 auto RangePair = std::equal_range(DebugPHINumToValue.begin(), 3904 DebugPHINumToValue.end(), InstrNum); 3905 auto LowerIt = RangePair.first; 3906 auto UpperIt = RangePair.second; 3907 3908 // No DBG_PHI means there can be no location. 3909 if (LowerIt == UpperIt) 3910 return None; 3911 3912 // If there's only one DBG_PHI, then that is our value number. 3913 if (std::distance(LowerIt, UpperIt) == 1) 3914 return LowerIt->ValueRead; 3915 3916 auto DBGPHIRange = make_range(LowerIt, UpperIt); 3917 3918 // Pick out the location (physreg, slot) where any PHIs must occur. It's 3919 // technically possible for us to merge values in different registers in each 3920 // block, but highly unlikely that LLVM will generate such code after register 3921 // allocation. 3922 LocIdx Loc = LowerIt->ReadLoc; 3923 3924 // We have several DBG_PHIs, and a use position (the Here inst). All each 3925 // DBG_PHI does is identify a value at a program position. We can treat each 3926 // DBG_PHI like it's a Def of a value, and the use position is a Use of a 3927 // value, just like SSA. We use the bulk-standard LLVM SSA updater class to 3928 // determine which Def is used at the Use, and any PHIs that happen along 3929 // the way. 3930 // Adapted LLVM SSA Updater: 3931 LDVSSAUpdater Updater(Loc, MLiveIns); 3932 // Map of which Def or PHI is the current value in each block. 3933 DenseMap<LDVSSABlock *, BlockValueNum> AvailableValues; 3934 // Set of PHIs that we have created along the way. 3935 SmallVector<LDVSSAPhi *, 8> CreatedPHIs; 3936 3937 // Each existing DBG_PHI is a Def'd value under this model. Record these Defs 3938 // for the SSAUpdater. 3939 for (const auto &DBG_PHI : DBGPHIRange) { 3940 LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB); 3941 const ValueIDNum &Num = DBG_PHI.ValueRead; 3942 AvailableValues.insert(std::make_pair(Block, Num.asU64())); 3943 } 3944 3945 LDVSSABlock *HereBlock = Updater.getSSALDVBlock(Here.getParent()); 3946 const auto &AvailIt = AvailableValues.find(HereBlock); 3947 if (AvailIt != AvailableValues.end()) { 3948 // Actually, we already know what the value is -- the Use is in the same 3949 // block as the Def. 3950 return ValueIDNum::fromU64(AvailIt->second); 3951 } 3952 3953 // Otherwise, we must use the SSA Updater. It will identify the value number 3954 // that we are to use, and the PHIs that must happen along the way. 3955 SSAUpdaterImpl<LDVSSAUpdater> Impl(&Updater, &AvailableValues, &CreatedPHIs); 3956 BlockValueNum ResultInt = Impl.GetValue(Updater.getSSALDVBlock(Here.getParent())); 3957 ValueIDNum Result = ValueIDNum::fromU64(ResultInt); 3958 3959 // We have the number for a PHI, or possibly live-through value, to be used 3960 // at this Use. There are a number of things we have to check about it though: 3961 // * Does any PHI use an 'Undef' (like an IMPLICIT_DEF) value? If so, this 3962 // Use was not completely dominated by DBG_PHIs and we should abort. 3963 // * Are the Defs or PHIs clobbered in a block? SSAUpdater isn't aware that 3964 // we've left SSA form. Validate that the inputs to each PHI are the 3965 // expected values. 3966 // * Is a PHI we've created actually a merging of values, or are all the 3967 // predecessor values the same, leading to a non-PHI machine value number? 3968 // (SSAUpdater doesn't know that either). Remap validated PHIs into the 3969 // the ValidatedValues collection below to sort this out. 3970 DenseMap<LDVSSABlock *, ValueIDNum> ValidatedValues; 3971 3972 // Define all the input DBG_PHI values in ValidatedValues. 3973 for (const auto &DBG_PHI : DBGPHIRange) { 3974 LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB); 3975 const ValueIDNum &Num = DBG_PHI.ValueRead; 3976 ValidatedValues.insert(std::make_pair(Block, Num)); 3977 } 3978 3979 // Sort PHIs to validate into RPO-order. 3980 SmallVector<LDVSSAPhi *, 8> SortedPHIs; 3981 for (auto &PHI : CreatedPHIs) 3982 SortedPHIs.push_back(PHI); 3983 3984 std::sort( 3985 SortedPHIs.begin(), SortedPHIs.end(), [&](LDVSSAPhi *A, LDVSSAPhi *B) { 3986 return BBToOrder[&A->getParent()->BB] < BBToOrder[&B->getParent()->BB]; 3987 }); 3988 3989 for (auto &PHI : SortedPHIs) { 3990 ValueIDNum ThisBlockValueNum = 3991 MLiveIns[PHI->ParentBlock->BB.getNumber()][Loc.asU64()]; 3992 3993 // Are all these things actually defined? 3994 for (auto &PHIIt : PHI->IncomingValues) { 3995 // Any undef input means DBG_PHIs didn't dominate the use point. 3996 if (Updater.UndefMap.find(&PHIIt.first->BB) != Updater.UndefMap.end()) 3997 return None; 3998 3999 ValueIDNum ValueToCheck; 4000 ValueIDNum *BlockLiveOuts = MLiveOuts[PHIIt.first->BB.getNumber()]; 4001 4002 auto VVal = ValidatedValues.find(PHIIt.first); 4003 if (VVal == ValidatedValues.end()) { 4004 // We cross a loop, and this is a backedge. LLVMs tail duplication 4005 // happens so late that DBG_PHI instructions should not be able to 4006 // migrate into loops -- meaning we can only be live-through this 4007 // loop. 4008 ValueToCheck = ThisBlockValueNum; 4009 } else { 4010 // Does the block have as a live-out, in the location we're examining, 4011 // the value that we expect? If not, it's been moved or clobbered. 4012 ValueToCheck = VVal->second; 4013 } 4014 4015 if (BlockLiveOuts[Loc.asU64()] != ValueToCheck) 4016 return None; 4017 } 4018 4019 // Record this value as validated. 4020 ValidatedValues.insert({PHI->ParentBlock, ThisBlockValueNum}); 4021 } 4022 4023 // All the PHIs are valid: we can return what the SSAUpdater said our value 4024 // number was. 4025 return Result; 4026 } 4027