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