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