1 //===- LiveDebugVariables.cpp - Tracking debug info variables -------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the LiveDebugVariables analysis. 11 // 12 // Remove all DBG_VALUE instructions referencing virtual registers and replace 13 // them with a data structure tracking where live user variables are kept - in a 14 // virtual register or in a stack slot. 15 // 16 // Allow the data structure to be updated during register allocation when values 17 // are moved between registers and stack slots. Finally emit new DBG_VALUE 18 // instructions after register allocation is complete. 19 // 20 //===----------------------------------------------------------------------===// 21 22 #include "LiveDebugVariables.h" 23 #include "llvm/ADT/ArrayRef.h" 24 #include "llvm/ADT/DenseMap.h" 25 #include "llvm/ADT/IntervalMap.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/MC/MCRegisterInfo.h" 53 #include "llvm/Pass.h" 54 #include "llvm/Support/Casting.h" 55 #include "llvm/Support/CommandLine.h" 56 #include "llvm/Support/Compiler.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 /// Describes a location by number along with some flags about the original 99 /// usage of the location. 100 class DbgValueLocation { 101 public: 102 DbgValueLocation(unsigned LocNo, bool WasIndirect) 103 : LocNo(LocNo), WasIndirect(WasIndirect) { 104 static_assert(sizeof(*this) == sizeof(unsigned), "bad bitfield packing"); 105 assert(locNo() == LocNo && "location truncation"); 106 } 107 108 DbgValueLocation() : LocNo(0), WasIndirect(0) {} 109 110 unsigned locNo() const { 111 // Fix up the undef location number, which gets truncated. 112 return LocNo == INT_MAX ? UndefLocNo : LocNo; 113 } 114 bool wasIndirect() const { return WasIndirect; } 115 bool isUndef() const { return locNo() == UndefLocNo; } 116 117 DbgValueLocation changeLocNo(unsigned NewLocNo) const { 118 return DbgValueLocation(NewLocNo, WasIndirect); 119 } 120 121 friend inline bool operator==(const DbgValueLocation &LHS, 122 const DbgValueLocation &RHS) { 123 return LHS.LocNo == RHS.LocNo && LHS.WasIndirect == RHS.WasIndirect; 124 } 125 126 friend inline bool operator!=(const DbgValueLocation &LHS, 127 const DbgValueLocation &RHS) { 128 return !(LHS == RHS); 129 } 130 131 private: 132 unsigned LocNo : 31; 133 unsigned WasIndirect : 1; 134 }; 135 136 /// Map of where a user value is live, and its location. 137 using LocMap = IntervalMap<SlotIndex, DbgValueLocation, 4>; 138 139 /// Map of stack slot offsets for spilled locations. 140 /// Non-spilled locations are not added to the map. 141 using SpillOffsetMap = DenseMap<unsigned, unsigned>; 142 143 namespace { 144 145 class LDVImpl; 146 147 /// A user value is a part of a debug info user variable. 148 /// 149 /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register 150 /// holds part of a user variable. The part is identified by a byte offset. 151 /// 152 /// UserValues are grouped into equivalence classes for easier searching. Two 153 /// user values are related if they refer to the same variable, or if they are 154 /// held by the same virtual register. The equivalence class is the transitive 155 /// closure of that relation. 156 class UserValue { 157 const DILocalVariable *Variable; ///< The debug info variable we are part of. 158 const DIExpression *Expression; ///< Any complex address expression. 159 DebugLoc dl; ///< The debug location for the variable. This is 160 ///< used by dwarf writer to find lexical scope. 161 UserValue *leader; ///< Equivalence class leader. 162 UserValue *next = nullptr; ///< Next value in equivalence class, or null. 163 164 /// Numbered locations referenced by locmap. 165 SmallVector<MachineOperand, 4> locations; 166 167 /// Map of slot indices where this value is live. 168 LocMap locInts; 169 170 /// Set of interval start indexes that have been trimmed to the 171 /// lexical scope. 172 SmallSet<SlotIndex, 2> trimmedDefs; 173 174 /// Insert a DBG_VALUE into MBB at Idx for LocNo. 175 void insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx, 176 SlotIndex StopIdx, DbgValueLocation Loc, bool Spilled, 177 unsigned SpillOffset, LiveIntervals &LIS, 178 const TargetInstrInfo &TII, 179 const TargetRegisterInfo &TRI); 180 181 /// Replace OldLocNo ranges with NewRegs ranges where NewRegs 182 /// is live. Returns true if any changes were made. 183 bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs, 184 LiveIntervals &LIS); 185 186 public: 187 /// Create a new UserValue. 188 UserValue(const DILocalVariable *var, const DIExpression *expr, DebugLoc L, 189 LocMap::Allocator &alloc) 190 : Variable(var), Expression(expr), dl(std::move(L)), leader(this), 191 locInts(alloc) {} 192 193 /// Get the leader of this value's equivalence class. 194 UserValue *getLeader() { 195 UserValue *l = leader; 196 while (l != l->leader) 197 l = l->leader; 198 return leader = l; 199 } 200 201 /// Return the next UserValue in the equivalence class. 202 UserValue *getNext() const { return next; } 203 204 /// Does this UserValue match the parameters? 205 bool match(const DILocalVariable *Var, const DIExpression *Expr, 206 const DILocation *IA) const { 207 // FIXME: The fragment should be part of the equivalence class, but not 208 // other things in the expression like stack values. 209 return Var == Variable && Expr == Expression && dl->getInlinedAt() == IA; 210 } 211 212 /// Merge equivalence classes. 213 static UserValue *merge(UserValue *L1, UserValue *L2) { 214 L2 = L2->getLeader(); 215 if (!L1) 216 return L2; 217 L1 = L1->getLeader(); 218 if (L1 == L2) 219 return L1; 220 // Splice L2 before L1's members. 221 UserValue *End = L2; 222 while (End->next) { 223 End->leader = L1; 224 End = End->next; 225 } 226 End->leader = L1; 227 End->next = L1->next; 228 L1->next = L2; 229 return L1; 230 } 231 232 /// Return the location number that matches Loc. 233 /// 234 /// For undef values we always return location number UndefLocNo without 235 /// inserting anything in locations. Since locations is a vector and the 236 /// location number is the position in the vector and UndefLocNo is ~0, 237 /// we would need a very big vector to put the value at the right position. 238 unsigned getLocationNo(const MachineOperand &LocMO) { 239 if (LocMO.isReg()) { 240 if (LocMO.getReg() == 0) 241 return UndefLocNo; 242 // For register locations we dont care about use/def and other flags. 243 for (unsigned i = 0, e = locations.size(); i != e; ++i) 244 if (locations[i].isReg() && 245 locations[i].getReg() == LocMO.getReg() && 246 locations[i].getSubReg() == LocMO.getSubReg()) 247 return i; 248 } else 249 for (unsigned i = 0, e = locations.size(); i != e; ++i) 250 if (LocMO.isIdenticalTo(locations[i])) 251 return i; 252 locations.push_back(LocMO); 253 // We are storing a MachineOperand outside a MachineInstr. 254 locations.back().clearParent(); 255 // Don't store def operands. 256 if (locations.back().isReg()) { 257 if (locations.back().isDef()) 258 locations.back().setIsDead(false); 259 locations.back().setIsUse(); 260 } 261 return locations.size() - 1; 262 } 263 264 /// Ensure that all virtual register locations are mapped. 265 void mapVirtRegs(LDVImpl *LDV); 266 267 /// Add a definition point to this value. 268 void addDef(SlotIndex Idx, const MachineOperand &LocMO, bool IsIndirect) { 269 DbgValueLocation Loc(getLocationNo(LocMO), IsIndirect); 270 // Add a singular (Idx,Idx) -> Loc mapping. 271 LocMap::iterator I = locInts.find(Idx); 272 if (!I.valid() || I.start() != Idx) 273 I.insert(Idx, Idx.getNextSlot(), Loc); 274 else 275 // A later DBG_VALUE at the same SlotIndex overrides the old location. 276 I.setValue(Loc); 277 } 278 279 /// Extend the current definition as far as possible down. 280 /// 281 /// Stop when meeting an existing def or when leaving the live 282 /// range of VNI. End points where VNI is no longer live are added to Kills. 283 /// 284 /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a 285 /// data-flow analysis to propagate them beyond basic block boundaries. 286 /// 287 /// \param Idx Starting point for the definition. 288 /// \param Loc Location number to propagate. 289 /// \param LR Restrict liveness to where LR has the value VNI. May be null. 290 /// \param VNI When LR is not null, this is the value to restrict to. 291 /// \param [out] Kills Append end points of VNI's live range to Kills. 292 /// \param LIS Live intervals analysis. 293 void extendDef(SlotIndex Idx, DbgValueLocation Loc, 294 LiveRange *LR, const VNInfo *VNI, 295 SmallVectorImpl<SlotIndex> *Kills, 296 LiveIntervals &LIS); 297 298 /// The value in LI/LocNo may be copies to other registers. Determine if 299 /// any of the copies are available at the kill points, and add defs if 300 /// possible. 301 /// 302 /// \param LI Scan for copies of the value in LI->reg. 303 /// \param LocNo Location number of LI->reg. 304 /// \param WasIndirect Indicates if the original use of LI->reg was indirect 305 /// \param Kills Points where the range of LocNo could be extended. 306 /// \param [in,out] NewDefs Append (Idx, LocNo) of inserted defs here. 307 void addDefsFromCopies( 308 LiveInterval *LI, unsigned LocNo, bool WasIndirect, 309 const SmallVectorImpl<SlotIndex> &Kills, 310 SmallVectorImpl<std::pair<SlotIndex, DbgValueLocation>> &NewDefs, 311 MachineRegisterInfo &MRI, LiveIntervals &LIS); 312 313 /// Compute the live intervals of all locations after collecting all their 314 /// def points. 315 void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, 316 LiveIntervals &LIS, LexicalScopes &LS); 317 318 /// Replace OldReg ranges with NewRegs ranges where NewRegs is 319 /// live. Returns true if any changes were made. 320 bool splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, 321 LiveIntervals &LIS); 322 323 /// Rewrite virtual register locations according to the provided virtual 324 /// register map. Record the stack slot offsets for the locations that 325 /// were spilled. 326 void rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF, 327 const TargetInstrInfo &TII, 328 const TargetRegisterInfo &TRI, 329 SpillOffsetMap &SpillOffsets); 330 331 /// Recreate DBG_VALUE instruction from data structures. 332 void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS, 333 const TargetInstrInfo &TII, 334 const TargetRegisterInfo &TRI, 335 const SpillOffsetMap &SpillOffsets); 336 337 /// Return DebugLoc of this UserValue. 338 DebugLoc getDebugLoc() { return dl;} 339 340 void print(raw_ostream &, const TargetRegisterInfo *); 341 }; 342 343 /// A user label is a part of a debug info user label. 344 class UserLabel { 345 const DILabel *Label; ///< The debug info label we are part of. 346 DebugLoc dl; ///< The debug location for the label. This is 347 ///< used by dwarf writer to find lexical scope. 348 SlotIndex loc; ///< Slot used by the debug label. 349 350 /// Insert a DBG_LABEL into MBB at Idx. 351 void insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx, 352 LiveIntervals &LIS, const TargetInstrInfo &TII); 353 354 public: 355 /// Create a new UserLabel. 356 UserLabel(const DILabel *label, DebugLoc L, SlotIndex Idx) 357 : Label(label), dl(std::move(L)), loc(Idx) {} 358 359 /// Does this UserLabel match the parameters? 360 bool match(const DILabel *L, const DILocation *IA, 361 const SlotIndex Index) const { 362 return Label == L && dl->getInlinedAt() == IA && loc == Index; 363 } 364 365 /// Recreate DBG_LABEL instruction from data structures. 366 void emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII); 367 368 /// Return DebugLoc of this UserLabel. 369 DebugLoc getDebugLoc() { return dl; } 370 371 void print(raw_ostream &, const TargetRegisterInfo *); 372 }; 373 374 /// Implementation of the LiveDebugVariables pass. 375 class LDVImpl { 376 LiveDebugVariables &pass; 377 LocMap::Allocator allocator; 378 MachineFunction *MF = nullptr; 379 LiveIntervals *LIS; 380 const TargetRegisterInfo *TRI; 381 382 /// Whether emitDebugValues is called. 383 bool EmitDone = false; 384 385 /// Whether the machine function is modified during the pass. 386 bool ModifiedMF = false; 387 388 /// All allocated UserValue instances. 389 SmallVector<std::unique_ptr<UserValue>, 8> userValues; 390 391 /// All allocated UserLabel instances. 392 SmallVector<std::unique_ptr<UserLabel>, 2> userLabels; 393 394 /// Map virtual register to eq class leader. 395 using VRMap = DenseMap<unsigned, UserValue *>; 396 VRMap virtRegToEqClass; 397 398 /// Map user variable to eq class leader. 399 using UVMap = DenseMap<const DILocalVariable *, UserValue *>; 400 UVMap userVarMap; 401 402 /// Find or create a UserValue. 403 UserValue *getUserValue(const DILocalVariable *Var, const DIExpression *Expr, 404 const DebugLoc &DL); 405 406 /// Find the EC leader for VirtReg or null. 407 UserValue *lookupVirtReg(unsigned VirtReg); 408 409 /// Add DBG_VALUE instruction to our maps. 410 /// 411 /// \param MI DBG_VALUE instruction 412 /// \param Idx Last valid SLotIndex before instruction. 413 /// 414 /// \returns True if the DBG_VALUE instruction should be deleted. 415 bool handleDebugValue(MachineInstr &MI, SlotIndex Idx); 416 417 /// Add DBG_LABEL instruction to UserLabel. 418 /// 419 /// \param MI DBG_LABEL instruction 420 /// \param Idx Last valid SlotIndex before instruction. 421 /// 422 /// \returns True if the DBG_LABEL instruction should be deleted. 423 bool handleDebugLabel(MachineInstr &MI, SlotIndex Idx); 424 425 /// Collect and erase all DBG_VALUE instructions, adding a UserValue def 426 /// for each instruction. 427 /// 428 /// \param mf MachineFunction to be scanned. 429 /// 430 /// \returns True if any debug values were found. 431 bool collectDebugValues(MachineFunction &mf); 432 433 /// Compute the live intervals of all user values after collecting all 434 /// their def points. 435 void computeIntervals(); 436 437 public: 438 LDVImpl(LiveDebugVariables *ps) : pass(*ps) {} 439 440 bool runOnMachineFunction(MachineFunction &mf); 441 442 /// Release all memory. 443 void clear() { 444 MF = nullptr; 445 userValues.clear(); 446 userLabels.clear(); 447 virtRegToEqClass.clear(); 448 userVarMap.clear(); 449 // Make sure we call emitDebugValues if the machine function was modified. 450 assert((!ModifiedMF || EmitDone) && 451 "Dbg values are not emitted in LDV"); 452 EmitDone = false; 453 ModifiedMF = false; 454 } 455 456 /// Map virtual register to an equivalence class. 457 void mapVirtReg(unsigned VirtReg, UserValue *EC); 458 459 /// Replace all references to OldReg with NewRegs. 460 void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs); 461 462 /// Recreate DBG_VALUE instruction from data structures. 463 void emitDebugValues(VirtRegMap *VRM); 464 465 void print(raw_ostream&); 466 }; 467 468 } // end anonymous namespace 469 470 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 471 static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS, 472 const LLVMContext &Ctx) { 473 if (!DL) 474 return; 475 476 auto *Scope = cast<DIScope>(DL.getScope()); 477 // Omit the directory, because it's likely to be long and uninteresting. 478 CommentOS << Scope->getFilename(); 479 CommentOS << ':' << DL.getLine(); 480 if (DL.getCol() != 0) 481 CommentOS << ':' << DL.getCol(); 482 483 DebugLoc InlinedAtDL = DL.getInlinedAt(); 484 if (!InlinedAtDL) 485 return; 486 487 CommentOS << " @[ "; 488 printDebugLoc(InlinedAtDL, CommentOS, Ctx); 489 CommentOS << " ]"; 490 } 491 492 static void printExtendedName(raw_ostream &OS, const DINode *Node, 493 const DILocation *DL) { 494 const LLVMContext &Ctx = Node->getContext(); 495 StringRef Res; 496 unsigned Line; 497 if (const auto *V = dyn_cast<const DILocalVariable>(Node)) { 498 Res = V->getName(); 499 Line = V->getLine(); 500 } else if (const auto *L = dyn_cast<const DILabel>(Node)) { 501 Res = L->getName(); 502 Line = L->getLine(); 503 } 504 505 if (!Res.empty()) 506 OS << Res << "," << Line; 507 if (auto *InlinedAt = DL->getInlinedAt()) { 508 if (DebugLoc InlinedAtDL = InlinedAt) { 509 OS << " @["; 510 printDebugLoc(InlinedAtDL, OS, Ctx); 511 OS << "]"; 512 } 513 } 514 } 515 516 void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) { 517 OS << "!\""; 518 printExtendedName(OS, Variable, dl); 519 520 OS << "\"\t"; 521 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) { 522 OS << " [" << I.start() << ';' << I.stop() << "):"; 523 if (I.value().isUndef()) 524 OS << "undef"; 525 else { 526 OS << I.value().locNo(); 527 if (I.value().wasIndirect()) 528 OS << " ind"; 529 } 530 } 531 for (unsigned i = 0, e = locations.size(); i != e; ++i) { 532 OS << " Loc" << i << '='; 533 locations[i].print(OS, TRI); 534 } 535 OS << '\n'; 536 } 537 538 void UserLabel::print(raw_ostream &OS, const TargetRegisterInfo *TRI) { 539 OS << "!\""; 540 printExtendedName(OS, Label, dl); 541 542 OS << "\"\t"; 543 OS << loc; 544 OS << '\n'; 545 } 546 547 void LDVImpl::print(raw_ostream &OS) { 548 OS << "********** DEBUG VARIABLES **********\n"; 549 for (auto &userValue : userValues) 550 userValue->print(OS, TRI); 551 OS << "********** DEBUG LABELS **********\n"; 552 for (auto &userLabel : userLabels) 553 userLabel->print(OS, TRI); 554 } 555 #endif 556 557 void UserValue::mapVirtRegs(LDVImpl *LDV) { 558 for (unsigned i = 0, e = locations.size(); i != e; ++i) 559 if (locations[i].isReg() && 560 TargetRegisterInfo::isVirtualRegister(locations[i].getReg())) 561 LDV->mapVirtReg(locations[i].getReg(), this); 562 } 563 564 UserValue *LDVImpl::getUserValue(const DILocalVariable *Var, 565 const DIExpression *Expr, const DebugLoc &DL) { 566 UserValue *&Leader = userVarMap[Var]; 567 if (Leader) { 568 UserValue *UV = Leader->getLeader(); 569 Leader = UV; 570 for (; UV; UV = UV->getNext()) 571 if (UV->match(Var, Expr, DL->getInlinedAt())) 572 return UV; 573 } 574 575 userValues.push_back( 576 llvm::make_unique<UserValue>(Var, Expr, DL, allocator)); 577 UserValue *UV = userValues.back().get(); 578 Leader = UserValue::merge(Leader, UV); 579 return UV; 580 } 581 582 void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) { 583 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs"); 584 UserValue *&Leader = virtRegToEqClass[VirtReg]; 585 Leader = UserValue::merge(Leader, EC); 586 } 587 588 UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) { 589 if (UserValue *UV = virtRegToEqClass.lookup(VirtReg)) 590 return UV->getLeader(); 591 return nullptr; 592 } 593 594 bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) { 595 // DBG_VALUE loc, offset, variable 596 if (MI.getNumOperands() != 4 || 597 !(MI.getOperand(1).isReg() || MI.getOperand(1).isImm()) || 598 !MI.getOperand(2).isMetadata()) { 599 LLVM_DEBUG(dbgs() << "Can't handle " << MI); 600 return false; 601 } 602 603 // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual 604 // register that hasn't been defined yet. If we do not remove those here, then 605 // the re-insertion of the DBG_VALUE instruction after register allocation 606 // will be incorrect. 607 // TODO: If earlier passes are corrected to generate sane debug information 608 // (and if the machine verifier is improved to catch this), then these checks 609 // could be removed or replaced by asserts. 610 bool Discard = false; 611 if (MI.getOperand(0).isReg() && 612 TargetRegisterInfo::isVirtualRegister(MI.getOperand(0).getReg())) { 613 const unsigned Reg = MI.getOperand(0).getReg(); 614 if (!LIS->hasInterval(Reg)) { 615 // The DBG_VALUE is described by a virtual register that does not have a 616 // live interval. Discard the DBG_VALUE. 617 Discard = true; 618 LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx 619 << " " << MI); 620 } else { 621 // The DBG_VALUE is only valid if either Reg is live out from Idx, or Reg 622 // is defined dead at Idx (where Idx is the slot index for the instruction 623 // preceeding the DBG_VALUE). 624 const LiveInterval &LI = LIS->getInterval(Reg); 625 LiveQueryResult LRQ = LI.Query(Idx); 626 if (!LRQ.valueOutOrDead()) { 627 // We have found a DBG_VALUE with the value in a virtual register that 628 // is not live. Discard the DBG_VALUE. 629 Discard = true; 630 LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx 631 << " " << MI); 632 } 633 } 634 } 635 636 // Get or create the UserValue for (variable,offset) here. 637 bool IsIndirect = MI.getOperand(1).isImm(); 638 if (IsIndirect) 639 assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset"); 640 const DILocalVariable *Var = MI.getDebugVariable(); 641 const DIExpression *Expr = MI.getDebugExpression(); 642 UserValue *UV = 643 getUserValue(Var, Expr, MI.getDebugLoc()); 644 if (!Discard) 645 UV->addDef(Idx, MI.getOperand(0), IsIndirect); 646 else { 647 MachineOperand MO = MachineOperand::CreateReg(0U, false); 648 MO.setIsDebug(); 649 UV->addDef(Idx, MO, false); 650 } 651 return true; 652 } 653 654 bool LDVImpl::handleDebugLabel(MachineInstr &MI, SlotIndex Idx) { 655 // DBG_LABEL label 656 if (MI.getNumOperands() != 1 || !MI.getOperand(0).isMetadata()) { 657 LLVM_DEBUG(dbgs() << "Can't handle " << MI); 658 return false; 659 } 660 661 // Get or create the UserLabel for label here. 662 const DILabel *Label = MI.getDebugLabel(); 663 const DebugLoc &DL = MI.getDebugLoc(); 664 bool Found = false; 665 for (auto const &L : userLabels) { 666 if (L->match(Label, DL->getInlinedAt(), Idx)) { 667 Found = true; 668 break; 669 } 670 } 671 if (!Found) 672 userLabels.push_back(llvm::make_unique<UserLabel>(Label, DL, Idx)); 673 674 return true; 675 } 676 677 bool LDVImpl::collectDebugValues(MachineFunction &mf) { 678 bool Changed = false; 679 for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE; 680 ++MFI) { 681 MachineBasicBlock *MBB = &*MFI; 682 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end(); 683 MBBI != MBBE;) { 684 // Use the first debug instruction in the sequence to get a SlotIndex 685 // for following consecutive debug instructions. 686 if (!MBBI->isDebugInstr()) { 687 ++MBBI; 688 continue; 689 } 690 // Debug instructions has no slot index. Use the previous 691 // non-debug instruction's SlotIndex as its SlotIndex. 692 SlotIndex Idx = 693 MBBI == MBB->begin() 694 ? LIS->getMBBStartIdx(MBB) 695 : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot(); 696 // Handle consecutive debug instructions with the same slot index. 697 do { 698 // Only handle DBG_VALUE in handleDebugValue(). Skip all other 699 // kinds of debug instructions. 700 if ((MBBI->isDebugValue() && handleDebugValue(*MBBI, Idx)) || 701 (MBBI->isDebugLabel() && handleDebugLabel(*MBBI, Idx))) { 702 MBBI = MBB->erase(MBBI); 703 Changed = true; 704 } else 705 ++MBBI; 706 } while (MBBI != MBBE && MBBI->isDebugInstr()); 707 } 708 } 709 return Changed; 710 } 711 712 void UserValue::extendDef(SlotIndex Idx, DbgValueLocation Loc, LiveRange *LR, 713 const VNInfo *VNI, SmallVectorImpl<SlotIndex> *Kills, 714 LiveIntervals &LIS) { 715 SlotIndex Start = Idx; 716 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start); 717 SlotIndex Stop = LIS.getMBBEndIdx(MBB); 718 LocMap::iterator I = locInts.find(Start); 719 720 // Limit to VNI's live range. 721 bool ToEnd = true; 722 if (LR && VNI) { 723 LiveInterval::Segment *Segment = LR->getSegmentContaining(Start); 724 if (!Segment || Segment->valno != VNI) { 725 if (Kills) 726 Kills->push_back(Start); 727 return; 728 } 729 if (Segment->end < Stop) { 730 Stop = Segment->end; 731 ToEnd = false; 732 } 733 } 734 735 // There could already be a short def at Start. 736 if (I.valid() && I.start() <= Start) { 737 // Stop when meeting a different location or an already extended interval. 738 Start = Start.getNextSlot(); 739 if (I.value() != Loc || I.stop() != Start) 740 return; 741 // This is a one-slot placeholder. Just skip it. 742 ++I; 743 } 744 745 // Limited by the next def. 746 if (I.valid() && I.start() < Stop) { 747 Stop = I.start(); 748 ToEnd = false; 749 } 750 // Limited by VNI's live range. 751 else if (!ToEnd && Kills) 752 Kills->push_back(Stop); 753 754 if (Start < Stop) 755 I.insert(Start, Stop, Loc); 756 } 757 758 void UserValue::addDefsFromCopies( 759 LiveInterval *LI, unsigned LocNo, bool WasIndirect, 760 const SmallVectorImpl<SlotIndex> &Kills, 761 SmallVectorImpl<std::pair<SlotIndex, DbgValueLocation>> &NewDefs, 762 MachineRegisterInfo &MRI, LiveIntervals &LIS) { 763 if (Kills.empty()) 764 return; 765 // Don't track copies from physregs, there are too many uses. 766 if (!TargetRegisterInfo::isVirtualRegister(LI->reg)) 767 return; 768 769 // Collect all the (vreg, valno) pairs that are copies of LI. 770 SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues; 771 for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) { 772 MachineInstr *MI = MO.getParent(); 773 // Copies of the full value. 774 if (MO.getSubReg() || !MI->isCopy()) 775 continue; 776 unsigned DstReg = MI->getOperand(0).getReg(); 777 778 // Don't follow copies to physregs. These are usually setting up call 779 // arguments, and the argument registers are always call clobbered. We are 780 // better off in the source register which could be a callee-saved register, 781 // or it could be spilled. 782 if (!TargetRegisterInfo::isVirtualRegister(DstReg)) 783 continue; 784 785 // Is LocNo extended to reach this copy? If not, another def may be blocking 786 // it, or we are looking at a wrong value of LI. 787 SlotIndex Idx = LIS.getInstructionIndex(*MI); 788 LocMap::iterator I = locInts.find(Idx.getRegSlot(true)); 789 if (!I.valid() || I.value().locNo() != LocNo) 790 continue; 791 792 if (!LIS.hasInterval(DstReg)) 793 continue; 794 LiveInterval *DstLI = &LIS.getInterval(DstReg); 795 const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot()); 796 assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value"); 797 CopyValues.push_back(std::make_pair(DstLI, DstVNI)); 798 } 799 800 if (CopyValues.empty()) 801 return; 802 803 LLVM_DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI 804 << '\n'); 805 806 // Try to add defs of the copied values for each kill point. 807 for (unsigned i = 0, e = Kills.size(); i != e; ++i) { 808 SlotIndex Idx = Kills[i]; 809 for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) { 810 LiveInterval *DstLI = CopyValues[j].first; 811 const VNInfo *DstVNI = CopyValues[j].second; 812 if (DstLI->getVNInfoAt(Idx) != DstVNI) 813 continue; 814 // Check that there isn't already a def at Idx 815 LocMap::iterator I = locInts.find(Idx); 816 if (I.valid() && I.start() <= Idx) 817 continue; 818 LLVM_DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #" 819 << DstVNI->id << " in " << *DstLI << '\n'); 820 MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def); 821 assert(CopyMI && CopyMI->isCopy() && "Bad copy value"); 822 unsigned LocNo = getLocationNo(CopyMI->getOperand(0)); 823 DbgValueLocation NewLoc(LocNo, WasIndirect); 824 I.insert(Idx, Idx.getNextSlot(), NewLoc); 825 NewDefs.push_back(std::make_pair(Idx, NewLoc)); 826 break; 827 } 828 } 829 } 830 831 void UserValue::computeIntervals(MachineRegisterInfo &MRI, 832 const TargetRegisterInfo &TRI, 833 LiveIntervals &LIS, LexicalScopes &LS) { 834 SmallVector<std::pair<SlotIndex, DbgValueLocation>, 16> Defs; 835 836 // Collect all defs to be extended (Skipping undefs). 837 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) 838 if (!I.value().isUndef()) 839 Defs.push_back(std::make_pair(I.start(), I.value())); 840 841 // Extend all defs, and possibly add new ones along the way. 842 for (unsigned i = 0; i != Defs.size(); ++i) { 843 SlotIndex Idx = Defs[i].first; 844 DbgValueLocation Loc = Defs[i].second; 845 const MachineOperand &LocMO = locations[Loc.locNo()]; 846 847 if (!LocMO.isReg()) { 848 extendDef(Idx, Loc, nullptr, nullptr, nullptr, LIS); 849 continue; 850 } 851 852 // Register locations are constrained to where the register value is live. 853 if (TargetRegisterInfo::isVirtualRegister(LocMO.getReg())) { 854 LiveInterval *LI = nullptr; 855 const VNInfo *VNI = nullptr; 856 if (LIS.hasInterval(LocMO.getReg())) { 857 LI = &LIS.getInterval(LocMO.getReg()); 858 VNI = LI->getVNInfoAt(Idx); 859 } 860 SmallVector<SlotIndex, 16> Kills; 861 extendDef(Idx, Loc, LI, VNI, &Kills, LIS); 862 // FIXME: Handle sub-registers in addDefsFromCopies. The problem is that 863 // if the original location for example is %vreg0:sub_hi, and we find a 864 // full register copy in addDefsFromCopies (at the moment it only handles 865 // full register copies), then we must add the sub1 sub-register index to 866 // the new location. However, that is only possible if the new virtual 867 // register is of the same regclass (or if there is an equivalent 868 // sub-register in that regclass). For now, simply skip handling copies if 869 // a sub-register is involved. 870 if (LI && !LocMO.getSubReg()) 871 addDefsFromCopies(LI, Loc.locNo(), Loc.wasIndirect(), Kills, Defs, MRI, 872 LIS); 873 continue; 874 } 875 876 // For physregs, we only mark the start slot idx. DwarfDebug will see it 877 // as if the DBG_VALUE is valid up until the end of the basic block, or 878 // the next def of the physical register. So we do not need to extend the 879 // range. It might actually happen that the DBG_VALUE is the last use of 880 // the physical register (e.g. if this is an unused input argument to a 881 // function). 882 } 883 884 // The computed intervals may extend beyond the range of the debug 885 // location's lexical scope. In this case, splitting of an interval 886 // can result in an interval outside of the scope being created, 887 // causing extra unnecessary DBG_VALUEs to be emitted. To prevent 888 // this, trim the intervals to the lexical scope. 889 890 LexicalScope *Scope = LS.findLexicalScope(dl); 891 if (!Scope) 892 return; 893 894 SlotIndex PrevEnd; 895 LocMap::iterator I = locInts.begin(); 896 897 // Iterate over the lexical scope ranges. Each time round the loop 898 // we check the intervals for overlap with the end of the previous 899 // range and the start of the next. The first range is handled as 900 // a special case where there is no PrevEnd. 901 for (const InsnRange &Range : Scope->getRanges()) { 902 SlotIndex RStart = LIS.getInstructionIndex(*Range.first); 903 SlotIndex REnd = LIS.getInstructionIndex(*Range.second); 904 905 // At the start of each iteration I has been advanced so that 906 // I.stop() >= PrevEnd. Check for overlap. 907 if (PrevEnd && I.start() < PrevEnd) { 908 SlotIndex IStop = I.stop(); 909 DbgValueLocation Loc = I.value(); 910 911 // Stop overlaps previous end - trim the end of the interval to 912 // the scope range. 913 I.setStopUnchecked(PrevEnd); 914 ++I; 915 916 // If the interval also overlaps the start of the "next" (i.e. 917 // current) range create a new interval for the remainder (which 918 // may be further trimmed). 919 if (RStart < IStop) 920 I.insert(RStart, IStop, Loc); 921 } 922 923 // Advance I so that I.stop() >= RStart, and check for overlap. 924 I.advanceTo(RStart); 925 if (!I.valid()) 926 return; 927 928 if (I.start() < RStart) { 929 // Interval start overlaps range - trim to the scope range. 930 I.setStartUnchecked(RStart); 931 // Remember that this interval was trimmed. 932 trimmedDefs.insert(RStart); 933 } 934 935 // The end of a lexical scope range is the last instruction in the 936 // range. To convert to an interval we need the index of the 937 // instruction after it. 938 REnd = REnd.getNextIndex(); 939 940 // Advance I to first interval outside current range. 941 I.advanceTo(REnd); 942 if (!I.valid()) 943 return; 944 945 PrevEnd = REnd; 946 } 947 948 // Check for overlap with end of final range. 949 if (PrevEnd && I.start() < PrevEnd) 950 I.setStopUnchecked(PrevEnd); 951 } 952 953 void LDVImpl::computeIntervals() { 954 LexicalScopes LS; 955 LS.initialize(*MF); 956 957 for (unsigned i = 0, e = userValues.size(); i != e; ++i) { 958 userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS); 959 userValues[i]->mapVirtRegs(this); 960 } 961 } 962 963 bool LDVImpl::runOnMachineFunction(MachineFunction &mf) { 964 clear(); 965 MF = &mf; 966 LIS = &pass.getAnalysis<LiveIntervals>(); 967 TRI = mf.getSubtarget().getRegisterInfo(); 968 LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: " 969 << mf.getName() << " **********\n"); 970 971 bool Changed = collectDebugValues(mf); 972 computeIntervals(); 973 LLVM_DEBUG(print(dbgs())); 974 ModifiedMF = Changed; 975 return Changed; 976 } 977 978 static void removeDebugValues(MachineFunction &mf) { 979 for (MachineBasicBlock &MBB : mf) { 980 for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) { 981 if (!MBBI->isDebugValue()) { 982 ++MBBI; 983 continue; 984 } 985 MBBI = MBB.erase(MBBI); 986 } 987 } 988 } 989 990 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) { 991 if (!EnableLDV) 992 return false; 993 if (!mf.getFunction().getSubprogram()) { 994 removeDebugValues(mf); 995 return false; 996 } 997 if (!pImpl) 998 pImpl = new LDVImpl(this); 999 return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf); 1000 } 1001 1002 void LiveDebugVariables::releaseMemory() { 1003 if (pImpl) 1004 static_cast<LDVImpl*>(pImpl)->clear(); 1005 } 1006 1007 LiveDebugVariables::~LiveDebugVariables() { 1008 if (pImpl) 1009 delete static_cast<LDVImpl*>(pImpl); 1010 } 1011 1012 //===----------------------------------------------------------------------===// 1013 // Live Range Splitting 1014 //===----------------------------------------------------------------------===// 1015 1016 bool 1017 UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs, 1018 LiveIntervals& LIS) { 1019 LLVM_DEBUG({ 1020 dbgs() << "Splitting Loc" << OldLocNo << '\t'; 1021 print(dbgs(), nullptr); 1022 }); 1023 bool DidChange = false; 1024 LocMap::iterator LocMapI; 1025 LocMapI.setMap(locInts); 1026 for (unsigned i = 0; i != NewRegs.size(); ++i) { 1027 LiveInterval *LI = &LIS.getInterval(NewRegs[i]); 1028 if (LI->empty()) 1029 continue; 1030 1031 // Don't allocate the new LocNo until it is needed. 1032 unsigned NewLocNo = UndefLocNo; 1033 1034 // Iterate over the overlaps between locInts and LI. 1035 LocMapI.find(LI->beginIndex()); 1036 if (!LocMapI.valid()) 1037 continue; 1038 LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start()); 1039 LiveInterval::iterator LIE = LI->end(); 1040 while (LocMapI.valid() && LII != LIE) { 1041 // At this point, we know that LocMapI.stop() > LII->start. 1042 LII = LI->advanceTo(LII, LocMapI.start()); 1043 if (LII == LIE) 1044 break; 1045 1046 // Now LII->end > LocMapI.start(). Do we have an overlap? 1047 if (LocMapI.value().locNo() == OldLocNo && LII->start < LocMapI.stop()) { 1048 // Overlapping correct location. Allocate NewLocNo now. 1049 if (NewLocNo == UndefLocNo) { 1050 MachineOperand MO = MachineOperand::CreateReg(LI->reg, false); 1051 MO.setSubReg(locations[OldLocNo].getSubReg()); 1052 NewLocNo = getLocationNo(MO); 1053 DidChange = true; 1054 } 1055 1056 SlotIndex LStart = LocMapI.start(); 1057 SlotIndex LStop = LocMapI.stop(); 1058 DbgValueLocation OldLoc = LocMapI.value(); 1059 1060 // Trim LocMapI down to the LII overlap. 1061 if (LStart < LII->start) 1062 LocMapI.setStartUnchecked(LII->start); 1063 if (LStop > LII->end) 1064 LocMapI.setStopUnchecked(LII->end); 1065 1066 // Change the value in the overlap. This may trigger coalescing. 1067 LocMapI.setValue(OldLoc.changeLocNo(NewLocNo)); 1068 1069 // Re-insert any removed OldLocNo ranges. 1070 if (LStart < LocMapI.start()) { 1071 LocMapI.insert(LStart, LocMapI.start(), OldLoc); 1072 ++LocMapI; 1073 assert(LocMapI.valid() && "Unexpected coalescing"); 1074 } 1075 if (LStop > LocMapI.stop()) { 1076 ++LocMapI; 1077 LocMapI.insert(LII->end, LStop, OldLoc); 1078 --LocMapI; 1079 } 1080 } 1081 1082 // Advance to the next overlap. 1083 if (LII->end < LocMapI.stop()) { 1084 if (++LII == LIE) 1085 break; 1086 LocMapI.advanceTo(LII->start); 1087 } else { 1088 ++LocMapI; 1089 if (!LocMapI.valid()) 1090 break; 1091 LII = LI->advanceTo(LII, LocMapI.start()); 1092 } 1093 } 1094 } 1095 1096 // Finally, remove any remaining OldLocNo intervals and OldLocNo itself. 1097 locations.erase(locations.begin() + OldLocNo); 1098 LocMapI.goToBegin(); 1099 while (LocMapI.valid()) { 1100 DbgValueLocation v = LocMapI.value(); 1101 if (v.locNo() == OldLocNo) { 1102 LLVM_DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';' 1103 << LocMapI.stop() << ")\n"); 1104 LocMapI.erase(); 1105 } else { 1106 // Undef values always have location number UndefLocNo, so don't change 1107 // locNo in that case. See getLocationNo(). 1108 if (!v.isUndef() && v.locNo() > OldLocNo) 1109 LocMapI.setValueUnchecked(v.changeLocNo(v.locNo() - 1)); 1110 ++LocMapI; 1111 } 1112 } 1113 1114 LLVM_DEBUG({ 1115 dbgs() << "Split result: \t"; 1116 print(dbgs(), nullptr); 1117 }); 1118 return DidChange; 1119 } 1120 1121 bool 1122 UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, 1123 LiveIntervals &LIS) { 1124 bool DidChange = false; 1125 // Split locations referring to OldReg. Iterate backwards so splitLocation can 1126 // safely erase unused locations. 1127 for (unsigned i = locations.size(); i ; --i) { 1128 unsigned LocNo = i-1; 1129 const MachineOperand *Loc = &locations[LocNo]; 1130 if (!Loc->isReg() || Loc->getReg() != OldReg) 1131 continue; 1132 DidChange |= splitLocation(LocNo, NewRegs, LIS); 1133 } 1134 return DidChange; 1135 } 1136 1137 void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) { 1138 bool DidChange = false; 1139 for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext()) 1140 DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS); 1141 1142 if (!DidChange) 1143 return; 1144 1145 // Map all of the new virtual registers. 1146 UserValue *UV = lookupVirtReg(OldReg); 1147 for (unsigned i = 0; i != NewRegs.size(); ++i) 1148 mapVirtReg(NewRegs[i], UV); 1149 } 1150 1151 void LiveDebugVariables:: 1152 splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) { 1153 if (pImpl) 1154 static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs); 1155 } 1156 1157 void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF, 1158 const TargetInstrInfo &TII, 1159 const TargetRegisterInfo &TRI, 1160 SpillOffsetMap &SpillOffsets) { 1161 // Build a set of new locations with new numbers so we can coalesce our 1162 // IntervalMap if two vreg intervals collapse to the same physical location. 1163 // Use MapVector instead of SetVector because MapVector::insert returns the 1164 // position of the previously or newly inserted element. The boolean value 1165 // tracks if the location was produced by a spill. 1166 // FIXME: This will be problematic if we ever support direct and indirect 1167 // frame index locations, i.e. expressing both variables in memory and 1168 // 'int x, *px = &x'. The "spilled" bit must become part of the location. 1169 MapVector<MachineOperand, std::pair<bool, unsigned>> NewLocations; 1170 SmallVector<unsigned, 4> LocNoMap(locations.size()); 1171 for (unsigned I = 0, E = locations.size(); I != E; ++I) { 1172 bool Spilled = false; 1173 unsigned SpillOffset = 0; 1174 MachineOperand Loc = locations[I]; 1175 // Only virtual registers are rewritten. 1176 if (Loc.isReg() && Loc.getReg() && 1177 TargetRegisterInfo::isVirtualRegister(Loc.getReg())) { 1178 unsigned VirtReg = Loc.getReg(); 1179 if (VRM.isAssignedReg(VirtReg) && 1180 TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) { 1181 // This can create a %noreg operand in rare cases when the sub-register 1182 // index is no longer available. That means the user value is in a 1183 // non-existent sub-register, and %noreg is exactly what we want. 1184 Loc.substPhysReg(VRM.getPhys(VirtReg), TRI); 1185 } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) { 1186 // Retrieve the stack slot offset. 1187 unsigned SpillSize; 1188 const MachineRegisterInfo &MRI = MF.getRegInfo(); 1189 const TargetRegisterClass *TRC = MRI.getRegClass(VirtReg); 1190 bool Success = TII.getStackSlotRange(TRC, Loc.getSubReg(), SpillSize, 1191 SpillOffset, MF); 1192 1193 // FIXME: Invalidate the location if the offset couldn't be calculated. 1194 (void)Success; 1195 1196 Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg)); 1197 Spilled = true; 1198 } else { 1199 Loc.setReg(0); 1200 Loc.setSubReg(0); 1201 } 1202 } 1203 1204 // Insert this location if it doesn't already exist and record a mapping 1205 // from the old number to the new number. 1206 auto InsertResult = NewLocations.insert({Loc, {Spilled, SpillOffset}}); 1207 unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first); 1208 LocNoMap[I] = NewLocNo; 1209 } 1210 1211 // Rewrite the locations and record the stack slot offsets for spills. 1212 locations.clear(); 1213 SpillOffsets.clear(); 1214 for (auto &Pair : NewLocations) { 1215 bool Spilled; 1216 unsigned SpillOffset; 1217 std::tie(Spilled, SpillOffset) = Pair.second; 1218 locations.push_back(Pair.first); 1219 if (Spilled) { 1220 unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair); 1221 SpillOffsets[NewLocNo] = SpillOffset; 1222 } 1223 } 1224 1225 // Update the interval map, but only coalesce left, since intervals to the 1226 // right use the old location numbers. This should merge two contiguous 1227 // DBG_VALUE intervals with different vregs that were allocated to the same 1228 // physical register. 1229 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) { 1230 DbgValueLocation Loc = I.value(); 1231 // Undef values don't exist in locations (and thus not in LocNoMap either) 1232 // so skip over them. See getLocationNo(). 1233 if (Loc.isUndef()) 1234 continue; 1235 unsigned NewLocNo = LocNoMap[Loc.locNo()]; 1236 I.setValueUnchecked(Loc.changeLocNo(NewLocNo)); 1237 I.setStart(I.start()); 1238 } 1239 } 1240 1241 /// Find an iterator for inserting a DBG_VALUE instruction. 1242 static MachineBasicBlock::iterator 1243 findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx, 1244 LiveIntervals &LIS) { 1245 SlotIndex Start = LIS.getMBBStartIdx(MBB); 1246 Idx = Idx.getBaseIndex(); 1247 1248 // Try to find an insert location by going backwards from Idx. 1249 MachineInstr *MI; 1250 while (!(MI = LIS.getInstructionFromIndex(Idx))) { 1251 // We've reached the beginning of MBB. 1252 if (Idx == Start) { 1253 MachineBasicBlock::iterator I = MBB->SkipPHIsLabelsAndDebug(MBB->begin()); 1254 return I; 1255 } 1256 Idx = Idx.getPrevIndex(); 1257 } 1258 1259 // Don't insert anything after the first terminator, though. 1260 return MI->isTerminator() ? MBB->getFirstTerminator() : 1261 std::next(MachineBasicBlock::iterator(MI)); 1262 } 1263 1264 /// Find an iterator for inserting the next DBG_VALUE instruction 1265 /// (or end if no more insert locations found). 1266 static MachineBasicBlock::iterator 1267 findNextInsertLocation(MachineBasicBlock *MBB, 1268 MachineBasicBlock::iterator I, 1269 SlotIndex StopIdx, MachineOperand &LocMO, 1270 LiveIntervals &LIS, 1271 const TargetRegisterInfo &TRI) { 1272 if (!LocMO.isReg()) 1273 return MBB->instr_end(); 1274 unsigned Reg = LocMO.getReg(); 1275 1276 // Find the next instruction in the MBB that define the register Reg. 1277 while (I != MBB->end() && !I->isTerminator()) { 1278 if (!LIS.isNotInMIMap(*I) && 1279 SlotIndex::isEarlierEqualInstr(StopIdx, LIS.getInstructionIndex(*I))) 1280 break; 1281 if (I->definesRegister(Reg, &TRI)) 1282 // The insert location is directly after the instruction/bundle. 1283 return std::next(I); 1284 ++I; 1285 } 1286 return MBB->end(); 1287 } 1288 1289 void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx, 1290 SlotIndex StopIdx, DbgValueLocation Loc, 1291 bool Spilled, unsigned SpillOffset, 1292 LiveIntervals &LIS, const TargetInstrInfo &TII, 1293 const TargetRegisterInfo &TRI) { 1294 SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB); 1295 // Only search within the current MBB. 1296 StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx; 1297 MachineBasicBlock::iterator I = findInsertLocation(MBB, StartIdx, LIS); 1298 // Undef values don't exist in locations so create new "noreg" register MOs 1299 // for them. See getLocationNo(). 1300 MachineOperand MO = !Loc.isUndef() ? 1301 locations[Loc.locNo()] : 1302 MachineOperand::CreateReg(/* Reg */ 0, /* isDef */ false, /* isImp */ false, 1303 /* isKill */ false, /* isDead */ false, 1304 /* isUndef */ false, /* isEarlyClobber */ false, 1305 /* SubReg */ 0, /* isDebug */ true); 1306 1307 ++NumInsertedDebugValues; 1308 1309 assert(cast<DILocalVariable>(Variable) 1310 ->isValidLocationForIntrinsic(getDebugLoc()) && 1311 "Expected inlined-at fields to agree"); 1312 1313 // If the location was spilled, the new DBG_VALUE will be indirect. If the 1314 // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate 1315 // that the original virtual register was a pointer. Also, add the stack slot 1316 // offset for the spilled register to the expression. 1317 const DIExpression *Expr = Expression; 1318 bool IsIndirect = Loc.wasIndirect(); 1319 if (Spilled) { 1320 auto Deref = IsIndirect ? DIExpression::WithDeref : DIExpression::NoDeref; 1321 Expr = 1322 DIExpression::prepend(Expr, DIExpression::NoDeref, SpillOffset, Deref); 1323 IsIndirect = true; 1324 } 1325 1326 assert((!Spilled || MO.isFI()) && "a spilled location must be a frame index"); 1327 1328 do { 1329 BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE), 1330 IsIndirect, MO, Variable, Expr); 1331 1332 // Continue and insert DBG_VALUES after every redefinition of register 1333 // associated with the debug value within the range 1334 I = findNextInsertLocation(MBB, I, StopIdx, MO, LIS, TRI); 1335 } while (I != MBB->end()); 1336 } 1337 1338 void UserLabel::insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx, 1339 LiveIntervals &LIS, 1340 const TargetInstrInfo &TII) { 1341 MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS); 1342 ++NumInsertedDebugLabels; 1343 BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_LABEL)) 1344 .addMetadata(Label); 1345 } 1346 1347 void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS, 1348 const TargetInstrInfo &TII, 1349 const TargetRegisterInfo &TRI, 1350 const SpillOffsetMap &SpillOffsets) { 1351 MachineFunction::iterator MFEnd = VRM->getMachineFunction().end(); 1352 1353 for (LocMap::const_iterator I = locInts.begin(); I.valid();) { 1354 SlotIndex Start = I.start(); 1355 SlotIndex Stop = I.stop(); 1356 DbgValueLocation Loc = I.value(); 1357 auto SpillIt = 1358 !Loc.isUndef() ? SpillOffsets.find(Loc.locNo()) : SpillOffsets.end(); 1359 bool Spilled = SpillIt != SpillOffsets.end(); 1360 unsigned SpillOffset = Spilled ? SpillIt->second : 0; 1361 1362 // If the interval start was trimmed to the lexical scope insert the 1363 // DBG_VALUE at the previous index (otherwise it appears after the 1364 // first instruction in the range). 1365 if (trimmedDefs.count(Start)) 1366 Start = Start.getPrevIndex(); 1367 1368 LLVM_DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << Loc.locNo()); 1369 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator(); 1370 SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB); 1371 1372 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd); 1373 insertDebugValue(&*MBB, Start, Stop, Loc, Spilled, SpillOffset, LIS, TII, 1374 TRI); 1375 // This interval may span multiple basic blocks. 1376 // Insert a DBG_VALUE into each one. 1377 while (Stop > MBBEnd) { 1378 // Move to the next block. 1379 Start = MBBEnd; 1380 if (++MBB == MFEnd) 1381 break; 1382 MBBEnd = LIS.getMBBEndIdx(&*MBB); 1383 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd); 1384 insertDebugValue(&*MBB, Start, Stop, Loc, Spilled, SpillOffset, LIS, TII, 1385 TRI); 1386 } 1387 LLVM_DEBUG(dbgs() << '\n'); 1388 if (MBB == MFEnd) 1389 break; 1390 1391 ++I; 1392 } 1393 } 1394 1395 void UserLabel::emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII) { 1396 LLVM_DEBUG(dbgs() << "\t" << loc); 1397 MachineFunction::iterator MBB = LIS.getMBBFromIndex(loc)->getIterator(); 1398 1399 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB)); 1400 insertDebugLabel(&*MBB, loc, LIS, TII); 1401 1402 LLVM_DEBUG(dbgs() << '\n'); 1403 } 1404 1405 void LDVImpl::emitDebugValues(VirtRegMap *VRM) { 1406 LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n"); 1407 if (!MF) 1408 return; 1409 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 1410 SpillOffsetMap SpillOffsets; 1411 for (auto &userValue : userValues) { 1412 LLVM_DEBUG(userValue->print(dbgs(), TRI)); 1413 userValue->rewriteLocations(*VRM, *MF, *TII, *TRI, SpillOffsets); 1414 userValue->emitDebugValues(VRM, *LIS, *TII, *TRI, SpillOffsets); 1415 } 1416 LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG LABELS **********\n"); 1417 for (auto &userLabel : userLabels) { 1418 LLVM_DEBUG(userLabel->print(dbgs(), TRI)); 1419 userLabel->emitDebugLabel(*LIS, *TII); 1420 } 1421 EmitDone = true; 1422 } 1423 1424 void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) { 1425 if (pImpl) 1426 static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM); 1427 } 1428 1429 bool LiveDebugVariables::doInitialization(Module &M) { 1430 return Pass::doInitialization(M); 1431 } 1432 1433 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1434 LLVM_DUMP_METHOD void LiveDebugVariables::dump() const { 1435 if (pImpl) 1436 static_cast<LDVImpl*>(pImpl)->print(dbgs()); 1437 } 1438 #endif 1439