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