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