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