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