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