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