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