1 //===- llvm/CodeGen/AsmPrinter/DbgEntityHistoryCalculator.cpp -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "llvm/CodeGen/DbgEntityHistoryCalculator.h" 10 #include "llvm/ADT/BitVector.h" 11 #include "llvm/ADT/STLExtras.h" 12 #include "llvm/ADT/SmallSet.h" 13 #include "llvm/ADT/SmallVector.h" 14 #include "llvm/CodeGen/MachineBasicBlock.h" 15 #include "llvm/CodeGen/MachineFunction.h" 16 #include "llvm/CodeGen/MachineInstr.h" 17 #include "llvm/CodeGen/MachineOperand.h" 18 #include "llvm/CodeGen/TargetLowering.h" 19 #include "llvm/CodeGen/TargetRegisterInfo.h" 20 #include "llvm/CodeGen/TargetSubtargetInfo.h" 21 #include "llvm/IR/DebugInfoMetadata.h" 22 #include "llvm/IR/DebugLoc.h" 23 #include "llvm/MC/MCRegisterInfo.h" 24 #include "llvm/Support/Debug.h" 25 #include "llvm/Support/raw_ostream.h" 26 #include <cassert> 27 #include <map> 28 #include <utility> 29 30 using namespace llvm; 31 32 #define DEBUG_TYPE "dwarfdebug" 33 34 namespace { 35 using EntryIndex = DbgValueHistoryMap::EntryIndex; 36 } 37 38 // If @MI is a DBG_VALUE with debug value described by a 39 // defined register, returns the number of this register. 40 // In the other case, returns 0. 41 static unsigned isDescribedByReg(const MachineInstr &MI) { 42 assert(MI.isDebugValue()); 43 assert(MI.getNumOperands() == 4); 44 // If location of variable is described using a register (directly or 45 // indirectly), this register is always a first operand. 46 return MI.getOperand(0).isReg() ? MI.getOperand(0).getReg() : 0; 47 } 48 49 bool DbgValueHistoryMap::startDbgValue(InlinedEntity Var, 50 const MachineInstr &MI, 51 EntryIndex &NewIndex) { 52 // Instruction range should start with a DBG_VALUE instruction for the 53 // variable. 54 assert(MI.isDebugValue() && "not a DBG_VALUE"); 55 auto &Entries = VarEntries[Var]; 56 if (!Entries.empty() && Entries.back().isDbgValue() && 57 !Entries.back().isClosed() && 58 Entries.back().getInstr()->isIdenticalTo(MI)) { 59 LLVM_DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n" 60 << "\t" << Entries.back().getInstr() << "\t" << MI 61 << "\n"); 62 return false; 63 } 64 Entries.emplace_back(&MI, Entry::DbgValue); 65 NewIndex = Entries.size() - 1; 66 return true; 67 } 68 69 EntryIndex DbgValueHistoryMap::startClobber(InlinedEntity Var, 70 const MachineInstr &MI) { 71 auto &Entries = VarEntries[Var]; 72 // If an instruction clobbers multiple registers that the variable is 73 // described by, then we may have already created a clobbering instruction. 74 if (Entries.back().isClobber() && Entries.back().getInstr() == &MI) 75 return Entries.size() - 1; 76 Entries.emplace_back(&MI, Entry::Clobber); 77 return Entries.size() - 1; 78 } 79 80 void DbgValueHistoryMap::Entry::endEntry(EntryIndex Index) { 81 // For now, instruction ranges are not allowed to cross basic block 82 // boundaries. 83 assert(isDbgValue() && "Setting end index for non-debug value"); 84 assert(!isClosed() && "End index has already been set"); 85 EndIndex = Index; 86 } 87 88 void DbgLabelInstrMap::addInstr(InlinedEntity Label, const MachineInstr &MI) { 89 assert(MI.isDebugLabel() && "not a DBG_LABEL"); 90 LabelInstr[Label] = &MI; 91 } 92 93 namespace { 94 95 // Maps physreg numbers to the variables they describe. 96 using InlinedEntity = DbgValueHistoryMap::InlinedEntity; 97 using RegDescribedVarsMap = std::map<unsigned, SmallVector<InlinedEntity, 1>>; 98 99 // Keeps track of the debug value entries that are currently live for each 100 // inlined entity. As the history map entries are stored in a SmallVector, they 101 // may be moved at insertion of new entries, so store indices rather than 102 // pointers. 103 using DbgValueEntriesMap = std::map<InlinedEntity, SmallSet<EntryIndex, 1>>; 104 105 } // end anonymous namespace 106 107 // Claim that @Var is not described by @RegNo anymore. 108 static void dropRegDescribedVar(RegDescribedVarsMap &RegVars, unsigned RegNo, 109 InlinedEntity Var) { 110 const auto &I = RegVars.find(RegNo); 111 assert(RegNo != 0U && I != RegVars.end()); 112 auto &VarSet = I->second; 113 const auto &VarPos = llvm::find(VarSet, Var); 114 assert(VarPos != VarSet.end()); 115 VarSet.erase(VarPos); 116 // Don't keep empty sets in a map to keep it as small as possible. 117 if (VarSet.empty()) 118 RegVars.erase(I); 119 } 120 121 // Claim that @Var is now described by @RegNo. 122 static void addRegDescribedVar(RegDescribedVarsMap &RegVars, unsigned RegNo, 123 InlinedEntity Var) { 124 assert(RegNo != 0U); 125 auto &VarSet = RegVars[RegNo]; 126 assert(!is_contained(VarSet, Var)); 127 VarSet.push_back(Var); 128 } 129 130 /// Create a clobbering entry and end all open debug value entries 131 /// for \p Var that are described by \p RegNo using that entry. 132 static void clobberRegEntries(InlinedEntity Var, unsigned RegNo, 133 const MachineInstr &ClobberingInstr, 134 DbgValueEntriesMap &LiveEntries, 135 DbgValueHistoryMap &HistMap) { 136 EntryIndex ClobberIndex = HistMap.startClobber(Var, ClobberingInstr); 137 138 // Close all entries whose values are described by the register. 139 SmallVector<EntryIndex, 4> IndicesToErase; 140 for (auto Index : LiveEntries[Var]) { 141 auto &Entry = HistMap.getEntry(Var, Index); 142 assert(Entry.isDbgValue() && "Not a DBG_VALUE in LiveEntries"); 143 if (isDescribedByReg(*Entry.getInstr()) == RegNo) { 144 IndicesToErase.push_back(Index); 145 Entry.endEntry(ClobberIndex); 146 } 147 } 148 149 // Drop all entries that have ended. 150 for (auto Index : IndicesToErase) 151 LiveEntries[Var].erase(Index); 152 } 153 154 /// Add a new debug value for \p Var. Closes all overlapping debug values. 155 static void handleNewDebugValue(InlinedEntity Var, const MachineInstr &DV, 156 RegDescribedVarsMap &RegVars, 157 DbgValueEntriesMap &LiveEntries, 158 DbgValueHistoryMap &HistMap) { 159 EntryIndex NewIndex; 160 if (HistMap.startDbgValue(Var, DV, NewIndex)) { 161 SmallDenseMap<unsigned, bool, 4> TrackedRegs; 162 163 // If we have created a new debug value entry, close all preceding 164 // live entries that overlap. 165 SmallVector<EntryIndex, 4> IndicesToErase; 166 const DIExpression *DIExpr = DV.getDebugExpression(); 167 for (auto Index : LiveEntries[Var]) { 168 auto &Entry = HistMap.getEntry(Var, Index); 169 assert(Entry.isDbgValue() && "Not a DBG_VALUE in LiveEntries"); 170 const MachineInstr &DV = *Entry.getInstr(); 171 bool Overlaps = DIExpr->fragmentsOverlap(DV.getDebugExpression()); 172 if (Overlaps) { 173 IndicesToErase.push_back(Index); 174 Entry.endEntry(NewIndex); 175 } 176 if (unsigned Reg = isDescribedByReg(DV)) 177 TrackedRegs[Reg] |= !Overlaps; 178 } 179 180 // If the new debug value is described by a register, add tracking of 181 // that register if it is not already tracked. 182 if (unsigned NewReg = isDescribedByReg(DV)) { 183 if (!TrackedRegs.count(NewReg)) 184 addRegDescribedVar(RegVars, NewReg, Var); 185 LiveEntries[Var].insert(NewIndex); 186 TrackedRegs[NewReg] = true; 187 } 188 189 // Drop tracking of registers that are no longer used. 190 for (auto I : TrackedRegs) 191 if (!I.second) 192 dropRegDescribedVar(RegVars, I.first, Var); 193 194 // Drop all entries that have ended, and mark the new entry as live. 195 for (auto Index : IndicesToErase) 196 LiveEntries[Var].erase(Index); 197 LiveEntries[Var].insert(NewIndex); 198 } 199 } 200 201 // Terminate the location range for variables described by register at 202 // @I by inserting @ClobberingInstr to their history. 203 static void clobberRegisterUses(RegDescribedVarsMap &RegVars, 204 RegDescribedVarsMap::iterator I, 205 DbgValueHistoryMap &HistMap, 206 DbgValueEntriesMap &LiveEntries, 207 const MachineInstr &ClobberingInstr) { 208 // Iterate over all variables described by this register and add this 209 // instruction to their history, clobbering it. 210 for (const auto &Var : I->second) 211 clobberRegEntries(Var, I->first, ClobberingInstr, LiveEntries, HistMap); 212 RegVars.erase(I); 213 } 214 215 // Terminate the location range for variables described by register 216 // @RegNo by inserting @ClobberingInstr to their history. 217 static void clobberRegisterUses(RegDescribedVarsMap &RegVars, unsigned RegNo, 218 DbgValueHistoryMap &HistMap, 219 DbgValueEntriesMap &LiveEntries, 220 const MachineInstr &ClobberingInstr) { 221 const auto &I = RegVars.find(RegNo); 222 if (I == RegVars.end()) 223 return; 224 clobberRegisterUses(RegVars, I, HistMap, LiveEntries, ClobberingInstr); 225 } 226 227 // Returns the first instruction in @MBB which corresponds to 228 // the function epilogue, or nullptr if @MBB doesn't contain an epilogue. 229 static const MachineInstr *getFirstEpilogueInst(const MachineBasicBlock &MBB) { 230 auto LastMI = MBB.getLastNonDebugInstr(); 231 if (LastMI == MBB.end() || !LastMI->isReturn()) 232 return nullptr; 233 // Assume that epilogue starts with instruction having the same debug location 234 // as the return instruction. 235 DebugLoc LastLoc = LastMI->getDebugLoc(); 236 auto Res = LastMI; 237 for (MachineBasicBlock::const_reverse_iterator I = LastMI.getReverse(), 238 E = MBB.rend(); 239 I != E; ++I) { 240 if (I->getDebugLoc() != LastLoc) 241 return &*Res; 242 Res = &*I; 243 } 244 // If all instructions have the same debug location, assume whole MBB is 245 // an epilogue. 246 return &*MBB.begin(); 247 } 248 249 // Collect registers that are modified in the function body (their 250 // contents is changed outside of the prologue and epilogue). 251 static void collectChangingRegs(const MachineFunction *MF, 252 const TargetRegisterInfo *TRI, 253 BitVector &Regs) { 254 for (const auto &MBB : *MF) { 255 auto FirstEpilogueInst = getFirstEpilogueInst(MBB); 256 257 for (const auto &MI : MBB) { 258 // Avoid looking at prologue or epilogue instructions. 259 if (&MI == FirstEpilogueInst) 260 break; 261 if (MI.getFlag(MachineInstr::FrameSetup)) 262 continue; 263 264 // Look for register defs and register masks. Register masks are 265 // typically on calls and they clobber everything not in the mask. 266 for (const MachineOperand &MO : MI.operands()) { 267 // Skip virtual registers since they are handled by the parent. 268 if (MO.isReg() && MO.isDef() && MO.getReg() && 269 !TRI->isVirtualRegister(MO.getReg())) { 270 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); 271 ++AI) 272 Regs.set(*AI); 273 } else if (MO.isRegMask()) { 274 Regs.setBitsNotInMask(MO.getRegMask()); 275 } 276 } 277 } 278 } 279 } 280 281 void llvm::calculateDbgEntityHistory(const MachineFunction *MF, 282 const TargetRegisterInfo *TRI, 283 DbgValueHistoryMap &DbgValues, 284 DbgLabelInstrMap &DbgLabels) { 285 BitVector ChangingRegs(TRI->getNumRegs()); 286 collectChangingRegs(MF, TRI, ChangingRegs); 287 288 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering(); 289 unsigned SP = TLI->getStackPointerRegisterToSaveRestore(); 290 unsigned FrameReg = TRI->getFrameRegister(*MF); 291 RegDescribedVarsMap RegVars; 292 DbgValueEntriesMap LiveEntries; 293 for (const auto &MBB : *MF) { 294 for (const auto &MI : MBB) { 295 if (!MI.isDebugInstr()) { 296 // Not a DBG_VALUE instruction. It may clobber registers which describe 297 // some variables. 298 for (const MachineOperand &MO : MI.operands()) { 299 if (MO.isReg() && MO.isDef() && MO.getReg()) { 300 // Ignore call instructions that claim to clobber SP. The AArch64 301 // backend does this for aggregate function arguments. 302 if (MI.isCall() && MO.getReg() == SP) 303 continue; 304 // If this is a virtual register, only clobber it since it doesn't 305 // have aliases. 306 if (TRI->isVirtualRegister(MO.getReg())) 307 clobberRegisterUses(RegVars, MO.getReg(), DbgValues, LiveEntries, 308 MI); 309 // If this is a register def operand, it may end a debug value 310 // range. 311 else { 312 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); 313 ++AI) 314 if (ChangingRegs.test(*AI)) 315 clobberRegisterUses(RegVars, *AI, DbgValues, LiveEntries, MI); 316 } 317 } else if (MO.isRegMask()) { 318 // If this is a register mask operand, clobber all debug values in 319 // non-CSRs. 320 for (unsigned I : ChangingRegs.set_bits()) { 321 // Don't consider SP to be clobbered by register masks. 322 if (unsigned(I) != SP && TRI->isPhysicalRegister(I) && 323 MO.clobbersPhysReg(I)) { 324 clobberRegisterUses(RegVars, I, DbgValues, LiveEntries, MI); 325 } 326 } 327 } 328 } 329 continue; 330 } 331 332 if (MI.isDebugValue()) { 333 assert(MI.getNumOperands() > 1 && "Invalid DBG_VALUE instruction!"); 334 // Use the base variable (without any DW_OP_piece expressions) 335 // as index into History. The full variables including the 336 // piece expressions are attached to the MI. 337 const DILocalVariable *RawVar = MI.getDebugVariable(); 338 assert(RawVar->isValidLocationForIntrinsic(MI.getDebugLoc()) && 339 "Expected inlined-at fields to agree"); 340 InlinedEntity Var(RawVar, MI.getDebugLoc()->getInlinedAt()); 341 342 handleNewDebugValue(Var, MI, RegVars, LiveEntries, DbgValues); 343 } else if (MI.isDebugLabel()) { 344 assert(MI.getNumOperands() == 1 && "Invalid DBG_LABEL instruction!"); 345 const DILabel *RawLabel = MI.getDebugLabel(); 346 assert(RawLabel->isValidLocationForIntrinsic(MI.getDebugLoc()) && 347 "Expected inlined-at fields to agree"); 348 // When collecting debug information for labels, there is no MCSymbol 349 // generated for it. So, we keep MachineInstr in DbgLabels in order 350 // to query MCSymbol afterward. 351 InlinedEntity L(RawLabel, MI.getDebugLoc()->getInlinedAt()); 352 DbgLabels.addInstr(L, MI); 353 } 354 } 355 356 // Make sure locations for register-described variables are valid only 357 // until the end of the basic block (unless it's the last basic block, in 358 // which case let their liveness run off to the end of the function). 359 if (!MBB.empty() && &MBB != &MF->back()) { 360 for (auto I = RegVars.begin(), E = RegVars.end(); I != E;) { 361 auto CurElem = I++; // CurElem can be erased below. 362 if (TRI->isVirtualRegister(CurElem->first) || 363 ChangingRegs.test(CurElem->first) || 364 CurElem->first == FrameReg) 365 clobberRegisterUses(RegVars, CurElem, DbgValues, LiveEntries, 366 MBB.back()); 367 } 368 } 369 } 370 } 371 372 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 373 LLVM_DUMP_METHOD void DbgValueHistoryMap::dump() const { 374 dbgs() << "DbgValueHistoryMap:\n"; 375 for (const auto &VarRangePair : *this) { 376 const InlinedEntity &Var = VarRangePair.first; 377 const Entries &Entries = VarRangePair.second; 378 379 const DILocalVariable *LocalVar = cast<DILocalVariable>(Var.first); 380 const DILocation *Location = Var.second; 381 382 dbgs() << " - " << LocalVar->getName() << " at "; 383 384 if (Location) 385 dbgs() << Location->getFilename() << ":" << Location->getLine() << ":" 386 << Location->getColumn(); 387 else 388 dbgs() << "<unknown location>"; 389 390 dbgs() << " --\n"; 391 392 for (const auto &E : enumerate(Entries)) { 393 const auto &Entry = E.value(); 394 dbgs() << " Entry[" << E.index() << "]: "; 395 if (Entry.isDbgValue()) 396 dbgs() << "Debug value\n"; 397 else 398 dbgs() << "Clobber\n"; 399 dbgs() << " Instr: " << *Entry.getInstr(); 400 if (Entry.isDbgValue()) { 401 if (Entry.getEndIndex() == NoEntry) 402 dbgs() << " - Valid until end of function\n"; 403 else 404 dbgs() << " - Closed by Entry[" << Entry.getEndIndex() << "]\n"; 405 } 406 dbgs() << "\n"; 407 } 408 } 409 } 410 #endif 411