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/IntervalMap.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 26 #include "llvm/CodeGen/MachineDominators.h" 27 #include "llvm/CodeGen/MachineFunction.h" 28 #include "llvm/CodeGen/MachineInstrBuilder.h" 29 #include "llvm/CodeGen/MachineRegisterInfo.h" 30 #include "llvm/CodeGen/Passes.h" 31 #include "llvm/CodeGen/VirtRegMap.h" 32 #include "llvm/IR/Constants.h" 33 #include "llvm/IR/DebugInfo.h" 34 #include "llvm/IR/Metadata.h" 35 #include "llvm/IR/Value.h" 36 #include "llvm/Support/CommandLine.h" 37 #include "llvm/Support/Debug.h" 38 #include "llvm/Support/raw_ostream.h" 39 #include "llvm/Target/TargetInstrInfo.h" 40 #include "llvm/Target/TargetMachine.h" 41 #include "llvm/Target/TargetRegisterInfo.h" 42 #include "llvm/Target/TargetSubtargetInfo.h" 43 #include <memory> 44 #include <utility> 45 46 using namespace llvm; 47 48 #define DEBUG_TYPE "livedebugvars" 49 50 static cl::opt<bool> 51 EnableLDV("live-debug-variables", cl::init(true), 52 cl::desc("Enable the live debug variables pass"), cl::Hidden); 53 54 STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted"); 55 char LiveDebugVariables::ID = 0; 56 57 INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE, 58 "Debug Variable Analysis", false, false) 59 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 60 INITIALIZE_PASS_DEPENDENCY(LiveIntervals) 61 INITIALIZE_PASS_END(LiveDebugVariables, DEBUG_TYPE, 62 "Debug Variable Analysis", false, false) 63 64 void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const { 65 AU.addRequired<MachineDominatorTree>(); 66 AU.addRequiredTransitive<LiveIntervals>(); 67 AU.setPreservesAll(); 68 MachineFunctionPass::getAnalysisUsage(AU); 69 } 70 71 LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID), pImpl(nullptr) { 72 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry()); 73 } 74 75 /// LocMap - Map of where a user value is live, and its location. 76 typedef IntervalMap<SlotIndex, unsigned, 4> LocMap; 77 78 /// UserValue - A user value is a part of a debug info user variable. 79 /// 80 /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register 81 /// holds part of a user variable. The part is identified by a byte offset. 82 /// 83 /// UserValues are grouped into equivalence classes for easier searching. Two 84 /// user values are related if they refer to the same variable, or if they are 85 /// held by the same virtual register. The equivalence class is the transitive 86 /// closure of that relation. 87 namespace { 88 class LDVImpl; 89 class UserValue { 90 const MDNode *Variable; ///< The debug info variable we are part of. 91 const MDNode *Expression; ///< Any complex address expression. 92 bool IsIndirect; ///< true if this is a register-indirect+offset value. 93 DebugLoc dl; ///< The debug location for the variable. This is 94 ///< used by dwarf writer to find lexical scope. 95 UserValue *leader; ///< Equivalence class leader. 96 UserValue *next; ///< Next value in equivalence class, or null. 97 98 /// Numbered locations referenced by locmap. 99 SmallVector<MachineOperand, 4> locations; 100 101 /// Map of slot indices where this value is live. 102 LocMap locInts; 103 104 /// coalesceLocation - After LocNo was changed, check if it has become 105 /// identical to another location, and coalesce them. This may cause LocNo or 106 /// a later location to be erased, but no earlier location will be erased. 107 void coalesceLocation(unsigned LocNo); 108 109 /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo. 110 void insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, unsigned LocNo, 111 LiveIntervals &LIS, const TargetInstrInfo &TII); 112 113 /// splitLocation - Replace OldLocNo ranges with NewRegs ranges where NewRegs 114 /// is live. Returns true if any changes were made. 115 bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs, 116 LiveIntervals &LIS); 117 118 public: 119 /// UserValue - Create a new UserValue. 120 UserValue(const MDNode *var, const MDNode *expr, bool i, DebugLoc L, 121 LocMap::Allocator &alloc) 122 : Variable(var), Expression(expr), IsIndirect(i), dl(std::move(L)), 123 leader(this), next(nullptr), locInts(alloc) {} 124 125 /// getLeader - Get the leader of this value's equivalence class. 126 UserValue *getLeader() { 127 UserValue *l = leader; 128 while (l != l->leader) 129 l = l->leader; 130 return leader = l; 131 } 132 133 /// getNext - Return the next UserValue in the equivalence class. 134 UserValue *getNext() const { return next; } 135 136 /// match - Does this UserValue match the parameters? 137 bool match(const MDNode *Var, const MDNode *Expr, const DILocation *IA, 138 bool indirect) const { 139 return Var == Variable && Expr == Expression && dl->getInlinedAt() == IA && 140 indirect == IsIndirect; 141 } 142 143 /// merge - Merge equivalence classes. 144 static UserValue *merge(UserValue *L1, UserValue *L2) { 145 L2 = L2->getLeader(); 146 if (!L1) 147 return L2; 148 L1 = L1->getLeader(); 149 if (L1 == L2) 150 return L1; 151 // Splice L2 before L1's members. 152 UserValue *End = L2; 153 while (End->next) { 154 End->leader = L1; 155 End = End->next; 156 } 157 End->leader = L1; 158 End->next = L1->next; 159 L1->next = L2; 160 return L1; 161 } 162 163 /// getLocationNo - Return the location number that matches Loc. 164 unsigned getLocationNo(const MachineOperand &LocMO) { 165 if (LocMO.isReg()) { 166 if (LocMO.getReg() == 0) 167 return ~0u; 168 // For register locations we dont care about use/def and other flags. 169 for (unsigned i = 0, e = locations.size(); i != e; ++i) 170 if (locations[i].isReg() && 171 locations[i].getReg() == LocMO.getReg() && 172 locations[i].getSubReg() == LocMO.getSubReg()) 173 return i; 174 } else 175 for (unsigned i = 0, e = locations.size(); i != e; ++i) 176 if (LocMO.isIdenticalTo(locations[i])) 177 return i; 178 locations.push_back(LocMO); 179 // We are storing a MachineOperand outside a MachineInstr. 180 locations.back().clearParent(); 181 // Don't store def operands. 182 if (locations.back().isReg()) 183 locations.back().setIsUse(); 184 return locations.size() - 1; 185 } 186 187 /// mapVirtRegs - Ensure that all virtual register locations are mapped. 188 void mapVirtRegs(LDVImpl *LDV); 189 190 /// addDef - Add a definition point to this value. 191 void addDef(SlotIndex Idx, const MachineOperand &LocMO) { 192 // Add a singular (Idx,Idx) -> Loc mapping. 193 LocMap::iterator I = locInts.find(Idx); 194 if (!I.valid() || I.start() != Idx) 195 I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO)); 196 else 197 // A later DBG_VALUE at the same SlotIndex overrides the old location. 198 I.setValue(getLocationNo(LocMO)); 199 } 200 201 /// extendDef - Extend the current definition as far as possible down. 202 /// Stop when meeting an existing def or when leaving the live 203 /// range of VNI. 204 /// End points where VNI is no longer live are added to Kills. 205 /// @param Idx Starting point for the definition. 206 /// @param LocNo Location number to propagate. 207 /// @param LR Restrict liveness to where LR has the value VNI. May be null. 208 /// @param VNI When LR is not null, this is the value to restrict to. 209 /// @param Kills Append end points of VNI's live range to Kills. 210 /// @param LIS Live intervals analysis. 211 void extendDef(SlotIndex Idx, unsigned LocNo, 212 LiveRange *LR, const VNInfo *VNI, 213 SmallVectorImpl<SlotIndex> *Kills, 214 LiveIntervals &LIS); 215 216 /// addDefsFromCopies - The value in LI/LocNo may be copies to other 217 /// registers. Determine if any of the copies are available at the kill 218 /// points, and add defs if possible. 219 /// @param LI Scan for copies of the value in LI->reg. 220 /// @param LocNo Location number of LI->reg. 221 /// @param Kills Points where the range of LocNo could be extended. 222 /// @param NewDefs Append (Idx, LocNo) of inserted defs here. 223 void addDefsFromCopies(LiveInterval *LI, unsigned LocNo, 224 const SmallVectorImpl<SlotIndex> &Kills, 225 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs, 226 MachineRegisterInfo &MRI, 227 LiveIntervals &LIS); 228 229 /// computeIntervals - Compute the live intervals of all locations after 230 /// collecting all their def points. 231 void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, 232 LiveIntervals &LIS); 233 234 /// splitRegister - Replace OldReg ranges with NewRegs ranges where NewRegs is 235 /// live. Returns true if any changes were made. 236 bool splitRegister(unsigned OldLocNo, ArrayRef<unsigned> NewRegs, 237 LiveIntervals &LIS); 238 239 /// rewriteLocations - Rewrite virtual register locations according to the 240 /// provided virtual register map. 241 void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI); 242 243 /// emitDebugValues - Recreate DBG_VALUE instruction from data structures. 244 void emitDebugValues(VirtRegMap *VRM, 245 LiveIntervals &LIS, const TargetInstrInfo &TRI); 246 247 /// getDebugLoc - Return DebugLoc of this UserValue. 248 DebugLoc getDebugLoc() { return dl;} 249 void print(raw_ostream &, const TargetRegisterInfo *); 250 }; 251 } // namespace 252 253 /// LDVImpl - Implementation of the LiveDebugVariables pass. 254 namespace { 255 class LDVImpl { 256 LiveDebugVariables &pass; 257 LocMap::Allocator allocator; 258 MachineFunction *MF; 259 LiveIntervals *LIS; 260 const TargetRegisterInfo *TRI; 261 262 /// Whether emitDebugValues is called. 263 bool EmitDone; 264 /// Whether the machine function is modified during the pass. 265 bool ModifiedMF; 266 267 /// userValues - All allocated UserValue instances. 268 SmallVector<std::unique_ptr<UserValue>, 8> userValues; 269 270 /// Map virtual register to eq class leader. 271 typedef DenseMap<unsigned, UserValue*> VRMap; 272 VRMap virtRegToEqClass; 273 274 /// Map user variable to eq class leader. 275 typedef DenseMap<const MDNode *, UserValue*> UVMap; 276 UVMap userVarMap; 277 278 /// getUserValue - Find or create a UserValue. 279 UserValue *getUserValue(const MDNode *Var, const MDNode *Expr, 280 bool IsIndirect, const DebugLoc &DL); 281 282 /// lookupVirtReg - Find the EC leader for VirtReg or null. 283 UserValue *lookupVirtReg(unsigned VirtReg); 284 285 /// handleDebugValue - Add DBG_VALUE instruction to our maps. 286 /// @param MI DBG_VALUE instruction 287 /// @param Idx Last valid SLotIndex before instruction. 288 /// @return True if the DBG_VALUE instruction should be deleted. 289 bool handleDebugValue(MachineInstr &MI, SlotIndex Idx); 290 291 /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding 292 /// a UserValue def for each instruction. 293 /// @param mf MachineFunction to be scanned. 294 /// @return True if any debug values were found. 295 bool collectDebugValues(MachineFunction &mf); 296 297 /// computeIntervals - Compute the live intervals of all user values after 298 /// collecting all their def points. 299 void computeIntervals(); 300 301 public: 302 LDVImpl(LiveDebugVariables *ps) 303 : pass(*ps), MF(nullptr), EmitDone(false), ModifiedMF(false) {} 304 bool runOnMachineFunction(MachineFunction &mf); 305 306 /// clear - Release all memory. 307 void clear() { 308 MF = nullptr; 309 userValues.clear(); 310 virtRegToEqClass.clear(); 311 userVarMap.clear(); 312 // Make sure we call emitDebugValues if the machine function was modified. 313 assert((!ModifiedMF || EmitDone) && 314 "Dbg values are not emitted in LDV"); 315 EmitDone = false; 316 ModifiedMF = false; 317 } 318 319 /// mapVirtReg - Map virtual register to an equivalence class. 320 void mapVirtReg(unsigned VirtReg, UserValue *EC); 321 322 /// splitRegister - Replace all references to OldReg with NewRegs. 323 void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs); 324 325 /// emitDebugValues - Recreate DBG_VALUE instruction from data structures. 326 void emitDebugValues(VirtRegMap *VRM); 327 328 void print(raw_ostream&); 329 }; 330 } // namespace 331 332 #ifndef NDEBUG 333 static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS, 334 const LLVMContext &Ctx) { 335 if (!DL) 336 return; 337 338 auto *Scope = cast<DIScope>(DL.getScope()); 339 // Omit the directory, because it's likely to be long and uninteresting. 340 CommentOS << Scope->getFilename(); 341 CommentOS << ':' << DL.getLine(); 342 if (DL.getCol() != 0) 343 CommentOS << ':' << DL.getCol(); 344 345 DebugLoc InlinedAtDL = DL.getInlinedAt(); 346 if (!InlinedAtDL) 347 return; 348 349 CommentOS << " @[ "; 350 printDebugLoc(InlinedAtDL, CommentOS, Ctx); 351 CommentOS << " ]"; 352 } 353 354 static void printExtendedName(raw_ostream &OS, const DILocalVariable *V, 355 const DILocation *DL) { 356 const LLVMContext &Ctx = V->getContext(); 357 StringRef Res = V->getName(); 358 if (!Res.empty()) 359 OS << Res << "," << V->getLine(); 360 if (auto *InlinedAt = DL->getInlinedAt()) { 361 if (DebugLoc InlinedAtDL = InlinedAt) { 362 OS << " @["; 363 printDebugLoc(InlinedAtDL, OS, Ctx); 364 OS << "]"; 365 } 366 } 367 } 368 369 void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) { 370 auto *DV = cast<DILocalVariable>(Variable); 371 OS << "!\""; 372 printExtendedName(OS, DV, dl); 373 374 OS << "\"\t"; 375 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) { 376 OS << " [" << I.start() << ';' << I.stop() << "):"; 377 if (I.value() == ~0u) 378 OS << "undef"; 379 else 380 OS << I.value(); 381 } 382 for (unsigned i = 0, e = locations.size(); i != e; ++i) { 383 OS << " Loc" << i << '='; 384 locations[i].print(OS, TRI); 385 } 386 OS << '\n'; 387 } 388 389 void LDVImpl::print(raw_ostream &OS) { 390 OS << "********** DEBUG VARIABLES **********\n"; 391 for (unsigned i = 0, e = userValues.size(); i != e; ++i) 392 userValues[i]->print(OS, TRI); 393 } 394 #endif 395 396 void UserValue::coalesceLocation(unsigned LocNo) { 397 unsigned KeepLoc = 0; 398 for (unsigned e = locations.size(); KeepLoc != e; ++KeepLoc) { 399 if (KeepLoc == LocNo) 400 continue; 401 if (locations[KeepLoc].isIdenticalTo(locations[LocNo])) 402 break; 403 } 404 // No matches. 405 if (KeepLoc == locations.size()) 406 return; 407 408 // Keep the smaller location, erase the larger one. 409 unsigned EraseLoc = LocNo; 410 if (KeepLoc > EraseLoc) 411 std::swap(KeepLoc, EraseLoc); 412 locations.erase(locations.begin() + EraseLoc); 413 414 // Rewrite values. 415 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) { 416 unsigned v = I.value(); 417 if (v == EraseLoc) 418 I.setValue(KeepLoc); // Coalesce when possible. 419 else if (v > EraseLoc) 420 I.setValueUnchecked(v-1); // Avoid coalescing with untransformed values. 421 } 422 } 423 424 void UserValue::mapVirtRegs(LDVImpl *LDV) { 425 for (unsigned i = 0, e = locations.size(); i != e; ++i) 426 if (locations[i].isReg() && 427 TargetRegisterInfo::isVirtualRegister(locations[i].getReg())) 428 LDV->mapVirtReg(locations[i].getReg(), this); 429 } 430 431 UserValue *LDVImpl::getUserValue(const MDNode *Var, const MDNode *Expr, 432 bool IsIndirect, const DebugLoc &DL) { 433 UserValue *&Leader = userVarMap[Var]; 434 if (Leader) { 435 UserValue *UV = Leader->getLeader(); 436 Leader = UV; 437 for (; UV; UV = UV->getNext()) 438 if (UV->match(Var, Expr, DL->getInlinedAt(), IsIndirect)) 439 return UV; 440 } 441 442 userValues.push_back( 443 make_unique<UserValue>(Var, Expr, IsIndirect, DL, allocator)); 444 UserValue *UV = userValues.back().get(); 445 Leader = UserValue::merge(Leader, UV); 446 return UV; 447 } 448 449 void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) { 450 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs"); 451 UserValue *&Leader = virtRegToEqClass[VirtReg]; 452 Leader = UserValue::merge(Leader, EC); 453 } 454 455 UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) { 456 if (UserValue *UV = virtRegToEqClass.lookup(VirtReg)) 457 return UV->getLeader(); 458 return nullptr; 459 } 460 461 bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) { 462 // DBG_VALUE loc, offset, variable 463 if (MI.getNumOperands() != 4 || 464 !(MI.getOperand(1).isReg() || MI.getOperand(1).isImm()) || 465 !MI.getOperand(2).isMetadata()) { 466 DEBUG(dbgs() << "Can't handle " << MI); 467 return false; 468 } 469 470 // Get or create the UserValue for (variable,offset). 471 bool IsIndirect = MI.isIndirectDebugValue(); 472 if (IsIndirect) 473 assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset"); 474 const MDNode *Var = MI.getDebugVariable(); 475 const MDNode *Expr = MI.getDebugExpression(); 476 //here. 477 UserValue *UV = getUserValue(Var, Expr, IsIndirect, MI.getDebugLoc()); 478 UV->addDef(Idx, MI.getOperand(0)); 479 return true; 480 } 481 482 bool LDVImpl::collectDebugValues(MachineFunction &mf) { 483 bool Changed = false; 484 for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE; 485 ++MFI) { 486 MachineBasicBlock *MBB = &*MFI; 487 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end(); 488 MBBI != MBBE;) { 489 if (!MBBI->isDebugValue()) { 490 ++MBBI; 491 continue; 492 } 493 // DBG_VALUE has no slot index, use the previous instruction instead. 494 SlotIndex Idx = 495 MBBI == MBB->begin() 496 ? LIS->getMBBStartIdx(MBB) 497 : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot(); 498 // Handle consecutive DBG_VALUE instructions with the same slot index. 499 do { 500 if (handleDebugValue(*MBBI, Idx)) { 501 MBBI = MBB->erase(MBBI); 502 Changed = true; 503 } else 504 ++MBBI; 505 } while (MBBI != MBBE && MBBI->isDebugValue()); 506 } 507 } 508 return Changed; 509 } 510 511 /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a 512 /// data-flow analysis to propagate them beyond basic block boundaries. 513 void UserValue::extendDef(SlotIndex Idx, unsigned LocNo, LiveRange *LR, 514 const VNInfo *VNI, SmallVectorImpl<SlotIndex> *Kills, 515 LiveIntervals &LIS) { 516 SlotIndex Start = Idx; 517 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start); 518 SlotIndex Stop = LIS.getMBBEndIdx(MBB); 519 LocMap::iterator I = locInts.find(Start); 520 521 // Limit to VNI's live range. 522 bool ToEnd = true; 523 if (LR && VNI) { 524 LiveInterval::Segment *Segment = LR->getSegmentContaining(Start); 525 if (!Segment || Segment->valno != VNI) { 526 if (Kills) 527 Kills->push_back(Start); 528 return; 529 } 530 if (Segment->end < Stop) { 531 Stop = Segment->end; 532 ToEnd = false; 533 } 534 } 535 536 // There could already be a short def at Start. 537 if (I.valid() && I.start() <= Start) { 538 // Stop when meeting a different location or an already extended interval. 539 Start = Start.getNextSlot(); 540 if (I.value() != LocNo || I.stop() != Start) 541 return; 542 // This is a one-slot placeholder. Just skip it. 543 ++I; 544 } 545 546 // Limited by the next def. 547 if (I.valid() && I.start() < Stop) { 548 Stop = I.start(); 549 ToEnd = false; 550 } 551 // Limited by VNI's live range. 552 else if (!ToEnd && Kills) 553 Kills->push_back(Stop); 554 555 if (Start < Stop) 556 I.insert(Start, Stop, LocNo); 557 } 558 559 void 560 UserValue::addDefsFromCopies(LiveInterval *LI, unsigned LocNo, 561 const SmallVectorImpl<SlotIndex> &Kills, 562 SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs, 563 MachineRegisterInfo &MRI, LiveIntervals &LIS) { 564 if (Kills.empty()) 565 return; 566 // Don't track copies from physregs, there are too many uses. 567 if (!TargetRegisterInfo::isVirtualRegister(LI->reg)) 568 return; 569 570 // Collect all the (vreg, valno) pairs that are copies of LI. 571 SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues; 572 for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) { 573 MachineInstr *MI = MO.getParent(); 574 // Copies of the full value. 575 if (MO.getSubReg() || !MI->isCopy()) 576 continue; 577 unsigned DstReg = MI->getOperand(0).getReg(); 578 579 // Don't follow copies to physregs. These are usually setting up call 580 // arguments, and the argument registers are always call clobbered. We are 581 // better off in the source register which could be a callee-saved register, 582 // or it could be spilled. 583 if (!TargetRegisterInfo::isVirtualRegister(DstReg)) 584 continue; 585 586 // Is LocNo extended to reach this copy? If not, another def may be blocking 587 // it, or we are looking at a wrong value of LI. 588 SlotIndex Idx = LIS.getInstructionIndex(*MI); 589 LocMap::iterator I = locInts.find(Idx.getRegSlot(true)); 590 if (!I.valid() || I.value() != LocNo) 591 continue; 592 593 if (!LIS.hasInterval(DstReg)) 594 continue; 595 LiveInterval *DstLI = &LIS.getInterval(DstReg); 596 const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot()); 597 assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value"); 598 CopyValues.push_back(std::make_pair(DstLI, DstVNI)); 599 } 600 601 if (CopyValues.empty()) 602 return; 603 604 DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI << '\n'); 605 606 // Try to add defs of the copied values for each kill point. 607 for (unsigned i = 0, e = Kills.size(); i != e; ++i) { 608 SlotIndex Idx = Kills[i]; 609 for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) { 610 LiveInterval *DstLI = CopyValues[j].first; 611 const VNInfo *DstVNI = CopyValues[j].second; 612 if (DstLI->getVNInfoAt(Idx) != DstVNI) 613 continue; 614 // Check that there isn't already a def at Idx 615 LocMap::iterator I = locInts.find(Idx); 616 if (I.valid() && I.start() <= Idx) 617 continue; 618 DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #" 619 << DstVNI->id << " in " << *DstLI << '\n'); 620 MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def); 621 assert(CopyMI && CopyMI->isCopy() && "Bad copy value"); 622 unsigned LocNo = getLocationNo(CopyMI->getOperand(0)); 623 I.insert(Idx, Idx.getNextSlot(), LocNo); 624 NewDefs.push_back(std::make_pair(Idx, LocNo)); 625 break; 626 } 627 } 628 } 629 630 void 631 UserValue::computeIntervals(MachineRegisterInfo &MRI, 632 const TargetRegisterInfo &TRI, 633 LiveIntervals &LIS) { 634 SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs; 635 636 // Collect all defs to be extended (Skipping undefs). 637 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) 638 if (I.value() != ~0u) 639 Defs.push_back(std::make_pair(I.start(), I.value())); 640 641 // Extend all defs, and possibly add new ones along the way. 642 for (unsigned i = 0; i != Defs.size(); ++i) { 643 SlotIndex Idx = Defs[i].first; 644 unsigned LocNo = Defs[i].second; 645 const MachineOperand &Loc = locations[LocNo]; 646 647 if (!Loc.isReg()) { 648 extendDef(Idx, LocNo, nullptr, nullptr, nullptr, LIS); 649 continue; 650 } 651 652 // Register locations are constrained to where the register value is live. 653 if (TargetRegisterInfo::isVirtualRegister(Loc.getReg())) { 654 LiveInterval *LI = nullptr; 655 const VNInfo *VNI = nullptr; 656 if (LIS.hasInterval(Loc.getReg())) { 657 LI = &LIS.getInterval(Loc.getReg()); 658 VNI = LI->getVNInfoAt(Idx); 659 } 660 SmallVector<SlotIndex, 16> Kills; 661 extendDef(Idx, LocNo, LI, VNI, &Kills, LIS); 662 if (LI) 663 addDefsFromCopies(LI, LocNo, Kills, Defs, MRI, LIS); 664 continue; 665 } 666 667 // For physregs, use the live range of the first regunit as a guide. 668 unsigned Unit = *MCRegUnitIterator(Loc.getReg(), &TRI); 669 LiveRange *LR = &LIS.getRegUnit(Unit); 670 const VNInfo *VNI = LR->getVNInfoAt(Idx); 671 // Don't track copies from physregs, it is too expensive. 672 extendDef(Idx, LocNo, LR, VNI, nullptr, LIS); 673 } 674 675 // Finally, erase all the undefs. 676 for (LocMap::iterator I = locInts.begin(); I.valid();) 677 if (I.value() == ~0u) 678 I.erase(); 679 else 680 ++I; 681 } 682 683 void LDVImpl::computeIntervals() { 684 for (unsigned i = 0, e = userValues.size(); i != e; ++i) { 685 userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS); 686 userValues[i]->mapVirtRegs(this); 687 } 688 } 689 690 bool LDVImpl::runOnMachineFunction(MachineFunction &mf) { 691 clear(); 692 MF = &mf; 693 LIS = &pass.getAnalysis<LiveIntervals>(); 694 TRI = mf.getSubtarget().getRegisterInfo(); 695 DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: " 696 << mf.getName() << " **********\n"); 697 698 bool Changed = collectDebugValues(mf); 699 computeIntervals(); 700 DEBUG(print(dbgs())); 701 ModifiedMF = Changed; 702 return Changed; 703 } 704 705 static void removeDebugValues(MachineFunction &mf) { 706 for (MachineBasicBlock &MBB : mf) { 707 for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) { 708 if (!MBBI->isDebugValue()) { 709 ++MBBI; 710 continue; 711 } 712 MBBI = MBB.erase(MBBI); 713 } 714 } 715 } 716 717 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) { 718 if (!EnableLDV) 719 return false; 720 if (!mf.getFunction()->getSubprogram()) { 721 removeDebugValues(mf); 722 return false; 723 } 724 if (!pImpl) 725 pImpl = new LDVImpl(this); 726 return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf); 727 } 728 729 void LiveDebugVariables::releaseMemory() { 730 if (pImpl) 731 static_cast<LDVImpl*>(pImpl)->clear(); 732 } 733 734 LiveDebugVariables::~LiveDebugVariables() { 735 if (pImpl) 736 delete static_cast<LDVImpl*>(pImpl); 737 } 738 739 //===----------------------------------------------------------------------===// 740 // Live Range Splitting 741 //===----------------------------------------------------------------------===// 742 743 bool 744 UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs, 745 LiveIntervals& LIS) { 746 DEBUG({ 747 dbgs() << "Splitting Loc" << OldLocNo << '\t'; 748 print(dbgs(), nullptr); 749 }); 750 bool DidChange = false; 751 LocMap::iterator LocMapI; 752 LocMapI.setMap(locInts); 753 for (unsigned i = 0; i != NewRegs.size(); ++i) { 754 LiveInterval *LI = &LIS.getInterval(NewRegs[i]); 755 if (LI->empty()) 756 continue; 757 758 // Don't allocate the new LocNo until it is needed. 759 unsigned NewLocNo = ~0u; 760 761 // Iterate over the overlaps between locInts and LI. 762 LocMapI.find(LI->beginIndex()); 763 if (!LocMapI.valid()) 764 continue; 765 LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start()); 766 LiveInterval::iterator LIE = LI->end(); 767 while (LocMapI.valid() && LII != LIE) { 768 // At this point, we know that LocMapI.stop() > LII->start. 769 LII = LI->advanceTo(LII, LocMapI.start()); 770 if (LII == LIE) 771 break; 772 773 // Now LII->end > LocMapI.start(). Do we have an overlap? 774 if (LocMapI.value() == OldLocNo && LII->start < LocMapI.stop()) { 775 // Overlapping correct location. Allocate NewLocNo now. 776 if (NewLocNo == ~0u) { 777 MachineOperand MO = MachineOperand::CreateReg(LI->reg, false); 778 MO.setSubReg(locations[OldLocNo].getSubReg()); 779 NewLocNo = getLocationNo(MO); 780 DidChange = true; 781 } 782 783 SlotIndex LStart = LocMapI.start(); 784 SlotIndex LStop = LocMapI.stop(); 785 786 // Trim LocMapI down to the LII overlap. 787 if (LStart < LII->start) 788 LocMapI.setStartUnchecked(LII->start); 789 if (LStop > LII->end) 790 LocMapI.setStopUnchecked(LII->end); 791 792 // Change the value in the overlap. This may trigger coalescing. 793 LocMapI.setValue(NewLocNo); 794 795 // Re-insert any removed OldLocNo ranges. 796 if (LStart < LocMapI.start()) { 797 LocMapI.insert(LStart, LocMapI.start(), OldLocNo); 798 ++LocMapI; 799 assert(LocMapI.valid() && "Unexpected coalescing"); 800 } 801 if (LStop > LocMapI.stop()) { 802 ++LocMapI; 803 LocMapI.insert(LII->end, LStop, OldLocNo); 804 --LocMapI; 805 } 806 } 807 808 // Advance to the next overlap. 809 if (LII->end < LocMapI.stop()) { 810 if (++LII == LIE) 811 break; 812 LocMapI.advanceTo(LII->start); 813 } else { 814 ++LocMapI; 815 if (!LocMapI.valid()) 816 break; 817 LII = LI->advanceTo(LII, LocMapI.start()); 818 } 819 } 820 } 821 822 // Finally, remove any remaining OldLocNo intervals and OldLocNo itself. 823 locations.erase(locations.begin() + OldLocNo); 824 LocMapI.goToBegin(); 825 while (LocMapI.valid()) { 826 unsigned v = LocMapI.value(); 827 if (v == OldLocNo) { 828 DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';' 829 << LocMapI.stop() << ")\n"); 830 LocMapI.erase(); 831 } else { 832 if (v > OldLocNo) 833 LocMapI.setValueUnchecked(v-1); 834 ++LocMapI; 835 } 836 } 837 838 DEBUG({dbgs() << "Split result: \t"; print(dbgs(), nullptr);}); 839 return DidChange; 840 } 841 842 bool 843 UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, 844 LiveIntervals &LIS) { 845 bool DidChange = false; 846 // Split locations referring to OldReg. Iterate backwards so splitLocation can 847 // safely erase unused locations. 848 for (unsigned i = locations.size(); i ; --i) { 849 unsigned LocNo = i-1; 850 const MachineOperand *Loc = &locations[LocNo]; 851 if (!Loc->isReg() || Loc->getReg() != OldReg) 852 continue; 853 DidChange |= splitLocation(LocNo, NewRegs, LIS); 854 } 855 return DidChange; 856 } 857 858 void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) { 859 bool DidChange = false; 860 for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext()) 861 DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS); 862 863 if (!DidChange) 864 return; 865 866 // Map all of the new virtual registers. 867 UserValue *UV = lookupVirtReg(OldReg); 868 for (unsigned i = 0; i != NewRegs.size(); ++i) 869 mapVirtReg(NewRegs[i], UV); 870 } 871 872 void LiveDebugVariables:: 873 splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) { 874 if (pImpl) 875 static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs); 876 } 877 878 void 879 UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI) { 880 // Iterate over locations in reverse makes it easier to handle coalescing. 881 for (unsigned i = locations.size(); i ; --i) { 882 unsigned LocNo = i-1; 883 MachineOperand &Loc = locations[LocNo]; 884 // Only virtual registers are rewritten. 885 if (!Loc.isReg() || !Loc.getReg() || 886 !TargetRegisterInfo::isVirtualRegister(Loc.getReg())) 887 continue; 888 unsigned VirtReg = Loc.getReg(); 889 if (VRM.isAssignedReg(VirtReg) && 890 TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) { 891 // This can create a %noreg operand in rare cases when the sub-register 892 // index is no longer available. That means the user value is in a 893 // non-existent sub-register, and %noreg is exactly what we want. 894 Loc.substPhysReg(VRM.getPhys(VirtReg), TRI); 895 } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) { 896 // FIXME: Translate SubIdx to a stackslot offset. 897 Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg)); 898 } else { 899 Loc.setReg(0); 900 Loc.setSubReg(0); 901 } 902 coalesceLocation(LocNo); 903 } 904 } 905 906 /// findInsertLocation - Find an iterator for inserting a DBG_VALUE 907 /// instruction. 908 static MachineBasicBlock::iterator 909 findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx, 910 LiveIntervals &LIS) { 911 SlotIndex Start = LIS.getMBBStartIdx(MBB); 912 Idx = Idx.getBaseIndex(); 913 914 // Try to find an insert location by going backwards from Idx. 915 MachineInstr *MI; 916 while (!(MI = LIS.getInstructionFromIndex(Idx))) { 917 // We've reached the beginning of MBB. 918 if (Idx == Start) { 919 MachineBasicBlock::iterator I = MBB->SkipPHIsLabelsAndDebug(MBB->begin()); 920 return I; 921 } 922 Idx = Idx.getPrevIndex(); 923 } 924 925 // Don't insert anything after the first terminator, though. 926 return MI->isTerminator() ? MBB->getFirstTerminator() : 927 std::next(MachineBasicBlock::iterator(MI)); 928 } 929 930 void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, 931 unsigned LocNo, 932 LiveIntervals &LIS, 933 const TargetInstrInfo &TII) { 934 MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS); 935 MachineOperand &Loc = locations[LocNo]; 936 ++NumInsertedDebugValues; 937 938 assert(cast<DILocalVariable>(Variable) 939 ->isValidLocationForIntrinsic(getDebugLoc()) && 940 "Expected inlined-at fields to agree"); 941 if (Loc.isReg()) 942 BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE), 943 IsIndirect, Loc.getReg(), Variable, Expression); 944 else 945 BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE)) 946 .add(Loc) 947 .addImm(0U) 948 .addMetadata(Variable) 949 .addMetadata(Expression); 950 } 951 952 void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS, 953 const TargetInstrInfo &TII) { 954 MachineFunction::iterator MFEnd = VRM->getMachineFunction().end(); 955 956 for (LocMap::const_iterator I = locInts.begin(); I.valid();) { 957 SlotIndex Start = I.start(); 958 SlotIndex Stop = I.stop(); 959 unsigned LocNo = I.value(); 960 DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo); 961 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator(); 962 SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB); 963 964 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd); 965 insertDebugValue(&*MBB, Start, LocNo, LIS, TII); 966 // This interval may span multiple basic blocks. 967 // Insert a DBG_VALUE into each one. 968 while(Stop > MBBEnd) { 969 // Move to the next block. 970 Start = MBBEnd; 971 if (++MBB == MFEnd) 972 break; 973 MBBEnd = LIS.getMBBEndIdx(&*MBB); 974 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd); 975 insertDebugValue(&*MBB, Start, LocNo, LIS, TII); 976 } 977 DEBUG(dbgs() << '\n'); 978 if (MBB == MFEnd) 979 break; 980 981 ++I; 982 } 983 } 984 985 void LDVImpl::emitDebugValues(VirtRegMap *VRM) { 986 DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n"); 987 if (!MF) 988 return; 989 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 990 for (unsigned i = 0, e = userValues.size(); i != e; ++i) { 991 DEBUG(userValues[i]->print(dbgs(), TRI)); 992 userValues[i]->rewriteLocations(*VRM, *TRI); 993 userValues[i]->emitDebugValues(VRM, *LIS, *TII); 994 } 995 EmitDone = true; 996 } 997 998 void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) { 999 if (pImpl) 1000 static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM); 1001 } 1002 1003 bool LiveDebugVariables::doInitialization(Module &M) { 1004 return Pass::doInitialization(M); 1005 } 1006 1007 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1008 LLVM_DUMP_METHOD void LiveDebugVariables::dump() const { 1009 if (pImpl) 1010 static_cast<LDVImpl*>(pImpl)->print(dbgs()); 1011 } 1012 #endif 1013