1 //===- LiveDebugVariables.cpp - Tracking debug info variables -------------===// 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 // 9 // This file implements the LiveDebugVariables analysis. 10 // 11 // Remove all DBG_VALUE instructions referencing virtual registers and replace 12 // them with a data structure tracking where live user variables are kept - in a 13 // virtual register or in a stack slot. 14 // 15 // Allow the data structure to be updated during register allocation when values 16 // are moved between registers and stack slots. Finally emit new DBG_VALUE 17 // instructions after register allocation is complete. 18 // 19 //===----------------------------------------------------------------------===// 20 21 #include "LiveDebugVariables.h" 22 #include "llvm/ADT/ArrayRef.h" 23 #include "llvm/ADT/DenseMap.h" 24 #include "llvm/ADT/IntervalMap.h" 25 #include "llvm/ADT/MapVector.h" 26 #include "llvm/ADT/STLExtras.h" 27 #include "llvm/ADT/SmallSet.h" 28 #include "llvm/ADT/SmallVector.h" 29 #include "llvm/ADT/Statistic.h" 30 #include "llvm/ADT/StringRef.h" 31 #include "llvm/CodeGen/LexicalScopes.h" 32 #include "llvm/CodeGen/LiveInterval.h" 33 #include "llvm/CodeGen/LiveIntervals.h" 34 #include "llvm/CodeGen/MachineBasicBlock.h" 35 #include "llvm/CodeGen/MachineDominators.h" 36 #include "llvm/CodeGen/MachineFunction.h" 37 #include "llvm/CodeGen/MachineInstr.h" 38 #include "llvm/CodeGen/MachineInstrBuilder.h" 39 #include "llvm/CodeGen/MachineOperand.h" 40 #include "llvm/CodeGen/MachineRegisterInfo.h" 41 #include "llvm/CodeGen/SlotIndexes.h" 42 #include "llvm/CodeGen/TargetInstrInfo.h" 43 #include "llvm/CodeGen/TargetOpcodes.h" 44 #include "llvm/CodeGen/TargetRegisterInfo.h" 45 #include "llvm/CodeGen/TargetSubtargetInfo.h" 46 #include "llvm/CodeGen/VirtRegMap.h" 47 #include "llvm/Config/llvm-config.h" 48 #include "llvm/IR/DebugInfoMetadata.h" 49 #include "llvm/IR/DebugLoc.h" 50 #include "llvm/IR/Function.h" 51 #include "llvm/IR/Metadata.h" 52 #include "llvm/InitializePasses.h" 53 #include "llvm/MC/MCRegisterInfo.h" 54 #include "llvm/Pass.h" 55 #include "llvm/Support/Casting.h" 56 #include "llvm/Support/CommandLine.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/raw_ostream.h" 59 #include <algorithm> 60 #include <cassert> 61 #include <iterator> 62 #include <memory> 63 #include <utility> 64 65 using namespace llvm; 66 67 #define DEBUG_TYPE "livedebugvars" 68 69 static cl::opt<bool> 70 EnableLDV("live-debug-variables", cl::init(true), 71 cl::desc("Enable the live debug variables pass"), cl::Hidden); 72 73 STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted"); 74 STATISTIC(NumInsertedDebugLabels, "Number of DBG_LABELs inserted"); 75 76 char LiveDebugVariables::ID = 0; 77 78 INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE, 79 "Debug Variable Analysis", false, false) 80 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 81 INITIALIZE_PASS_DEPENDENCY(LiveIntervals) 82 INITIALIZE_PASS_END(LiveDebugVariables, DEBUG_TYPE, 83 "Debug Variable Analysis", false, false) 84 85 void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const { 86 AU.addRequired<MachineDominatorTree>(); 87 AU.addRequiredTransitive<LiveIntervals>(); 88 AU.setPreservesAll(); 89 MachineFunctionPass::getAnalysisUsage(AU); 90 } 91 92 LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID) { 93 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry()); 94 } 95 96 enum : unsigned { UndefLocNo = ~0U }; 97 98 namespace { 99 /// Describes a debug variable value by location number and expression along 100 /// with some flags about the original usage of the location. 101 class DbgVariableValue { 102 public: 103 DbgVariableValue(ArrayRef<unsigned> NewLocs, bool WasIndirect, bool WasList, 104 const DIExpression &Expr) 105 : WasIndirect(WasIndirect), WasList(WasList), Expression(&Expr) { 106 assert(!(WasIndirect && WasList) && 107 "DBG_VALUE_LISTs should not be indirect."); 108 SmallVector<unsigned> LocNoVec; 109 for (unsigned LocNo : NewLocs) { 110 auto It = find(LocNoVec, LocNo); 111 if (It == LocNoVec.end()) 112 LocNoVec.push_back(LocNo); 113 else { 114 // Loc duplicates an element in LocNos; replace references to Op 115 // with references to the duplicating element. 116 unsigned OpIdx = LocNoVec.size(); 117 unsigned DuplicatingIdx = std::distance(LocNoVec.begin(), It); 118 Expression = 119 DIExpression::replaceArg(Expression, OpIdx, DuplicatingIdx); 120 } 121 } 122 // A debug value referencing 64+ unique machine locations is very likely 123 // to be the result of a bug earlier in the pipeline. If by some means this 124 // limit is validly reached, then we can add a byte to the size of 125 // LocNoCount. 126 assert(LocNoVec.size() < 64 && 127 "debug value containing 64+ unique machine locations is not " 128 "supported by Live Debug Variables"); 129 LocNoCount = LocNoVec.size(); 130 if (LocNoCount > 0) { 131 LocNos.reset(new unsigned[LocNoCount]()); 132 std::copy(LocNoVec.begin(), LocNoVec.end(), loc_nos_begin()); 133 } 134 } 135 136 DbgVariableValue() : LocNoCount(0), WasIndirect(0), WasList(0) {} 137 DbgVariableValue(const DbgVariableValue &Other) 138 : LocNoCount(Other.LocNoCount), WasIndirect(Other.getWasIndirect()), 139 WasList(Other.getWasList()), Expression(Other.getExpression()) { 140 if (Other.getLocNoCount()) { 141 LocNos.reset(new unsigned[Other.getLocNoCount()]); 142 std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin()); 143 } 144 } 145 146 DbgVariableValue &operator=(const DbgVariableValue &Other) { 147 if (this == &Other) 148 return *this; 149 if (Other.getLocNoCount()) { 150 LocNos.reset(new unsigned[Other.getLocNoCount()]); 151 std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin()); 152 } else { 153 LocNos.release(); 154 } 155 LocNoCount = Other.getLocNoCount(); 156 WasIndirect = Other.getWasIndirect(); 157 WasList = Other.getWasList(); 158 Expression = Other.getExpression(); 159 return *this; 160 } 161 162 const DIExpression *getExpression() const { return Expression; } 163 uint8_t getLocNoCount() const { return LocNoCount; } 164 bool containsLocNo(unsigned LocNo) const { 165 return is_contained(loc_nos(), LocNo); 166 } 167 bool getWasIndirect() const { return WasIndirect; } 168 bool getWasList() const { return WasList; } 169 bool isUndef() const { return LocNoCount == 0 || containsLocNo(UndefLocNo); } 170 171 DbgVariableValue decrementLocNosAfterPivot(unsigned Pivot) const { 172 SmallVector<unsigned, 4> NewLocNos; 173 for (unsigned LocNo : loc_nos()) 174 NewLocNos.push_back(LocNo != UndefLocNo && LocNo > Pivot ? LocNo - 1 175 : LocNo); 176 return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression); 177 } 178 179 DbgVariableValue remapLocNos(ArrayRef<unsigned> LocNoMap) const { 180 SmallVector<unsigned> NewLocNos; 181 for (unsigned LocNo : loc_nos()) 182 // Undef values don't exist in locations (and thus not in LocNoMap 183 // either) so skip over them. See getLocationNo(). 184 NewLocNos.push_back(LocNo == UndefLocNo ? UndefLocNo : LocNoMap[LocNo]); 185 return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression); 186 } 187 188 DbgVariableValue changeLocNo(unsigned OldLocNo, unsigned NewLocNo) const { 189 SmallVector<unsigned> NewLocNos; 190 NewLocNos.assign(loc_nos_begin(), loc_nos_end()); 191 auto OldLocIt = find(NewLocNos, OldLocNo); 192 assert(OldLocIt != NewLocNos.end() && "Old location must be present."); 193 *OldLocIt = NewLocNo; 194 return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression); 195 } 196 197 bool hasLocNoGreaterThan(unsigned LocNo) const { 198 return any_of(loc_nos(), 199 [LocNo](unsigned ThisLocNo) { return ThisLocNo > LocNo; }); 200 } 201 202 void printLocNos(llvm::raw_ostream &OS) const { 203 for (const unsigned &Loc : loc_nos()) 204 OS << (&Loc == loc_nos_begin() ? " " : ", ") << Loc; 205 } 206 207 friend inline bool operator==(const DbgVariableValue &LHS, 208 const DbgVariableValue &RHS) { 209 if (std::tie(LHS.LocNoCount, LHS.WasIndirect, LHS.WasList, 210 LHS.Expression) != 211 std::tie(RHS.LocNoCount, RHS.WasIndirect, RHS.WasList, RHS.Expression)) 212 return false; 213 return std::equal(LHS.loc_nos_begin(), LHS.loc_nos_end(), 214 RHS.loc_nos_begin()); 215 } 216 217 friend inline bool operator!=(const DbgVariableValue &LHS, 218 const DbgVariableValue &RHS) { 219 return !(LHS == RHS); 220 } 221 222 unsigned *loc_nos_begin() { return LocNos.get(); } 223 const unsigned *loc_nos_begin() const { return LocNos.get(); } 224 unsigned *loc_nos_end() { return LocNos.get() + LocNoCount; } 225 const unsigned *loc_nos_end() const { return LocNos.get() + LocNoCount; } 226 ArrayRef<unsigned> loc_nos() const { 227 return ArrayRef<unsigned>(LocNos.get(), LocNoCount); 228 } 229 230 private: 231 // IntervalMap requires the value object to be very small, to the extent 232 // that we do not have enough room for an std::vector. Using a C-style array 233 // (with a unique_ptr wrapper for convenience) allows us to optimize for this 234 // specific case by packing the array size into only 6 bits (it is highly 235 // unlikely that any debug value will need 64+ locations). 236 std::unique_ptr<unsigned[]> LocNos; 237 uint8_t LocNoCount : 6; 238 bool WasIndirect : 1; 239 bool WasList : 1; 240 const DIExpression *Expression = nullptr; 241 }; 242 } // namespace 243 244 /// Map of where a user value is live to that value. 245 using LocMap = IntervalMap<SlotIndex, DbgVariableValue, 4>; 246 247 /// Map of stack slot offsets for spilled locations. 248 /// Non-spilled locations are not added to the map. 249 using SpillOffsetMap = DenseMap<unsigned, unsigned>; 250 251 /// Cache to save the location where it can be used as the starting 252 /// position as input for calling MachineBasicBlock::SkipPHIsLabelsAndDebug. 253 /// This is to prevent MachineBasicBlock::SkipPHIsLabelsAndDebug from 254 /// repeatedly searching the same set of PHIs/Labels/Debug instructions 255 /// if it is called many times for the same block. 256 using BlockSkipInstsMap = 257 DenseMap<MachineBasicBlock *, MachineBasicBlock::iterator>; 258 259 namespace { 260 261 class LDVImpl; 262 263 /// A user value is a part of a debug info user variable. 264 /// 265 /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register 266 /// holds part of a user variable. The part is identified by a byte offset. 267 /// 268 /// UserValues are grouped into equivalence classes for easier searching. Two 269 /// user values are related if they are held by the same virtual register. The 270 /// equivalence class is the transitive closure of that relation. 271 class UserValue { 272 const DILocalVariable *Variable; ///< The debug info variable we are part of. 273 /// The part of the variable we describe. 274 const Optional<DIExpression::FragmentInfo> Fragment; 275 DebugLoc dl; ///< The debug location for the variable. This is 276 ///< used by dwarf writer to find lexical scope. 277 UserValue *leader; ///< Equivalence class leader. 278 UserValue *next = nullptr; ///< Next value in equivalence class, or null. 279 280 /// Numbered locations referenced by locmap. 281 SmallVector<MachineOperand, 4> locations; 282 283 /// Map of slot indices where this value is live. 284 LocMap locInts; 285 286 /// Set of interval start indexes that have been trimmed to the 287 /// lexical scope. 288 SmallSet<SlotIndex, 2> trimmedDefs; 289 290 /// Insert a DBG_VALUE into MBB at Idx for DbgValue. 291 void insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx, 292 SlotIndex StopIdx, DbgVariableValue DbgValue, 293 ArrayRef<bool> LocSpills, 294 ArrayRef<unsigned> SpillOffsets, LiveIntervals &LIS, 295 const TargetInstrInfo &TII, 296 const TargetRegisterInfo &TRI, 297 BlockSkipInstsMap &BBSkipInstsMap); 298 299 /// Replace OldLocNo ranges with NewRegs ranges where NewRegs 300 /// is live. Returns true if any changes were made. 301 bool splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs, 302 LiveIntervals &LIS); 303 304 public: 305 /// Create a new UserValue. 306 UserValue(const DILocalVariable *var, 307 Optional<DIExpression::FragmentInfo> Fragment, DebugLoc L, 308 LocMap::Allocator &alloc) 309 : Variable(var), Fragment(Fragment), dl(std::move(L)), leader(this), 310 locInts(alloc) {} 311 312 /// Get the leader of this value's equivalence class. 313 UserValue *getLeader() { 314 UserValue *l = leader; 315 while (l != l->leader) 316 l = l->leader; 317 return leader = l; 318 } 319 320 /// Return the next UserValue in the equivalence class. 321 UserValue *getNext() const { return next; } 322 323 /// Merge equivalence classes. 324 static UserValue *merge(UserValue *L1, UserValue *L2) { 325 L2 = L2->getLeader(); 326 if (!L1) 327 return L2; 328 L1 = L1->getLeader(); 329 if (L1 == L2) 330 return L1; 331 // Splice L2 before L1's members. 332 UserValue *End = L2; 333 while (End->next) { 334 End->leader = L1; 335 End = End->next; 336 } 337 End->leader = L1; 338 End->next = L1->next; 339 L1->next = L2; 340 return L1; 341 } 342 343 /// Return the location number that matches Loc. 344 /// 345 /// For undef values we always return location number UndefLocNo without 346 /// inserting anything in locations. Since locations is a vector and the 347 /// location number is the position in the vector and UndefLocNo is ~0, 348 /// we would need a very big vector to put the value at the right position. 349 unsigned getLocationNo(const MachineOperand &LocMO) { 350 if (LocMO.isReg()) { 351 if (LocMO.getReg() == 0) 352 return UndefLocNo; 353 // For register locations we dont care about use/def and other flags. 354 for (unsigned i = 0, e = locations.size(); i != e; ++i) 355 if (locations[i].isReg() && 356 locations[i].getReg() == LocMO.getReg() && 357 locations[i].getSubReg() == LocMO.getSubReg()) 358 return i; 359 } else 360 for (unsigned i = 0, e = locations.size(); i != e; ++i) 361 if (LocMO.isIdenticalTo(locations[i])) 362 return i; 363 locations.push_back(LocMO); 364 // We are storing a MachineOperand outside a MachineInstr. 365 locations.back().clearParent(); 366 // Don't store def operands. 367 if (locations.back().isReg()) { 368 if (locations.back().isDef()) 369 locations.back().setIsDead(false); 370 locations.back().setIsUse(); 371 } 372 return locations.size() - 1; 373 } 374 375 /// Remove (recycle) a location number. If \p LocNo still is used by the 376 /// locInts nothing is done. 377 void removeLocationIfUnused(unsigned LocNo) { 378 // Bail out if LocNo still is used. 379 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) { 380 const DbgVariableValue &DbgValue = I.value(); 381 if (DbgValue.containsLocNo(LocNo)) 382 return; 383 } 384 // Remove the entry in the locations vector, and adjust all references to 385 // location numbers above the removed entry. 386 locations.erase(locations.begin() + LocNo); 387 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) { 388 const DbgVariableValue &DbgValue = I.value(); 389 if (DbgValue.hasLocNoGreaterThan(LocNo)) 390 I.setValueUnchecked(DbgValue.decrementLocNosAfterPivot(LocNo)); 391 } 392 } 393 394 /// Ensure that all virtual register locations are mapped. 395 void mapVirtRegs(LDVImpl *LDV); 396 397 /// Add a definition point to this user value. 398 void addDef(SlotIndex Idx, ArrayRef<MachineOperand> LocMOs, bool IsIndirect, 399 bool IsList, const DIExpression &Expr) { 400 SmallVector<unsigned> Locs; 401 for (MachineOperand Op : LocMOs) 402 Locs.push_back(getLocationNo(Op)); 403 DbgVariableValue DbgValue(Locs, IsIndirect, IsList, Expr); 404 // Add a singular (Idx,Idx) -> value mapping. 405 LocMap::iterator I = locInts.find(Idx); 406 if (!I.valid() || I.start() != Idx) 407 I.insert(Idx, Idx.getNextSlot(), std::move(DbgValue)); 408 else 409 // A later DBG_VALUE at the same SlotIndex overrides the old location. 410 I.setValue(std::move(DbgValue)); 411 } 412 413 /// Extend the current definition as far as possible down. 414 /// 415 /// Stop when meeting an existing def or when leaving the live 416 /// range of VNI. End points where VNI is no longer live are added to Kills. 417 /// 418 /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a 419 /// data-flow analysis to propagate them beyond basic block boundaries. 420 /// 421 /// \param Idx Starting point for the definition. 422 /// \param DbgValue value to propagate. 423 /// \param LiveIntervalInfo For each location number key in this map, 424 /// restricts liveness to where the LiveRange has the value equal to the\ 425 /// VNInfo. 426 /// \param [out] Kills Append end points of VNI's live range to Kills. 427 /// \param LIS Live intervals analysis. 428 void extendDef(SlotIndex Idx, DbgVariableValue DbgValue, 429 SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>> 430 &LiveIntervalInfo, 431 Optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills, 432 LiveIntervals &LIS); 433 434 /// The value in LI may be copies to other registers. Determine if 435 /// any of the copies are available at the kill points, and add defs if 436 /// possible. 437 /// 438 /// \param DbgValue Location number of LI->reg, and DIExpression. 439 /// \param LocIntervals Scan for copies of the value for each location in the 440 /// corresponding LiveInterval->reg. 441 /// \param KilledAt The point where the range of DbgValue could be extended. 442 /// \param [in,out] NewDefs Append (Idx, DbgValue) of inserted defs here. 443 void addDefsFromCopies( 444 DbgVariableValue DbgValue, 445 SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals, 446 SlotIndex KilledAt, 447 SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs, 448 MachineRegisterInfo &MRI, LiveIntervals &LIS); 449 450 /// Compute the live intervals of all locations after collecting all their 451 /// def points. 452 void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, 453 LiveIntervals &LIS, LexicalScopes &LS); 454 455 /// Replace OldReg ranges with NewRegs ranges where NewRegs is 456 /// live. Returns true if any changes were made. 457 bool splitRegister(Register OldReg, ArrayRef<Register> NewRegs, 458 LiveIntervals &LIS); 459 460 /// Rewrite virtual register locations according to the provided virtual 461 /// register map. Record the stack slot offsets for the locations that 462 /// were spilled. 463 void rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF, 464 const TargetInstrInfo &TII, 465 const TargetRegisterInfo &TRI, 466 SpillOffsetMap &SpillOffsets); 467 468 /// Recreate DBG_VALUE instruction from data structures. 469 void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS, 470 const TargetInstrInfo &TII, 471 const TargetRegisterInfo &TRI, 472 const SpillOffsetMap &SpillOffsets, 473 BlockSkipInstsMap &BBSkipInstsMap); 474 475 /// Return DebugLoc of this UserValue. 476 DebugLoc getDebugLoc() { return dl;} 477 478 void print(raw_ostream &, const TargetRegisterInfo *); 479 }; 480 481 /// A user label is a part of a debug info user label. 482 class UserLabel { 483 const DILabel *Label; ///< The debug info label we are part of. 484 DebugLoc dl; ///< The debug location for the label. This is 485 ///< used by dwarf writer to find lexical scope. 486 SlotIndex loc; ///< Slot used by the debug label. 487 488 /// Insert a DBG_LABEL into MBB at Idx. 489 void insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx, 490 LiveIntervals &LIS, const TargetInstrInfo &TII, 491 BlockSkipInstsMap &BBSkipInstsMap); 492 493 public: 494 /// Create a new UserLabel. 495 UserLabel(const DILabel *label, DebugLoc L, SlotIndex Idx) 496 : Label(label), dl(std::move(L)), loc(Idx) {} 497 498 /// Does this UserLabel match the parameters? 499 bool matches(const DILabel *L, const DILocation *IA, 500 const SlotIndex Index) const { 501 return Label == L && dl->getInlinedAt() == IA && loc == Index; 502 } 503 504 /// Recreate DBG_LABEL instruction from data structures. 505 void emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII, 506 BlockSkipInstsMap &BBSkipInstsMap); 507 508 /// Return DebugLoc of this UserLabel. 509 DebugLoc getDebugLoc() { return dl; } 510 511 void print(raw_ostream &, const TargetRegisterInfo *); 512 }; 513 514 /// Implementation of the LiveDebugVariables pass. 515 class LDVImpl { 516 LiveDebugVariables &pass; 517 LocMap::Allocator allocator; 518 MachineFunction *MF = nullptr; 519 LiveIntervals *LIS; 520 const TargetRegisterInfo *TRI; 521 522 using StashedInstrRef = 523 std::tuple<unsigned, unsigned, const DILocalVariable *, 524 const DIExpression *, DebugLoc>; 525 std::map<SlotIndex, std::vector<StashedInstrRef>> StashedInstrReferences; 526 527 /// Whether emitDebugValues is called. 528 bool EmitDone = false; 529 530 /// Whether the machine function is modified during the pass. 531 bool ModifiedMF = false; 532 533 /// All allocated UserValue instances. 534 SmallVector<std::unique_ptr<UserValue>, 8> userValues; 535 536 /// All allocated UserLabel instances. 537 SmallVector<std::unique_ptr<UserLabel>, 2> userLabels; 538 539 /// Map virtual register to eq class leader. 540 using VRMap = DenseMap<unsigned, UserValue *>; 541 VRMap virtRegToEqClass; 542 543 /// Map to find existing UserValue instances. 544 using UVMap = DenseMap<DebugVariable, UserValue *>; 545 UVMap userVarMap; 546 547 /// Find or create a UserValue. 548 UserValue *getUserValue(const DILocalVariable *Var, 549 Optional<DIExpression::FragmentInfo> Fragment, 550 const DebugLoc &DL); 551 552 /// Find the EC leader for VirtReg or null. 553 UserValue *lookupVirtReg(Register VirtReg); 554 555 /// Add DBG_VALUE instruction to our maps. 556 /// 557 /// \param MI DBG_VALUE instruction 558 /// \param Idx Last valid SLotIndex before instruction. 559 /// 560 /// \returns True if the DBG_VALUE instruction should be deleted. 561 bool handleDebugValue(MachineInstr &MI, SlotIndex Idx); 562 563 /// Track a DBG_INSTR_REF. This needs to be removed from the MachineFunction 564 /// during regalloc -- but there's no need to maintain live ranges, as we 565 /// refer to a value rather than a location. 566 /// 567 /// \param MI DBG_INSTR_REF instruction 568 /// \param Idx Last valid SlotIndex before instruction 569 /// 570 /// \returns True if the DBG_VALUE instruction should be deleted. 571 bool handleDebugInstrRef(MachineInstr &MI, SlotIndex Idx); 572 573 /// Add DBG_LABEL instruction to UserLabel. 574 /// 575 /// \param MI DBG_LABEL instruction 576 /// \param Idx Last valid SlotIndex before instruction. 577 /// 578 /// \returns True if the DBG_LABEL instruction should be deleted. 579 bool handleDebugLabel(MachineInstr &MI, SlotIndex Idx); 580 581 /// Collect and erase all DBG_VALUE instructions, adding a UserValue def 582 /// for each instruction. 583 /// 584 /// \param mf MachineFunction to be scanned. 585 /// 586 /// \returns True if any debug values were found. 587 bool collectDebugValues(MachineFunction &mf); 588 589 /// Compute the live intervals of all user values after collecting all 590 /// their def points. 591 void computeIntervals(); 592 593 public: 594 LDVImpl(LiveDebugVariables *ps) : pass(*ps) {} 595 596 bool runOnMachineFunction(MachineFunction &mf); 597 598 /// Release all memory. 599 void clear() { 600 MF = nullptr; 601 StashedInstrReferences.clear(); 602 userValues.clear(); 603 userLabels.clear(); 604 virtRegToEqClass.clear(); 605 userVarMap.clear(); 606 // Make sure we call emitDebugValues if the machine function was modified. 607 assert((!ModifiedMF || EmitDone) && 608 "Dbg values are not emitted in LDV"); 609 EmitDone = false; 610 ModifiedMF = false; 611 } 612 613 /// Map virtual register to an equivalence class. 614 void mapVirtReg(Register VirtReg, UserValue *EC); 615 616 /// Replace all references to OldReg with NewRegs. 617 void splitRegister(Register OldReg, ArrayRef<Register> NewRegs); 618 619 /// Recreate DBG_VALUE instruction from data structures. 620 void emitDebugValues(VirtRegMap *VRM); 621 622 void print(raw_ostream&); 623 }; 624 625 } // end anonymous namespace 626 627 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 628 static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS, 629 const LLVMContext &Ctx) { 630 if (!DL) 631 return; 632 633 auto *Scope = cast<DIScope>(DL.getScope()); 634 // Omit the directory, because it's likely to be long and uninteresting. 635 CommentOS << Scope->getFilename(); 636 CommentOS << ':' << DL.getLine(); 637 if (DL.getCol() != 0) 638 CommentOS << ':' << DL.getCol(); 639 640 DebugLoc InlinedAtDL = DL.getInlinedAt(); 641 if (!InlinedAtDL) 642 return; 643 644 CommentOS << " @[ "; 645 printDebugLoc(InlinedAtDL, CommentOS, Ctx); 646 CommentOS << " ]"; 647 } 648 649 static void printExtendedName(raw_ostream &OS, const DINode *Node, 650 const DILocation *DL) { 651 const LLVMContext &Ctx = Node->getContext(); 652 StringRef Res; 653 unsigned Line = 0; 654 if (const auto *V = dyn_cast<const DILocalVariable>(Node)) { 655 Res = V->getName(); 656 Line = V->getLine(); 657 } else if (const auto *L = dyn_cast<const DILabel>(Node)) { 658 Res = L->getName(); 659 Line = L->getLine(); 660 } 661 662 if (!Res.empty()) 663 OS << Res << "," << Line; 664 auto *InlinedAt = DL ? DL->getInlinedAt() : nullptr; 665 if (InlinedAt) { 666 if (DebugLoc InlinedAtDL = InlinedAt) { 667 OS << " @["; 668 printDebugLoc(InlinedAtDL, OS, Ctx); 669 OS << "]"; 670 } 671 } 672 } 673 674 void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) { 675 OS << "!\""; 676 printExtendedName(OS, Variable, dl); 677 678 OS << "\"\t"; 679 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) { 680 OS << " [" << I.start() << ';' << I.stop() << "):"; 681 if (I.value().isUndef()) 682 OS << " undef"; 683 else { 684 I.value().printLocNos(OS); 685 if (I.value().getWasIndirect()) 686 OS << " ind"; 687 else if (I.value().getWasList()) 688 OS << " list"; 689 } 690 } 691 for (unsigned i = 0, e = locations.size(); i != e; ++i) { 692 OS << " Loc" << i << '='; 693 locations[i].print(OS, TRI); 694 } 695 OS << '\n'; 696 } 697 698 void UserLabel::print(raw_ostream &OS, const TargetRegisterInfo *TRI) { 699 OS << "!\""; 700 printExtendedName(OS, Label, dl); 701 702 OS << "\"\t"; 703 OS << loc; 704 OS << '\n'; 705 } 706 707 void LDVImpl::print(raw_ostream &OS) { 708 OS << "********** DEBUG VARIABLES **********\n"; 709 for (auto &userValue : userValues) 710 userValue->print(OS, TRI); 711 OS << "********** DEBUG LABELS **********\n"; 712 for (auto &userLabel : userLabels) 713 userLabel->print(OS, TRI); 714 } 715 #endif 716 717 void UserValue::mapVirtRegs(LDVImpl *LDV) { 718 for (unsigned i = 0, e = locations.size(); i != e; ++i) 719 if (locations[i].isReg() && 720 Register::isVirtualRegister(locations[i].getReg())) 721 LDV->mapVirtReg(locations[i].getReg(), this); 722 } 723 724 UserValue *LDVImpl::getUserValue(const DILocalVariable *Var, 725 Optional<DIExpression::FragmentInfo> Fragment, 726 const DebugLoc &DL) { 727 // FIXME: Handle partially overlapping fragments. See 728 // https://reviews.llvm.org/D70121#1849741. 729 DebugVariable ID(Var, Fragment, DL->getInlinedAt()); 730 UserValue *&UV = userVarMap[ID]; 731 if (!UV) { 732 userValues.push_back( 733 std::make_unique<UserValue>(Var, Fragment, DL, allocator)); 734 UV = userValues.back().get(); 735 } 736 return UV; 737 } 738 739 void LDVImpl::mapVirtReg(Register VirtReg, UserValue *EC) { 740 assert(Register::isVirtualRegister(VirtReg) && "Only map VirtRegs"); 741 UserValue *&Leader = virtRegToEqClass[VirtReg]; 742 Leader = UserValue::merge(Leader, EC); 743 } 744 745 UserValue *LDVImpl::lookupVirtReg(Register VirtReg) { 746 if (UserValue *UV = virtRegToEqClass.lookup(VirtReg)) 747 return UV->getLeader(); 748 return nullptr; 749 } 750 751 bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) { 752 // DBG_VALUE loc, offset, variable, expr 753 // DBG_VALUE_LIST variable, expr, locs... 754 if (!MI.isDebugValue()) { 755 LLVM_DEBUG(dbgs() << "Can't handle non-DBG_VALUE*: " << MI); 756 return false; 757 } 758 if (!MI.getDebugVariableOp().isMetadata()) { 759 LLVM_DEBUG(dbgs() << "Can't handle DBG_VALUE* with invalid variable: " 760 << MI); 761 return false; 762 } 763 if (MI.isNonListDebugValue() && 764 (MI.getNumOperands() != 4 || 765 !(MI.getDebugOffset().isImm() || MI.getDebugOffset().isReg()))) { 766 LLVM_DEBUG(dbgs() << "Can't handle malformed DBG_VALUE: " << MI); 767 return false; 768 } 769 770 // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual 771 // register that hasn't been defined yet. If we do not remove those here, then 772 // the re-insertion of the DBG_VALUE instruction after register allocation 773 // will be incorrect. 774 // TODO: If earlier passes are corrected to generate sane debug information 775 // (and if the machine verifier is improved to catch this), then these checks 776 // could be removed or replaced by asserts. 777 bool Discard = false; 778 for (const MachineOperand &Op : MI.debug_operands()) { 779 if (Op.isReg() && Register::isVirtualRegister(Op.getReg())) { 780 const Register Reg = Op.getReg(); 781 if (!LIS->hasInterval(Reg)) { 782 // The DBG_VALUE is described by a virtual register that does not have a 783 // live interval. Discard the DBG_VALUE. 784 Discard = true; 785 LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx 786 << " " << MI); 787 } else { 788 // The DBG_VALUE is only valid if either Reg is live out from Idx, or 789 // Reg is defined dead at Idx (where Idx is the slot index for the 790 // instruction preceding the DBG_VALUE). 791 const LiveInterval &LI = LIS->getInterval(Reg); 792 LiveQueryResult LRQ = LI.Query(Idx); 793 if (!LRQ.valueOutOrDead()) { 794 // We have found a DBG_VALUE with the value in a virtual register that 795 // is not live. Discard the DBG_VALUE. 796 Discard = true; 797 LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx 798 << " " << MI); 799 } 800 } 801 } 802 } 803 804 // Get or create the UserValue for (variable,offset) here. 805 bool IsIndirect = MI.isDebugOffsetImm(); 806 if (IsIndirect) 807 assert(MI.getDebugOffset().getImm() == 0 && 808 "DBG_VALUE with nonzero offset"); 809 bool IsList = MI.isDebugValueList(); 810 const DILocalVariable *Var = MI.getDebugVariable(); 811 const DIExpression *Expr = MI.getDebugExpression(); 812 UserValue *UV = getUserValue(Var, Expr->getFragmentInfo(), MI.getDebugLoc()); 813 if (!Discard) 814 UV->addDef(Idx, 815 ArrayRef<MachineOperand>(MI.debug_operands().begin(), 816 MI.debug_operands().end()), 817 IsIndirect, IsList, *Expr); 818 else { 819 MachineOperand MO = MachineOperand::CreateReg(0U, false); 820 MO.setIsDebug(); 821 // We should still pass a list the same size as MI.debug_operands() even if 822 // all MOs are undef, so that DbgVariableValue can correctly adjust the 823 // expression while removing the duplicated undefs. 824 SmallVector<MachineOperand, 4> UndefMOs(MI.getNumDebugOperands(), MO); 825 UV->addDef(Idx, UndefMOs, false, IsList, *Expr); 826 } 827 return true; 828 } 829 830 bool LDVImpl::handleDebugInstrRef(MachineInstr &MI, SlotIndex Idx) { 831 assert(MI.isDebugRef()); 832 unsigned InstrNum = MI.getOperand(0).getImm(); 833 unsigned OperandNum = MI.getOperand(1).getImm(); 834 auto *Var = MI.getDebugVariable(); 835 auto *Expr = MI.getDebugExpression(); 836 auto &DL = MI.getDebugLoc(); 837 StashedInstrRef Stashed = 838 std::make_tuple(InstrNum, OperandNum, Var, Expr, DL); 839 StashedInstrReferences[Idx].push_back(Stashed); 840 return true; 841 } 842 843 bool LDVImpl::handleDebugLabel(MachineInstr &MI, SlotIndex Idx) { 844 // DBG_LABEL label 845 if (MI.getNumOperands() != 1 || !MI.getOperand(0).isMetadata()) { 846 LLVM_DEBUG(dbgs() << "Can't handle " << MI); 847 return false; 848 } 849 850 // Get or create the UserLabel for label here. 851 const DILabel *Label = MI.getDebugLabel(); 852 const DebugLoc &DL = MI.getDebugLoc(); 853 bool Found = false; 854 for (auto const &L : userLabels) { 855 if (L->matches(Label, DL->getInlinedAt(), Idx)) { 856 Found = true; 857 break; 858 } 859 } 860 if (!Found) 861 userLabels.push_back(std::make_unique<UserLabel>(Label, DL, Idx)); 862 863 return true; 864 } 865 866 bool LDVImpl::collectDebugValues(MachineFunction &mf) { 867 bool Changed = false; 868 for (MachineBasicBlock &MBB : mf) { 869 for (MachineBasicBlock::iterator MBBI = MBB.begin(), MBBE = MBB.end(); 870 MBBI != MBBE;) { 871 // Use the first debug instruction in the sequence to get a SlotIndex 872 // for following consecutive debug instructions. 873 if (!MBBI->isDebugOrPseudoInstr()) { 874 ++MBBI; 875 continue; 876 } 877 // Debug instructions has no slot index. Use the previous 878 // non-debug instruction's SlotIndex as its SlotIndex. 879 SlotIndex Idx = 880 MBBI == MBB.begin() 881 ? LIS->getMBBStartIdx(&MBB) 882 : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot(); 883 // Handle consecutive debug instructions with the same slot index. 884 do { 885 // Only handle DBG_VALUE in handleDebugValue(). Skip all other 886 // kinds of debug instructions. 887 if ((MBBI->isDebugValue() && handleDebugValue(*MBBI, Idx)) || 888 (MBBI->isDebugRef() && handleDebugInstrRef(*MBBI, Idx)) || 889 (MBBI->isDebugLabel() && handleDebugLabel(*MBBI, Idx))) { 890 MBBI = MBB.erase(MBBI); 891 Changed = true; 892 } else 893 ++MBBI; 894 } while (MBBI != MBBE && MBBI->isDebugOrPseudoInstr()); 895 } 896 } 897 return Changed; 898 } 899 900 void UserValue::extendDef( 901 SlotIndex Idx, DbgVariableValue DbgValue, 902 SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>> 903 &LiveIntervalInfo, 904 Optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills, 905 LiveIntervals &LIS) { 906 SlotIndex Start = Idx; 907 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start); 908 SlotIndex Stop = LIS.getMBBEndIdx(MBB); 909 LocMap::iterator I = locInts.find(Start); 910 911 // Limit to the intersection of the VNIs' live ranges. 912 for (auto &LII : LiveIntervalInfo) { 913 LiveRange *LR = LII.second.first; 914 assert(LR && LII.second.second && "Missing range info for Idx."); 915 LiveInterval::Segment *Segment = LR->getSegmentContaining(Start); 916 assert(Segment && Segment->valno == LII.second.second && 917 "Invalid VNInfo for Idx given?"); 918 if (Segment->end < Stop) { 919 Stop = Segment->end; 920 Kills = {Stop, {LII.first}}; 921 } else if (Segment->end == Stop && Kills.hasValue()) { 922 // If multiple locations end at the same place, track all of them in 923 // Kills. 924 Kills->second.push_back(LII.first); 925 } 926 } 927 928 // There could already be a short def at Start. 929 if (I.valid() && I.start() <= Start) { 930 // Stop when meeting a different location or an already extended interval. 931 Start = Start.getNextSlot(); 932 if (I.value() != DbgValue || I.stop() != Start) { 933 // Clear `Kills`, as we have a new def available. 934 Kills = None; 935 return; 936 } 937 // This is a one-slot placeholder. Just skip it. 938 ++I; 939 } 940 941 // Limited by the next def. 942 if (I.valid() && I.start() < Stop) { 943 Stop = I.start(); 944 // Clear `Kills`, as we have a new def available. 945 Kills = None; 946 } 947 948 if (Start < Stop) { 949 DbgVariableValue ExtDbgValue(DbgValue); 950 I.insert(Start, Stop, std::move(ExtDbgValue)); 951 } 952 } 953 954 void UserValue::addDefsFromCopies( 955 DbgVariableValue DbgValue, 956 SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals, 957 SlotIndex KilledAt, 958 SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs, 959 MachineRegisterInfo &MRI, LiveIntervals &LIS) { 960 // Don't track copies from physregs, there are too many uses. 961 if (any_of(LocIntervals, [](auto LocI) { 962 return !Register::isVirtualRegister(LocI.second->reg()); 963 })) 964 return; 965 966 // Collect all the (vreg, valno) pairs that are copies of LI. 967 SmallDenseMap<unsigned, 968 SmallVector<std::pair<LiveInterval *, const VNInfo *>, 4>> 969 CopyValues; 970 for (auto &LocInterval : LocIntervals) { 971 unsigned LocNo = LocInterval.first; 972 LiveInterval *LI = LocInterval.second; 973 for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg())) { 974 MachineInstr *MI = MO.getParent(); 975 // Copies of the full value. 976 if (MO.getSubReg() || !MI->isCopy()) 977 continue; 978 Register DstReg = MI->getOperand(0).getReg(); 979 980 // Don't follow copies to physregs. These are usually setting up call 981 // arguments, and the argument registers are always call clobbered. We are 982 // better off in the source register which could be a callee-saved 983 // register, or it could be spilled. 984 if (!Register::isVirtualRegister(DstReg)) 985 continue; 986 987 // Is the value extended to reach this copy? If not, another def may be 988 // blocking it, or we are looking at a wrong value of LI. 989 SlotIndex Idx = LIS.getInstructionIndex(*MI); 990 LocMap::iterator I = locInts.find(Idx.getRegSlot(true)); 991 if (!I.valid() || I.value() != DbgValue) 992 continue; 993 994 if (!LIS.hasInterval(DstReg)) 995 continue; 996 LiveInterval *DstLI = &LIS.getInterval(DstReg); 997 const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot()); 998 assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value"); 999 CopyValues[LocNo].push_back(std::make_pair(DstLI, DstVNI)); 1000 } 1001 } 1002 1003 if (CopyValues.empty()) 1004 return; 1005 1006 #if !defined(NDEBUG) 1007 for (auto &LocInterval : LocIntervals) 1008 LLVM_DEBUG(dbgs() << "Got " << CopyValues[LocInterval.first].size() 1009 << " copies of " << *LocInterval.second << '\n'); 1010 #endif 1011 1012 // Try to add defs of the copied values for the kill point. Check that there 1013 // isn't already a def at Idx. 1014 LocMap::iterator I = locInts.find(KilledAt); 1015 if (I.valid() && I.start() <= KilledAt) 1016 return; 1017 DbgVariableValue NewValue(DbgValue); 1018 for (auto &LocInterval : LocIntervals) { 1019 unsigned LocNo = LocInterval.first; 1020 bool FoundCopy = false; 1021 for (auto &LIAndVNI : CopyValues[LocNo]) { 1022 LiveInterval *DstLI = LIAndVNI.first; 1023 const VNInfo *DstVNI = LIAndVNI.second; 1024 if (DstLI->getVNInfoAt(KilledAt) != DstVNI) 1025 continue; 1026 LLVM_DEBUG(dbgs() << "Kill at " << KilledAt << " covered by valno #" 1027 << DstVNI->id << " in " << *DstLI << '\n'); 1028 MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def); 1029 assert(CopyMI && CopyMI->isCopy() && "Bad copy value"); 1030 unsigned NewLocNo = getLocationNo(CopyMI->getOperand(0)); 1031 NewValue = NewValue.changeLocNo(LocNo, NewLocNo); 1032 FoundCopy = true; 1033 break; 1034 } 1035 // If there are any killed locations we can't find a copy for, we can't 1036 // extend the variable value. 1037 if (!FoundCopy) 1038 return; 1039 } 1040 I.insert(KilledAt, KilledAt.getNextSlot(), NewValue); 1041 NewDefs.push_back(std::make_pair(KilledAt, NewValue)); 1042 } 1043 1044 void UserValue::computeIntervals(MachineRegisterInfo &MRI, 1045 const TargetRegisterInfo &TRI, 1046 LiveIntervals &LIS, LexicalScopes &LS) { 1047 SmallVector<std::pair<SlotIndex, DbgVariableValue>, 16> Defs; 1048 1049 // Collect all defs to be extended (Skipping undefs). 1050 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) 1051 if (!I.value().isUndef()) 1052 Defs.push_back(std::make_pair(I.start(), I.value())); 1053 1054 // Extend all defs, and possibly add new ones along the way. 1055 for (unsigned i = 0; i != Defs.size(); ++i) { 1056 SlotIndex Idx = Defs[i].first; 1057 DbgVariableValue DbgValue = Defs[i].second; 1058 SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>> LIs; 1059 SmallVector<const VNInfo *, 4> VNIs; 1060 bool ShouldExtendDef = false; 1061 for (unsigned LocNo : DbgValue.loc_nos()) { 1062 const MachineOperand &LocMO = locations[LocNo]; 1063 if (!LocMO.isReg() || !Register::isVirtualRegister(LocMO.getReg())) { 1064 ShouldExtendDef |= !LocMO.isReg(); 1065 continue; 1066 } 1067 ShouldExtendDef = true; 1068 LiveInterval *LI = nullptr; 1069 const VNInfo *VNI = nullptr; 1070 if (LIS.hasInterval(LocMO.getReg())) { 1071 LI = &LIS.getInterval(LocMO.getReg()); 1072 VNI = LI->getVNInfoAt(Idx); 1073 } 1074 if (LI && VNI) 1075 LIs[LocNo] = {LI, VNI}; 1076 } 1077 if (ShouldExtendDef) { 1078 Optional<std::pair<SlotIndex, SmallVector<unsigned>>> Kills; 1079 extendDef(Idx, DbgValue, LIs, Kills, LIS); 1080 1081 if (Kills) { 1082 SmallVector<std::pair<unsigned, LiveInterval *>, 2> KilledLocIntervals; 1083 bool AnySubreg = false; 1084 for (unsigned LocNo : Kills->second) { 1085 const MachineOperand &LocMO = this->locations[LocNo]; 1086 if (LocMO.getSubReg()) { 1087 AnySubreg = true; 1088 break; 1089 } 1090 LiveInterval *LI = &LIS.getInterval(LocMO.getReg()); 1091 KilledLocIntervals.push_back({LocNo, LI}); 1092 } 1093 1094 // FIXME: Handle sub-registers in addDefsFromCopies. The problem is that 1095 // if the original location for example is %vreg0:sub_hi, and we find a 1096 // full register copy in addDefsFromCopies (at the moment it only 1097 // handles full register copies), then we must add the sub1 sub-register 1098 // index to the new location. However, that is only possible if the new 1099 // virtual register is of the same regclass (or if there is an 1100 // equivalent sub-register in that regclass). For now, simply skip 1101 // handling copies if a sub-register is involved. 1102 if (!AnySubreg) 1103 addDefsFromCopies(DbgValue, KilledLocIntervals, Kills->first, Defs, 1104 MRI, LIS); 1105 } 1106 } 1107 1108 // For physregs, we only mark the start slot idx. DwarfDebug will see it 1109 // as if the DBG_VALUE is valid up until the end of the basic block, or 1110 // the next def of the physical register. So we do not need to extend the 1111 // range. It might actually happen that the DBG_VALUE is the last use of 1112 // the physical register (e.g. if this is an unused input argument to a 1113 // function). 1114 } 1115 1116 // The computed intervals may extend beyond the range of the debug 1117 // location's lexical scope. In this case, splitting of an interval 1118 // can result in an interval outside of the scope being created, 1119 // causing extra unnecessary DBG_VALUEs to be emitted. To prevent 1120 // this, trim the intervals to the lexical scope. 1121 1122 LexicalScope *Scope = LS.findLexicalScope(dl); 1123 if (!Scope) 1124 return; 1125 1126 SlotIndex PrevEnd; 1127 LocMap::iterator I = locInts.begin(); 1128 1129 // Iterate over the lexical scope ranges. Each time round the loop 1130 // we check the intervals for overlap with the end of the previous 1131 // range and the start of the next. The first range is handled as 1132 // a special case where there is no PrevEnd. 1133 for (const InsnRange &Range : Scope->getRanges()) { 1134 SlotIndex RStart = LIS.getInstructionIndex(*Range.first); 1135 SlotIndex REnd = LIS.getInstructionIndex(*Range.second); 1136 1137 // Variable locations at the first instruction of a block should be 1138 // based on the block's SlotIndex, not the first instruction's index. 1139 if (Range.first == Range.first->getParent()->begin()) 1140 RStart = LIS.getSlotIndexes()->getIndexBefore(*Range.first); 1141 1142 // At the start of each iteration I has been advanced so that 1143 // I.stop() >= PrevEnd. Check for overlap. 1144 if (PrevEnd && I.start() < PrevEnd) { 1145 SlotIndex IStop = I.stop(); 1146 DbgVariableValue DbgValue = I.value(); 1147 1148 // Stop overlaps previous end - trim the end of the interval to 1149 // the scope range. 1150 I.setStopUnchecked(PrevEnd); 1151 ++I; 1152 1153 // If the interval also overlaps the start of the "next" (i.e. 1154 // current) range create a new interval for the remainder (which 1155 // may be further trimmed). 1156 if (RStart < IStop) 1157 I.insert(RStart, IStop, DbgValue); 1158 } 1159 1160 // Advance I so that I.stop() >= RStart, and check for overlap. 1161 I.advanceTo(RStart); 1162 if (!I.valid()) 1163 return; 1164 1165 if (I.start() < RStart) { 1166 // Interval start overlaps range - trim to the scope range. 1167 I.setStartUnchecked(RStart); 1168 // Remember that this interval was trimmed. 1169 trimmedDefs.insert(RStart); 1170 } 1171 1172 // The end of a lexical scope range is the last instruction in the 1173 // range. To convert to an interval we need the index of the 1174 // instruction after it. 1175 REnd = REnd.getNextIndex(); 1176 1177 // Advance I to first interval outside current range. 1178 I.advanceTo(REnd); 1179 if (!I.valid()) 1180 return; 1181 1182 PrevEnd = REnd; 1183 } 1184 1185 // Check for overlap with end of final range. 1186 if (PrevEnd && I.start() < PrevEnd) 1187 I.setStopUnchecked(PrevEnd); 1188 } 1189 1190 void LDVImpl::computeIntervals() { 1191 LexicalScopes LS; 1192 LS.initialize(*MF); 1193 1194 for (unsigned i = 0, e = userValues.size(); i != e; ++i) { 1195 userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS); 1196 userValues[i]->mapVirtRegs(this); 1197 } 1198 } 1199 1200 bool LDVImpl::runOnMachineFunction(MachineFunction &mf) { 1201 clear(); 1202 MF = &mf; 1203 LIS = &pass.getAnalysis<LiveIntervals>(); 1204 TRI = mf.getSubtarget().getRegisterInfo(); 1205 LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: " 1206 << mf.getName() << " **********\n"); 1207 1208 bool Changed = collectDebugValues(mf); 1209 computeIntervals(); 1210 LLVM_DEBUG(print(dbgs())); 1211 ModifiedMF = Changed; 1212 return Changed; 1213 } 1214 1215 static void removeDebugInstrs(MachineFunction &mf) { 1216 for (MachineBasicBlock &MBB : mf) { 1217 for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) { 1218 if (!MBBI->isDebugInstr()) { 1219 ++MBBI; 1220 continue; 1221 } 1222 MBBI = MBB.erase(MBBI); 1223 } 1224 } 1225 } 1226 1227 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) { 1228 if (!EnableLDV) 1229 return false; 1230 if (!mf.getFunction().getSubprogram()) { 1231 removeDebugInstrs(mf); 1232 return false; 1233 } 1234 if (!pImpl) 1235 pImpl = new LDVImpl(this); 1236 return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf); 1237 } 1238 1239 void LiveDebugVariables::releaseMemory() { 1240 if (pImpl) 1241 static_cast<LDVImpl*>(pImpl)->clear(); 1242 } 1243 1244 LiveDebugVariables::~LiveDebugVariables() { 1245 if (pImpl) 1246 delete static_cast<LDVImpl*>(pImpl); 1247 } 1248 1249 //===----------------------------------------------------------------------===// 1250 // Live Range Splitting 1251 //===----------------------------------------------------------------------===// 1252 1253 bool 1254 UserValue::splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs, 1255 LiveIntervals& LIS) { 1256 LLVM_DEBUG({ 1257 dbgs() << "Splitting Loc" << OldLocNo << '\t'; 1258 print(dbgs(), nullptr); 1259 }); 1260 bool DidChange = false; 1261 LocMap::iterator LocMapI; 1262 LocMapI.setMap(locInts); 1263 for (unsigned i = 0; i != NewRegs.size(); ++i) { 1264 LiveInterval *LI = &LIS.getInterval(NewRegs[i]); 1265 if (LI->empty()) 1266 continue; 1267 1268 // Don't allocate the new LocNo until it is needed. 1269 unsigned NewLocNo = UndefLocNo; 1270 1271 // Iterate over the overlaps between locInts and LI. 1272 LocMapI.find(LI->beginIndex()); 1273 if (!LocMapI.valid()) 1274 continue; 1275 LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start()); 1276 LiveInterval::iterator LIE = LI->end(); 1277 while (LocMapI.valid() && LII != LIE) { 1278 // At this point, we know that LocMapI.stop() > LII->start. 1279 LII = LI->advanceTo(LII, LocMapI.start()); 1280 if (LII == LIE) 1281 break; 1282 1283 // Now LII->end > LocMapI.start(). Do we have an overlap? 1284 if (LocMapI.value().containsLocNo(OldLocNo) && 1285 LII->start < LocMapI.stop()) { 1286 // Overlapping correct location. Allocate NewLocNo now. 1287 if (NewLocNo == UndefLocNo) { 1288 MachineOperand MO = MachineOperand::CreateReg(LI->reg(), false); 1289 MO.setSubReg(locations[OldLocNo].getSubReg()); 1290 NewLocNo = getLocationNo(MO); 1291 DidChange = true; 1292 } 1293 1294 SlotIndex LStart = LocMapI.start(); 1295 SlotIndex LStop = LocMapI.stop(); 1296 DbgVariableValue OldDbgValue = LocMapI.value(); 1297 1298 // Trim LocMapI down to the LII overlap. 1299 if (LStart < LII->start) 1300 LocMapI.setStartUnchecked(LII->start); 1301 if (LStop > LII->end) 1302 LocMapI.setStopUnchecked(LII->end); 1303 1304 // Change the value in the overlap. This may trigger coalescing. 1305 LocMapI.setValue(OldDbgValue.changeLocNo(OldLocNo, NewLocNo)); 1306 1307 // Re-insert any removed OldDbgValue ranges. 1308 if (LStart < LocMapI.start()) { 1309 LocMapI.insert(LStart, LocMapI.start(), OldDbgValue); 1310 ++LocMapI; 1311 assert(LocMapI.valid() && "Unexpected coalescing"); 1312 } 1313 if (LStop > LocMapI.stop()) { 1314 ++LocMapI; 1315 LocMapI.insert(LII->end, LStop, OldDbgValue); 1316 --LocMapI; 1317 } 1318 } 1319 1320 // Advance to the next overlap. 1321 if (LII->end < LocMapI.stop()) { 1322 if (++LII == LIE) 1323 break; 1324 LocMapI.advanceTo(LII->start); 1325 } else { 1326 ++LocMapI; 1327 if (!LocMapI.valid()) 1328 break; 1329 LII = LI->advanceTo(LII, LocMapI.start()); 1330 } 1331 } 1332 } 1333 1334 // Finally, remove OldLocNo unless it is still used by some interval in the 1335 // locInts map. One case when OldLocNo still is in use is when the register 1336 // has been spilled. In such situations the spilled register is kept as a 1337 // location until rewriteLocations is called (VirtRegMap is mapping the old 1338 // register to the spill slot). So for a while we can have locations that map 1339 // to virtual registers that have been removed from both the MachineFunction 1340 // and from LiveIntervals. 1341 // 1342 // We may also just be using the location for a value with a different 1343 // expression. 1344 removeLocationIfUnused(OldLocNo); 1345 1346 LLVM_DEBUG({ 1347 dbgs() << "Split result: \t"; 1348 print(dbgs(), nullptr); 1349 }); 1350 return DidChange; 1351 } 1352 1353 bool 1354 UserValue::splitRegister(Register OldReg, ArrayRef<Register> NewRegs, 1355 LiveIntervals &LIS) { 1356 bool DidChange = false; 1357 // Split locations referring to OldReg. Iterate backwards so splitLocation can 1358 // safely erase unused locations. 1359 for (unsigned i = locations.size(); i ; --i) { 1360 unsigned LocNo = i-1; 1361 const MachineOperand *Loc = &locations[LocNo]; 1362 if (!Loc->isReg() || Loc->getReg() != OldReg) 1363 continue; 1364 DidChange |= splitLocation(LocNo, NewRegs, LIS); 1365 } 1366 return DidChange; 1367 } 1368 1369 void LDVImpl::splitRegister(Register OldReg, ArrayRef<Register> NewRegs) { 1370 bool DidChange = false; 1371 for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext()) 1372 DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS); 1373 1374 if (!DidChange) 1375 return; 1376 1377 // Map all of the new virtual registers. 1378 UserValue *UV = lookupVirtReg(OldReg); 1379 for (unsigned i = 0; i != NewRegs.size(); ++i) 1380 mapVirtReg(NewRegs[i], UV); 1381 } 1382 1383 void LiveDebugVariables:: 1384 splitRegister(Register OldReg, ArrayRef<Register> NewRegs, LiveIntervals &LIS) { 1385 if (pImpl) 1386 static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs); 1387 } 1388 1389 void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF, 1390 const TargetInstrInfo &TII, 1391 const TargetRegisterInfo &TRI, 1392 SpillOffsetMap &SpillOffsets) { 1393 // Build a set of new locations with new numbers so we can coalesce our 1394 // IntervalMap if two vreg intervals collapse to the same physical location. 1395 // Use MapVector instead of SetVector because MapVector::insert returns the 1396 // position of the previously or newly inserted element. The boolean value 1397 // tracks if the location was produced by a spill. 1398 // FIXME: This will be problematic if we ever support direct and indirect 1399 // frame index locations, i.e. expressing both variables in memory and 1400 // 'int x, *px = &x'. The "spilled" bit must become part of the location. 1401 MapVector<MachineOperand, std::pair<bool, unsigned>> NewLocations; 1402 SmallVector<unsigned, 4> LocNoMap(locations.size()); 1403 for (unsigned I = 0, E = locations.size(); I != E; ++I) { 1404 bool Spilled = false; 1405 unsigned SpillOffset = 0; 1406 MachineOperand Loc = locations[I]; 1407 // Only virtual registers are rewritten. 1408 if (Loc.isReg() && Loc.getReg() && 1409 Register::isVirtualRegister(Loc.getReg())) { 1410 Register VirtReg = Loc.getReg(); 1411 if (VRM.isAssignedReg(VirtReg) && 1412 Register::isPhysicalRegister(VRM.getPhys(VirtReg))) { 1413 // This can create a %noreg operand in rare cases when the sub-register 1414 // index is no longer available. That means the user value is in a 1415 // non-existent sub-register, and %noreg is exactly what we want. 1416 Loc.substPhysReg(VRM.getPhys(VirtReg), TRI); 1417 } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) { 1418 // Retrieve the stack slot offset. 1419 unsigned SpillSize; 1420 const MachineRegisterInfo &MRI = MF.getRegInfo(); 1421 const TargetRegisterClass *TRC = MRI.getRegClass(VirtReg); 1422 bool Success = TII.getStackSlotRange(TRC, Loc.getSubReg(), SpillSize, 1423 SpillOffset, MF); 1424 1425 // FIXME: Invalidate the location if the offset couldn't be calculated. 1426 (void)Success; 1427 1428 Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg)); 1429 Spilled = true; 1430 } else { 1431 Loc.setReg(0); 1432 Loc.setSubReg(0); 1433 } 1434 } 1435 1436 // Insert this location if it doesn't already exist and record a mapping 1437 // from the old number to the new number. 1438 auto InsertResult = NewLocations.insert({Loc, {Spilled, SpillOffset}}); 1439 unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first); 1440 LocNoMap[I] = NewLocNo; 1441 } 1442 1443 // Rewrite the locations and record the stack slot offsets for spills. 1444 locations.clear(); 1445 SpillOffsets.clear(); 1446 for (auto &Pair : NewLocations) { 1447 bool Spilled; 1448 unsigned SpillOffset; 1449 std::tie(Spilled, SpillOffset) = Pair.second; 1450 locations.push_back(Pair.first); 1451 if (Spilled) { 1452 unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair); 1453 SpillOffsets[NewLocNo] = SpillOffset; 1454 } 1455 } 1456 1457 // Update the interval map, but only coalesce left, since intervals to the 1458 // right use the old location numbers. This should merge two contiguous 1459 // DBG_VALUE intervals with different vregs that were allocated to the same 1460 // physical register. 1461 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) { 1462 I.setValueUnchecked(I.value().remapLocNos(LocNoMap)); 1463 I.setStart(I.start()); 1464 } 1465 } 1466 1467 /// Find an iterator for inserting a DBG_VALUE instruction. 1468 static MachineBasicBlock::iterator 1469 findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx, LiveIntervals &LIS, 1470 BlockSkipInstsMap &BBSkipInstsMap) { 1471 SlotIndex Start = LIS.getMBBStartIdx(MBB); 1472 Idx = Idx.getBaseIndex(); 1473 1474 // Try to find an insert location by going backwards from Idx. 1475 MachineInstr *MI; 1476 while (!(MI = LIS.getInstructionFromIndex(Idx))) { 1477 // We've reached the beginning of MBB. 1478 if (Idx == Start) { 1479 // Retrieve the last PHI/Label/Debug location found when calling 1480 // SkipPHIsLabelsAndDebug last time. Start searching from there. 1481 // 1482 // Note the iterator kept in BBSkipInstsMap is one step back based 1483 // on the iterator returned by SkipPHIsLabelsAndDebug last time. 1484 // One exception is when SkipPHIsLabelsAndDebug returns MBB->begin(), 1485 // BBSkipInstsMap won't save it. This is to consider the case that 1486 // new instructions may be inserted at the beginning of MBB after 1487 // last call of SkipPHIsLabelsAndDebug. If we save MBB->begin() in 1488 // BBSkipInstsMap, after new non-phi/non-label/non-debug instructions 1489 // are inserted at the beginning of the MBB, the iterator in 1490 // BBSkipInstsMap won't point to the beginning of the MBB anymore. 1491 // Therefore The next search in SkipPHIsLabelsAndDebug will skip those 1492 // newly added instructions and that is unwanted. 1493 MachineBasicBlock::iterator BeginIt; 1494 auto MapIt = BBSkipInstsMap.find(MBB); 1495 if (MapIt == BBSkipInstsMap.end()) 1496 BeginIt = MBB->begin(); 1497 else 1498 BeginIt = std::next(MapIt->second); 1499 auto I = MBB->SkipPHIsLabelsAndDebug(BeginIt); 1500 if (I != BeginIt) 1501 BBSkipInstsMap[MBB] = std::prev(I); 1502 return I; 1503 } 1504 Idx = Idx.getPrevIndex(); 1505 } 1506 1507 // Don't insert anything after the first terminator, though. 1508 return MI->isTerminator() ? MBB->getFirstTerminator() : 1509 std::next(MachineBasicBlock::iterator(MI)); 1510 } 1511 1512 /// Find an iterator for inserting the next DBG_VALUE instruction 1513 /// (or end if no more insert locations found). 1514 static MachineBasicBlock::iterator 1515 findNextInsertLocation(MachineBasicBlock *MBB, MachineBasicBlock::iterator I, 1516 SlotIndex StopIdx, ArrayRef<MachineOperand> LocMOs, 1517 LiveIntervals &LIS, const TargetRegisterInfo &TRI) { 1518 SmallVector<Register, 4> Regs; 1519 for (const MachineOperand &LocMO : LocMOs) 1520 if (LocMO.isReg()) 1521 Regs.push_back(LocMO.getReg()); 1522 if (Regs.empty()) 1523 return MBB->instr_end(); 1524 1525 // Find the next instruction in the MBB that define the register Reg. 1526 while (I != MBB->end() && !I->isTerminator()) { 1527 if (!LIS.isNotInMIMap(*I) && 1528 SlotIndex::isEarlierEqualInstr(StopIdx, LIS.getInstructionIndex(*I))) 1529 break; 1530 if (any_of(Regs, [&I, &TRI](Register &Reg) { 1531 return I->definesRegister(Reg, &TRI); 1532 })) 1533 // The insert location is directly after the instruction/bundle. 1534 return std::next(I); 1535 ++I; 1536 } 1537 return MBB->end(); 1538 } 1539 1540 void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx, 1541 SlotIndex StopIdx, DbgVariableValue DbgValue, 1542 ArrayRef<bool> LocSpills, 1543 ArrayRef<unsigned> SpillOffsets, 1544 LiveIntervals &LIS, const TargetInstrInfo &TII, 1545 const TargetRegisterInfo &TRI, 1546 BlockSkipInstsMap &BBSkipInstsMap) { 1547 SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB); 1548 // Only search within the current MBB. 1549 StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx; 1550 MachineBasicBlock::iterator I = 1551 findInsertLocation(MBB, StartIdx, LIS, BBSkipInstsMap); 1552 // Undef values don't exist in locations so create new "noreg" register MOs 1553 // for them. See getLocationNo(). 1554 SmallVector<MachineOperand, 8> MOs; 1555 if (DbgValue.isUndef()) { 1556 MOs.assign(DbgValue.loc_nos().size(), 1557 MachineOperand::CreateReg( 1558 /* Reg */ 0, /* isDef */ false, /* isImp */ false, 1559 /* isKill */ false, /* isDead */ false, 1560 /* isUndef */ false, /* isEarlyClobber */ false, 1561 /* SubReg */ 0, /* isDebug */ true)); 1562 } else { 1563 for (unsigned LocNo : DbgValue.loc_nos()) 1564 MOs.push_back(locations[LocNo]); 1565 } 1566 1567 ++NumInsertedDebugValues; 1568 1569 assert(cast<DILocalVariable>(Variable) 1570 ->isValidLocationForIntrinsic(getDebugLoc()) && 1571 "Expected inlined-at fields to agree"); 1572 1573 // If the location was spilled, the new DBG_VALUE will be indirect. If the 1574 // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate 1575 // that the original virtual register was a pointer. Also, add the stack slot 1576 // offset for the spilled register to the expression. 1577 const DIExpression *Expr = DbgValue.getExpression(); 1578 bool IsIndirect = DbgValue.getWasIndirect(); 1579 bool IsList = DbgValue.getWasList(); 1580 for (unsigned I = 0, E = LocSpills.size(); I != E; ++I) { 1581 if (LocSpills[I]) { 1582 if (!IsList) { 1583 uint8_t DIExprFlags = DIExpression::ApplyOffset; 1584 if (IsIndirect) 1585 DIExprFlags |= DIExpression::DerefAfter; 1586 Expr = DIExpression::prepend(Expr, DIExprFlags, SpillOffsets[I]); 1587 IsIndirect = true; 1588 } else { 1589 SmallVector<uint64_t, 4> Ops; 1590 DIExpression::appendOffset(Ops, SpillOffsets[I]); 1591 Ops.push_back(dwarf::DW_OP_deref); 1592 Expr = DIExpression::appendOpsToArg(Expr, Ops, I); 1593 } 1594 } 1595 1596 assert((!LocSpills[I] || MOs[I].isFI()) && 1597 "a spilled location must be a frame index"); 1598 } 1599 1600 unsigned DbgValueOpcode = 1601 IsList ? TargetOpcode::DBG_VALUE_LIST : TargetOpcode::DBG_VALUE; 1602 do { 1603 BuildMI(*MBB, I, getDebugLoc(), TII.get(DbgValueOpcode), IsIndirect, MOs, 1604 Variable, Expr); 1605 1606 // Continue and insert DBG_VALUES after every redefinition of a register 1607 // associated with the debug value within the range 1608 I = findNextInsertLocation(MBB, I, StopIdx, MOs, LIS, TRI); 1609 } while (I != MBB->end()); 1610 } 1611 1612 void UserLabel::insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx, 1613 LiveIntervals &LIS, const TargetInstrInfo &TII, 1614 BlockSkipInstsMap &BBSkipInstsMap) { 1615 MachineBasicBlock::iterator I = 1616 findInsertLocation(MBB, Idx, LIS, BBSkipInstsMap); 1617 ++NumInsertedDebugLabels; 1618 BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_LABEL)) 1619 .addMetadata(Label); 1620 } 1621 1622 void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS, 1623 const TargetInstrInfo &TII, 1624 const TargetRegisterInfo &TRI, 1625 const SpillOffsetMap &SpillOffsets, 1626 BlockSkipInstsMap &BBSkipInstsMap) { 1627 MachineFunction::iterator MFEnd = VRM->getMachineFunction().end(); 1628 1629 for (LocMap::const_iterator I = locInts.begin(); I.valid();) { 1630 SlotIndex Start = I.start(); 1631 SlotIndex Stop = I.stop(); 1632 DbgVariableValue DbgValue = I.value(); 1633 1634 SmallVector<bool> SpilledLocs; 1635 SmallVector<unsigned> LocSpillOffsets; 1636 for (unsigned LocNo : DbgValue.loc_nos()) { 1637 auto SpillIt = 1638 !DbgValue.isUndef() ? SpillOffsets.find(LocNo) : SpillOffsets.end(); 1639 bool Spilled = SpillIt != SpillOffsets.end(); 1640 SpilledLocs.push_back(Spilled); 1641 LocSpillOffsets.push_back(Spilled ? SpillIt->second : 0); 1642 } 1643 1644 // If the interval start was trimmed to the lexical scope insert the 1645 // DBG_VALUE at the previous index (otherwise it appears after the 1646 // first instruction in the range). 1647 if (trimmedDefs.count(Start)) 1648 Start = Start.getPrevIndex(); 1649 1650 LLVM_DEBUG(auto &dbg = dbgs(); dbg << "\t[" << Start << ';' << Stop << "):"; 1651 DbgValue.printLocNos(dbg)); 1652 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator(); 1653 SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB); 1654 1655 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd); 1656 insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs, LocSpillOffsets, 1657 LIS, TII, TRI, BBSkipInstsMap); 1658 // This interval may span multiple basic blocks. 1659 // Insert a DBG_VALUE into each one. 1660 while (Stop > MBBEnd) { 1661 // Move to the next block. 1662 Start = MBBEnd; 1663 if (++MBB == MFEnd) 1664 break; 1665 MBBEnd = LIS.getMBBEndIdx(&*MBB); 1666 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd); 1667 insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs, 1668 LocSpillOffsets, LIS, TII, TRI, BBSkipInstsMap); 1669 } 1670 LLVM_DEBUG(dbgs() << '\n'); 1671 if (MBB == MFEnd) 1672 break; 1673 1674 ++I; 1675 } 1676 } 1677 1678 void UserLabel::emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII, 1679 BlockSkipInstsMap &BBSkipInstsMap) { 1680 LLVM_DEBUG(dbgs() << "\t" << loc); 1681 MachineFunction::iterator MBB = LIS.getMBBFromIndex(loc)->getIterator(); 1682 1683 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB)); 1684 insertDebugLabel(&*MBB, loc, LIS, TII, BBSkipInstsMap); 1685 1686 LLVM_DEBUG(dbgs() << '\n'); 1687 } 1688 1689 void LDVImpl::emitDebugValues(VirtRegMap *VRM) { 1690 LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n"); 1691 if (!MF) 1692 return; 1693 1694 BlockSkipInstsMap BBSkipInstsMap; 1695 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 1696 SpillOffsetMap SpillOffsets; 1697 for (auto &userValue : userValues) { 1698 LLVM_DEBUG(userValue->print(dbgs(), TRI)); 1699 userValue->rewriteLocations(*VRM, *MF, *TII, *TRI, SpillOffsets); 1700 userValue->emitDebugValues(VRM, *LIS, *TII, *TRI, SpillOffsets, 1701 BBSkipInstsMap); 1702 } 1703 LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG LABELS **********\n"); 1704 for (auto &userLabel : userLabels) { 1705 LLVM_DEBUG(userLabel->print(dbgs(), TRI)); 1706 userLabel->emitDebugLabel(*LIS, *TII, BBSkipInstsMap); 1707 } 1708 1709 LLVM_DEBUG(dbgs() << "********** EMITTING INSTR REFERENCES **********\n"); 1710 1711 // Re-insert any DBG_INSTR_REFs back in the position they were. Ordering 1712 // is preserved by vector. 1713 auto Slots = LIS->getSlotIndexes(); 1714 const MCInstrDesc &RefII = TII->get(TargetOpcode::DBG_INSTR_REF); 1715 for (auto &P : StashedInstrReferences) { 1716 const SlotIndex &Idx = P.first; 1717 auto *MBB = Slots->getMBBFromIndex(Idx); 1718 MachineBasicBlock::iterator insertPos = 1719 findInsertLocation(MBB, Idx, *LIS, BBSkipInstsMap); 1720 for (auto &Stashed : P.second) { 1721 auto MIB = BuildMI(*MF, std::get<4>(Stashed), RefII); 1722 MIB.addImm(std::get<0>(Stashed)); 1723 MIB.addImm(std::get<1>(Stashed)); 1724 MIB.addMetadata(std::get<2>(Stashed)); 1725 MIB.addMetadata(std::get<3>(Stashed)); 1726 MachineInstr *New = MIB; 1727 MBB->insert(insertPos, New); 1728 } 1729 } 1730 1731 EmitDone = true; 1732 BBSkipInstsMap.clear(); 1733 } 1734 1735 void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) { 1736 if (pImpl) 1737 static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM); 1738 } 1739 1740 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1741 LLVM_DUMP_METHOD void LiveDebugVariables::dump() const { 1742 if (pImpl) 1743 static_cast<LDVImpl*>(pImpl)->print(dbgs()); 1744 } 1745 #endif 1746