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