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