1 //===- LiveDebugVariables.cpp - Tracking debug info variables -------------===// 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 // This file implements the LiveDebugVariables analysis. 10 // 11 // Remove all DBG_VALUE instructions referencing virtual registers and replace 12 // them with a data structure tracking where live user variables are kept - in a 13 // virtual register or in a stack slot. 14 // 15 // Allow the data structure to be updated during register allocation when values 16 // are moved between registers and stack slots. Finally emit new DBG_VALUE 17 // instructions after register allocation is complete. 18 // 19 //===----------------------------------------------------------------------===// 20 21 #include "LiveDebugVariables.h" 22 #include "llvm/ADT/ArrayRef.h" 23 #include "llvm/ADT/DenseMap.h" 24 #include "llvm/ADT/IntervalMap.h" 25 #include "llvm/ADT/MapVector.h" 26 #include "llvm/ADT/STLExtras.h" 27 #include "llvm/ADT/SmallSet.h" 28 #include "llvm/ADT/SmallVector.h" 29 #include "llvm/ADT/Statistic.h" 30 #include "llvm/ADT/StringRef.h" 31 #include "llvm/CodeGen/LexicalScopes.h" 32 #include "llvm/CodeGen/LiveInterval.h" 33 #include "llvm/CodeGen/LiveIntervals.h" 34 #include "llvm/CodeGen/MachineBasicBlock.h" 35 #include "llvm/CodeGen/MachineDominators.h" 36 #include "llvm/CodeGen/MachineFunction.h" 37 #include "llvm/CodeGen/MachineInstr.h" 38 #include "llvm/CodeGen/MachineInstrBuilder.h" 39 #include "llvm/CodeGen/MachineOperand.h" 40 #include "llvm/CodeGen/MachineRegisterInfo.h" 41 #include "llvm/CodeGen/SlotIndexes.h" 42 #include "llvm/CodeGen/TargetInstrInfo.h" 43 #include "llvm/CodeGen/TargetOpcodes.h" 44 #include "llvm/CodeGen/TargetRegisterInfo.h" 45 #include "llvm/CodeGen/TargetSubtargetInfo.h" 46 #include "llvm/CodeGen/VirtRegMap.h" 47 #include "llvm/Config/llvm-config.h" 48 #include "llvm/IR/DebugInfoMetadata.h" 49 #include "llvm/IR/DebugLoc.h" 50 #include "llvm/IR/Function.h" 51 #include "llvm/IR/Metadata.h" 52 #include "llvm/InitializePasses.h" 53 #include "llvm/MC/MCRegisterInfo.h" 54 #include "llvm/Pass.h" 55 #include "llvm/Support/Casting.h" 56 #include "llvm/Support/CommandLine.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/raw_ostream.h" 59 #include <algorithm> 60 #include <cassert> 61 #include <iterator> 62 #include <memory> 63 #include <utility> 64 65 using namespace llvm; 66 67 #define DEBUG_TYPE "livedebugvars" 68 69 static cl::opt<bool> 70 EnableLDV("live-debug-variables", cl::init(true), 71 cl::desc("Enable the live debug variables pass"), cl::Hidden); 72 73 STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted"); 74 STATISTIC(NumInsertedDebugLabels, "Number of DBG_LABELs inserted"); 75 76 char LiveDebugVariables::ID = 0; 77 78 INITIALIZE_PASS_BEGIN(LiveDebugVariables, DEBUG_TYPE, 79 "Debug Variable Analysis", false, false) 80 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 81 INITIALIZE_PASS_DEPENDENCY(LiveIntervals) 82 INITIALIZE_PASS_END(LiveDebugVariables, DEBUG_TYPE, 83 "Debug Variable Analysis", false, false) 84 85 void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const { 86 AU.addRequired<MachineDominatorTree>(); 87 AU.addRequiredTransitive<LiveIntervals>(); 88 AU.setPreservesAll(); 89 MachineFunctionPass::getAnalysisUsage(AU); 90 } 91 92 LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID) { 93 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry()); 94 } 95 96 enum : unsigned { UndefLocNo = ~0U }; 97 98 namespace { 99 /// Describes a debug variable value by location number and expression along 100 /// with some flags about the original usage of the location. 101 class DbgVariableValue { 102 public: 103 DbgVariableValue(ArrayRef<unsigned> NewLocs, bool WasIndirect, bool WasList, 104 const DIExpression &Expr) 105 : WasIndirect(WasIndirect), WasList(WasList), Expression(&Expr) { 106 assert(!(WasIndirect && WasList) && 107 "DBG_VALUE_LISTs should not be indirect."); 108 SmallVector<unsigned> LocNoVec; 109 for (unsigned LocNo : NewLocs) { 110 auto It = find(LocNoVec, LocNo); 111 if (It == LocNoVec.end()) 112 LocNoVec.push_back(LocNo); 113 else { 114 // Loc duplicates an element in LocNos; replace references to Op 115 // with references to the duplicating element. 116 unsigned OpIdx = LocNoVec.size(); 117 unsigned DuplicatingIdx = std::distance(LocNoVec.begin(), It); 118 Expression = 119 DIExpression::replaceArg(Expression, OpIdx, DuplicatingIdx); 120 } 121 } 122 // FIXME: Debug values referencing 64+ unique machine locations are rare and 123 // currently unsupported for performance reasons. If we can verify that 124 // performance is acceptable for such debug values, we can increase the 125 // bit-width of LocNoCount to 14 to enable up to 16384 unique machine 126 // locations. We will also need to verify that this does not cause issues 127 // with LiveDebugVariables' use of IntervalMap. 128 if (LocNoVec.size() < 64) { 129 LocNoCount = LocNoVec.size(); 130 if (LocNoCount > 0) { 131 LocNos = std::make_unique<unsigned[]>(LocNoCount); 132 std::copy(LocNoVec.begin(), LocNoVec.end(), loc_nos_begin()); 133 } 134 } else { 135 LLVM_DEBUG(dbgs() << "Found debug value with 64+ unique machine " 136 "locations, dropping...\n"); 137 LocNoCount = 1; 138 // Turn this into an undef debug value list; right now, the simplest form 139 // of this is an expression with one arg, and an undef debug operand. 140 Expression = 141 DIExpression::get(Expr.getContext(), {dwarf::DW_OP_LLVM_arg, 0, 142 dwarf::DW_OP_stack_value}); 143 if (auto FragmentInfoOpt = Expr.getFragmentInfo()) 144 Expression = *DIExpression::createFragmentExpression( 145 Expression, FragmentInfoOpt->OffsetInBits, 146 FragmentInfoOpt->SizeInBits); 147 LocNos = std::make_unique<unsigned[]>(LocNoCount); 148 LocNos[0] = UndefLocNo; 149 } 150 } 151 152 DbgVariableValue() : LocNoCount(0), WasIndirect(0), WasList(0) {} 153 DbgVariableValue(const DbgVariableValue &Other) 154 : LocNoCount(Other.LocNoCount), WasIndirect(Other.getWasIndirect()), 155 WasList(Other.getWasList()), Expression(Other.getExpression()) { 156 if (Other.getLocNoCount()) { 157 LocNos.reset(new unsigned[Other.getLocNoCount()]); 158 std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin()); 159 } 160 } 161 162 DbgVariableValue &operator=(const DbgVariableValue &Other) { 163 if (this == &Other) 164 return *this; 165 if (Other.getLocNoCount()) { 166 LocNos.reset(new unsigned[Other.getLocNoCount()]); 167 std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin()); 168 } else { 169 LocNos.release(); 170 } 171 LocNoCount = Other.getLocNoCount(); 172 WasIndirect = Other.getWasIndirect(); 173 WasList = Other.getWasList(); 174 Expression = Other.getExpression(); 175 return *this; 176 } 177 178 const DIExpression *getExpression() const { return Expression; } 179 uint8_t getLocNoCount() const { return LocNoCount; } 180 bool containsLocNo(unsigned LocNo) const { 181 return is_contained(loc_nos(), LocNo); 182 } 183 bool getWasIndirect() const { return WasIndirect; } 184 bool getWasList() const { return WasList; } 185 bool isUndef() const { return LocNoCount == 0 || containsLocNo(UndefLocNo); } 186 187 DbgVariableValue decrementLocNosAfterPivot(unsigned Pivot) const { 188 SmallVector<unsigned, 4> NewLocNos; 189 for (unsigned LocNo : loc_nos()) 190 NewLocNos.push_back(LocNo != UndefLocNo && LocNo > Pivot ? LocNo - 1 191 : LocNo); 192 return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression); 193 } 194 195 DbgVariableValue remapLocNos(ArrayRef<unsigned> LocNoMap) const { 196 SmallVector<unsigned> NewLocNos; 197 for (unsigned LocNo : loc_nos()) 198 // Undef values don't exist in locations (and thus not in LocNoMap 199 // either) so skip over them. See getLocationNo(). 200 NewLocNos.push_back(LocNo == UndefLocNo ? UndefLocNo : LocNoMap[LocNo]); 201 return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression); 202 } 203 204 DbgVariableValue changeLocNo(unsigned OldLocNo, unsigned NewLocNo) const { 205 SmallVector<unsigned> NewLocNos; 206 NewLocNos.assign(loc_nos_begin(), loc_nos_end()); 207 auto OldLocIt = find(NewLocNos, OldLocNo); 208 assert(OldLocIt != NewLocNos.end() && "Old location must be present."); 209 *OldLocIt = NewLocNo; 210 return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression); 211 } 212 213 bool hasLocNoGreaterThan(unsigned LocNo) const { 214 return any_of(loc_nos(), 215 [LocNo](unsigned ThisLocNo) { return ThisLocNo > LocNo; }); 216 } 217 218 void printLocNos(llvm::raw_ostream &OS) const { 219 for (const unsigned &Loc : loc_nos()) 220 OS << (&Loc == loc_nos_begin() ? " " : ", ") << Loc; 221 } 222 223 friend inline bool operator==(const DbgVariableValue &LHS, 224 const DbgVariableValue &RHS) { 225 if (std::tie(LHS.LocNoCount, LHS.WasIndirect, LHS.WasList, 226 LHS.Expression) != 227 std::tie(RHS.LocNoCount, RHS.WasIndirect, RHS.WasList, RHS.Expression)) 228 return false; 229 return std::equal(LHS.loc_nos_begin(), LHS.loc_nos_end(), 230 RHS.loc_nos_begin()); 231 } 232 233 friend inline bool operator!=(const DbgVariableValue &LHS, 234 const DbgVariableValue &RHS) { 235 return !(LHS == RHS); 236 } 237 238 unsigned *loc_nos_begin() { return LocNos.get(); } 239 const unsigned *loc_nos_begin() const { return LocNos.get(); } 240 unsigned *loc_nos_end() { return LocNos.get() + LocNoCount; } 241 const unsigned *loc_nos_end() const { return LocNos.get() + LocNoCount; } 242 ArrayRef<unsigned> loc_nos() const { 243 return ArrayRef<unsigned>(LocNos.get(), LocNoCount); 244 } 245 246 private: 247 // IntervalMap requires the value object to be very small, to the extent 248 // that we do not have enough room for an std::vector. Using a C-style array 249 // (with a unique_ptr wrapper for convenience) allows us to optimize for this 250 // specific case by packing the array size into only 6 bits (it is highly 251 // unlikely that any debug value will need 64+ locations). 252 std::unique_ptr<unsigned[]> LocNos; 253 uint8_t LocNoCount : 6; 254 bool WasIndirect : 1; 255 bool WasList : 1; 256 const DIExpression *Expression = nullptr; 257 }; 258 } // namespace 259 260 /// Map of where a user value is live to that value. 261 using LocMap = IntervalMap<SlotIndex, DbgVariableValue, 4>; 262 263 /// Map of stack slot offsets for spilled locations. 264 /// Non-spilled locations are not added to the map. 265 using SpillOffsetMap = DenseMap<unsigned, unsigned>; 266 267 /// Cache to save the location where it can be used as the starting 268 /// position as input for calling MachineBasicBlock::SkipPHIsLabelsAndDebug. 269 /// This is to prevent MachineBasicBlock::SkipPHIsLabelsAndDebug from 270 /// repeatedly searching the same set of PHIs/Labels/Debug instructions 271 /// if it is called many times for the same block. 272 using BlockSkipInstsMap = 273 DenseMap<MachineBasicBlock *, MachineBasicBlock::iterator>; 274 275 namespace { 276 277 class LDVImpl; 278 279 /// A user value is a part of a debug info user variable. 280 /// 281 /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register 282 /// holds part of a user variable. The part is identified by a byte offset. 283 /// 284 /// UserValues are grouped into equivalence classes for easier searching. Two 285 /// user values are related if they are held by the same virtual register. The 286 /// equivalence class is the transitive closure of that relation. 287 class UserValue { 288 const DILocalVariable *Variable; ///< The debug info variable we are part of. 289 /// The part of the variable we describe. 290 const Optional<DIExpression::FragmentInfo> Fragment; 291 DebugLoc dl; ///< The debug location for the variable. This is 292 ///< used by dwarf writer to find lexical scope. 293 UserValue *leader; ///< Equivalence class leader. 294 UserValue *next = nullptr; ///< Next value in equivalence class, or null. 295 296 /// Numbered locations referenced by locmap. 297 SmallVector<MachineOperand, 4> locations; 298 299 /// Map of slot indices where this value is live. 300 LocMap locInts; 301 302 /// Set of interval start indexes that have been trimmed to the 303 /// lexical scope. 304 SmallSet<SlotIndex, 2> trimmedDefs; 305 306 /// Insert a DBG_VALUE into MBB at Idx for DbgValue. 307 void insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx, 308 SlotIndex StopIdx, DbgVariableValue DbgValue, 309 ArrayRef<bool> LocSpills, 310 ArrayRef<unsigned> SpillOffsets, LiveIntervals &LIS, 311 const TargetInstrInfo &TII, 312 const TargetRegisterInfo &TRI, 313 BlockSkipInstsMap &BBSkipInstsMap); 314 315 /// Replace OldLocNo ranges with NewRegs ranges where NewRegs 316 /// is live. Returns true if any changes were made. 317 bool splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs, 318 LiveIntervals &LIS); 319 320 public: 321 /// Create a new UserValue. 322 UserValue(const DILocalVariable *var, 323 Optional<DIExpression::FragmentInfo> Fragment, DebugLoc L, 324 LocMap::Allocator &alloc) 325 : Variable(var), Fragment(Fragment), dl(std::move(L)), leader(this), 326 locInts(alloc) {} 327 328 /// Get the leader of this value's equivalence class. 329 UserValue *getLeader() { 330 UserValue *l = leader; 331 while (l != l->leader) 332 l = l->leader; 333 return leader = l; 334 } 335 336 /// Return the next UserValue in the equivalence class. 337 UserValue *getNext() const { return next; } 338 339 /// Merge equivalence classes. 340 static UserValue *merge(UserValue *L1, UserValue *L2) { 341 L2 = L2->getLeader(); 342 if (!L1) 343 return L2; 344 L1 = L1->getLeader(); 345 if (L1 == L2) 346 return L1; 347 // Splice L2 before L1's members. 348 UserValue *End = L2; 349 while (End->next) { 350 End->leader = L1; 351 End = End->next; 352 } 353 End->leader = L1; 354 End->next = L1->next; 355 L1->next = L2; 356 return L1; 357 } 358 359 /// Return the location number that matches Loc. 360 /// 361 /// For undef values we always return location number UndefLocNo without 362 /// inserting anything in locations. Since locations is a vector and the 363 /// location number is the position in the vector and UndefLocNo is ~0, 364 /// we would need a very big vector to put the value at the right position. 365 unsigned getLocationNo(const MachineOperand &LocMO) { 366 if (LocMO.isReg()) { 367 if (LocMO.getReg() == 0) 368 return UndefLocNo; 369 // For register locations we dont care about use/def and other flags. 370 for (unsigned i = 0, e = locations.size(); i != e; ++i) 371 if (locations[i].isReg() && 372 locations[i].getReg() == LocMO.getReg() && 373 locations[i].getSubReg() == LocMO.getSubReg()) 374 return i; 375 } else 376 for (unsigned i = 0, e = locations.size(); i != e; ++i) 377 if (LocMO.isIdenticalTo(locations[i])) 378 return i; 379 locations.push_back(LocMO); 380 // We are storing a MachineOperand outside a MachineInstr. 381 locations.back().clearParent(); 382 // Don't store def operands. 383 if (locations.back().isReg()) { 384 if (locations.back().isDef()) 385 locations.back().setIsDead(false); 386 locations.back().setIsUse(); 387 } 388 return locations.size() - 1; 389 } 390 391 /// Remove (recycle) a location number. If \p LocNo still is used by the 392 /// locInts nothing is done. 393 void removeLocationIfUnused(unsigned LocNo) { 394 // Bail out if LocNo still is used. 395 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) { 396 const DbgVariableValue &DbgValue = I.value(); 397 if (DbgValue.containsLocNo(LocNo)) 398 return; 399 } 400 // Remove the entry in the locations vector, and adjust all references to 401 // location numbers above the removed entry. 402 locations.erase(locations.begin() + LocNo); 403 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) { 404 const DbgVariableValue &DbgValue = I.value(); 405 if (DbgValue.hasLocNoGreaterThan(LocNo)) 406 I.setValueUnchecked(DbgValue.decrementLocNosAfterPivot(LocNo)); 407 } 408 } 409 410 /// Ensure that all virtual register locations are mapped. 411 void mapVirtRegs(LDVImpl *LDV); 412 413 /// Add a definition point to this user value. 414 void addDef(SlotIndex Idx, ArrayRef<MachineOperand> LocMOs, bool IsIndirect, 415 bool IsList, const DIExpression &Expr) { 416 SmallVector<unsigned> Locs; 417 for (MachineOperand Op : LocMOs) 418 Locs.push_back(getLocationNo(Op)); 419 DbgVariableValue DbgValue(Locs, IsIndirect, IsList, Expr); 420 // Add a singular (Idx,Idx) -> value mapping. 421 LocMap::iterator I = locInts.find(Idx); 422 if (!I.valid() || I.start() != Idx) 423 I.insert(Idx, Idx.getNextSlot(), std::move(DbgValue)); 424 else 425 // A later DBG_VALUE at the same SlotIndex overrides the old location. 426 I.setValue(std::move(DbgValue)); 427 } 428 429 /// Extend the current definition as far as possible down. 430 /// 431 /// Stop when meeting an existing def or when leaving the live 432 /// range of VNI. End points where VNI is no longer live are added to Kills. 433 /// 434 /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a 435 /// data-flow analysis to propagate them beyond basic block boundaries. 436 /// 437 /// \param Idx Starting point for the definition. 438 /// \param DbgValue value to propagate. 439 /// \param LiveIntervalInfo For each location number key in this map, 440 /// restricts liveness to where the LiveRange has the value equal to the\ 441 /// VNInfo. 442 /// \param [out] Kills Append end points of VNI's live range to Kills. 443 /// \param LIS Live intervals analysis. 444 void extendDef(SlotIndex Idx, DbgVariableValue DbgValue, 445 SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>> 446 &LiveIntervalInfo, 447 Optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills, 448 LiveIntervals &LIS); 449 450 /// The value in LI may be copies to other registers. Determine if 451 /// any of the copies are available at the kill points, and add defs if 452 /// possible. 453 /// 454 /// \param DbgValue Location number of LI->reg, and DIExpression. 455 /// \param LocIntervals Scan for copies of the value for each location in the 456 /// corresponding LiveInterval->reg. 457 /// \param KilledAt The point where the range of DbgValue could be extended. 458 /// \param [in,out] NewDefs Append (Idx, DbgValue) of inserted defs here. 459 void addDefsFromCopies( 460 DbgVariableValue DbgValue, 461 SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals, 462 SlotIndex KilledAt, 463 SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs, 464 MachineRegisterInfo &MRI, LiveIntervals &LIS); 465 466 /// Compute the live intervals of all locations after collecting all their 467 /// def points. 468 void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, 469 LiveIntervals &LIS, LexicalScopes &LS); 470 471 /// Replace OldReg ranges with NewRegs ranges where NewRegs is 472 /// live. Returns true if any changes were made. 473 bool splitRegister(Register OldReg, ArrayRef<Register> NewRegs, 474 LiveIntervals &LIS); 475 476 /// Rewrite virtual register locations according to the provided virtual 477 /// register map. Record the stack slot offsets for the locations that 478 /// were spilled. 479 void rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF, 480 const TargetInstrInfo &TII, 481 const TargetRegisterInfo &TRI, 482 SpillOffsetMap &SpillOffsets); 483 484 /// Recreate DBG_VALUE instruction from data structures. 485 void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS, 486 const TargetInstrInfo &TII, 487 const TargetRegisterInfo &TRI, 488 const SpillOffsetMap &SpillOffsets, 489 BlockSkipInstsMap &BBSkipInstsMap); 490 491 /// Return DebugLoc of this UserValue. 492 const DebugLoc &getDebugLoc() { return dl; } 493 494 void print(raw_ostream &, const TargetRegisterInfo *); 495 }; 496 497 /// A user label is a part of a debug info user label. 498 class UserLabel { 499 const DILabel *Label; ///< The debug info label we are part of. 500 DebugLoc dl; ///< The debug location for the label. This is 501 ///< used by dwarf writer to find lexical scope. 502 SlotIndex loc; ///< Slot used by the debug label. 503 504 /// Insert a DBG_LABEL into MBB at Idx. 505 void insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx, 506 LiveIntervals &LIS, const TargetInstrInfo &TII, 507 BlockSkipInstsMap &BBSkipInstsMap); 508 509 public: 510 /// Create a new UserLabel. 511 UserLabel(const DILabel *label, DebugLoc L, SlotIndex Idx) 512 : Label(label), dl(std::move(L)), loc(Idx) {} 513 514 /// Does this UserLabel match the parameters? 515 bool matches(const DILabel *L, const DILocation *IA, 516 const SlotIndex Index) const { 517 return Label == L && dl->getInlinedAt() == IA && loc == Index; 518 } 519 520 /// Recreate DBG_LABEL instruction from data structures. 521 void emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII, 522 BlockSkipInstsMap &BBSkipInstsMap); 523 524 /// Return DebugLoc of this UserLabel. 525 const DebugLoc &getDebugLoc() { return dl; } 526 527 void print(raw_ostream &, const TargetRegisterInfo *); 528 }; 529 530 /// Implementation of the LiveDebugVariables pass. 531 class LDVImpl { 532 LiveDebugVariables &pass; 533 LocMap::Allocator allocator; 534 MachineFunction *MF = nullptr; 535 LiveIntervals *LIS; 536 const TargetRegisterInfo *TRI; 537 538 using StashedInstrRef = 539 std::tuple<unsigned, unsigned, const DILocalVariable *, 540 const DIExpression *, DebugLoc>; 541 542 /// Position and VReg of a PHI instruction during register allocation. 543 struct PHIValPos { 544 SlotIndex SI; /// Slot where this PHI occurs. 545 Register Reg; /// VReg this PHI occurs in. 546 unsigned SubReg; /// Qualifiying subregister for Reg. 547 }; 548 549 /// Map from debug instruction number to PHI position during allocation. 550 std::map<unsigned, PHIValPos> PHIValToPos; 551 /// Index of, for each VReg, which debug instruction numbers and corresponding 552 /// PHIs are sensitive to splitting. Each VReg may have multiple PHI defs, 553 /// at different positions. 554 DenseMap<Register, std::vector<unsigned>> RegToPHIIdx; 555 556 std::map<SlotIndex, std::vector<StashedInstrRef>> StashedInstrReferences; 557 558 /// Whether emitDebugValues is called. 559 bool EmitDone = false; 560 561 /// Whether the machine function is modified during the pass. 562 bool ModifiedMF = false; 563 564 /// All allocated UserValue instances. 565 SmallVector<std::unique_ptr<UserValue>, 8> userValues; 566 567 /// All allocated UserLabel instances. 568 SmallVector<std::unique_ptr<UserLabel>, 2> userLabels; 569 570 /// Map virtual register to eq class leader. 571 using VRMap = DenseMap<unsigned, UserValue *>; 572 VRMap virtRegToEqClass; 573 574 /// Map to find existing UserValue instances. 575 using UVMap = DenseMap<DebugVariable, UserValue *>; 576 UVMap userVarMap; 577 578 /// Find or create a UserValue. 579 UserValue *getUserValue(const DILocalVariable *Var, 580 Optional<DIExpression::FragmentInfo> Fragment, 581 const DebugLoc &DL); 582 583 /// Find the EC leader for VirtReg or null. 584 UserValue *lookupVirtReg(Register VirtReg); 585 586 /// Add DBG_VALUE instruction to our maps. 587 /// 588 /// \param MI DBG_VALUE instruction 589 /// \param Idx Last valid SLotIndex before instruction. 590 /// 591 /// \returns True if the DBG_VALUE instruction should be deleted. 592 bool handleDebugValue(MachineInstr &MI, SlotIndex Idx); 593 594 /// Track a DBG_INSTR_REF. This needs to be removed from the MachineFunction 595 /// during regalloc -- but there's no need to maintain live ranges, as we 596 /// refer to a value rather than a location. 597 /// 598 /// \param MI DBG_INSTR_REF instruction 599 /// \param Idx Last valid SlotIndex before instruction 600 /// 601 /// \returns True if the DBG_VALUE instruction should be deleted. 602 bool handleDebugInstrRef(MachineInstr &MI, SlotIndex Idx); 603 604 /// Add DBG_LABEL instruction to UserLabel. 605 /// 606 /// \param MI DBG_LABEL instruction 607 /// \param Idx Last valid SlotIndex before instruction. 608 /// 609 /// \returns True if the DBG_LABEL instruction should be deleted. 610 bool handleDebugLabel(MachineInstr &MI, SlotIndex Idx); 611 612 /// Collect and erase all DBG_VALUE instructions, adding a UserValue def 613 /// for each instruction. 614 /// 615 /// \param mf MachineFunction to be scanned. 616 /// 617 /// \returns True if any debug values were found. 618 bool collectDebugValues(MachineFunction &mf); 619 620 /// Compute the live intervals of all user values after collecting all 621 /// their def points. 622 void computeIntervals(); 623 624 public: 625 LDVImpl(LiveDebugVariables *ps) : pass(*ps) {} 626 627 bool runOnMachineFunction(MachineFunction &mf); 628 629 /// Release all memory. 630 void clear() { 631 MF = nullptr; 632 PHIValToPos.clear(); 633 RegToPHIIdx.clear(); 634 StashedInstrReferences.clear(); 635 userValues.clear(); 636 userLabels.clear(); 637 virtRegToEqClass.clear(); 638 userVarMap.clear(); 639 // Make sure we call emitDebugValues if the machine function was modified. 640 assert((!ModifiedMF || EmitDone) && 641 "Dbg values are not emitted in LDV"); 642 EmitDone = false; 643 ModifiedMF = false; 644 } 645 646 /// Map virtual register to an equivalence class. 647 void mapVirtReg(Register VirtReg, UserValue *EC); 648 649 /// Replace any PHI referring to OldReg with its corresponding NewReg, if 650 /// present. 651 void splitPHIRegister(Register OldReg, ArrayRef<Register> NewRegs); 652 653 /// Replace all references to OldReg with NewRegs. 654 void splitRegister(Register OldReg, ArrayRef<Register> NewRegs); 655 656 /// Recreate DBG_VALUE instruction from data structures. 657 void emitDebugValues(VirtRegMap *VRM); 658 659 void print(raw_ostream&); 660 }; 661 662 } // end anonymous namespace 663 664 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 665 static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS, 666 const LLVMContext &Ctx) { 667 if (!DL) 668 return; 669 670 auto *Scope = cast<DIScope>(DL.getScope()); 671 // Omit the directory, because it's likely to be long and uninteresting. 672 CommentOS << Scope->getFilename(); 673 CommentOS << ':' << DL.getLine(); 674 if (DL.getCol() != 0) 675 CommentOS << ':' << DL.getCol(); 676 677 DebugLoc InlinedAtDL = DL.getInlinedAt(); 678 if (!InlinedAtDL) 679 return; 680 681 CommentOS << " @[ "; 682 printDebugLoc(InlinedAtDL, CommentOS, Ctx); 683 CommentOS << " ]"; 684 } 685 686 static void printExtendedName(raw_ostream &OS, const DINode *Node, 687 const DILocation *DL) { 688 const LLVMContext &Ctx = Node->getContext(); 689 StringRef Res; 690 unsigned Line = 0; 691 if (const auto *V = dyn_cast<const DILocalVariable>(Node)) { 692 Res = V->getName(); 693 Line = V->getLine(); 694 } else if (const auto *L = dyn_cast<const DILabel>(Node)) { 695 Res = L->getName(); 696 Line = L->getLine(); 697 } 698 699 if (!Res.empty()) 700 OS << Res << "," << Line; 701 auto *InlinedAt = DL ? DL->getInlinedAt() : nullptr; 702 if (InlinedAt) { 703 if (DebugLoc InlinedAtDL = InlinedAt) { 704 OS << " @["; 705 printDebugLoc(InlinedAtDL, OS, Ctx); 706 OS << "]"; 707 } 708 } 709 } 710 711 void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) { 712 OS << "!\""; 713 printExtendedName(OS, Variable, dl); 714 715 OS << "\"\t"; 716 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) { 717 OS << " [" << I.start() << ';' << I.stop() << "):"; 718 if (I.value().isUndef()) 719 OS << " undef"; 720 else { 721 I.value().printLocNos(OS); 722 if (I.value().getWasIndirect()) 723 OS << " ind"; 724 else if (I.value().getWasList()) 725 OS << " list"; 726 } 727 } 728 for (unsigned i = 0, e = locations.size(); i != e; ++i) { 729 OS << " Loc" << i << '='; 730 locations[i].print(OS, TRI); 731 } 732 OS << '\n'; 733 } 734 735 void UserLabel::print(raw_ostream &OS, const TargetRegisterInfo *TRI) { 736 OS << "!\""; 737 printExtendedName(OS, Label, dl); 738 739 OS << "\"\t"; 740 OS << loc; 741 OS << '\n'; 742 } 743 744 void LDVImpl::print(raw_ostream &OS) { 745 OS << "********** DEBUG VARIABLES **********\n"; 746 for (auto &userValue : userValues) 747 userValue->print(OS, TRI); 748 OS << "********** DEBUG LABELS **********\n"; 749 for (auto &userLabel : userLabels) 750 userLabel->print(OS, TRI); 751 } 752 #endif 753 754 void UserValue::mapVirtRegs(LDVImpl *LDV) { 755 for (unsigned i = 0, e = locations.size(); i != e; ++i) 756 if (locations[i].isReg() && 757 Register::isVirtualRegister(locations[i].getReg())) 758 LDV->mapVirtReg(locations[i].getReg(), this); 759 } 760 761 UserValue *LDVImpl::getUserValue(const DILocalVariable *Var, 762 Optional<DIExpression::FragmentInfo> Fragment, 763 const DebugLoc &DL) { 764 // FIXME: Handle partially overlapping fragments. See 765 // https://reviews.llvm.org/D70121#1849741. 766 DebugVariable ID(Var, Fragment, DL->getInlinedAt()); 767 UserValue *&UV = userVarMap[ID]; 768 if (!UV) { 769 userValues.push_back( 770 std::make_unique<UserValue>(Var, Fragment, DL, allocator)); 771 UV = userValues.back().get(); 772 } 773 return UV; 774 } 775 776 void LDVImpl::mapVirtReg(Register VirtReg, UserValue *EC) { 777 assert(Register::isVirtualRegister(VirtReg) && "Only map VirtRegs"); 778 UserValue *&Leader = virtRegToEqClass[VirtReg]; 779 Leader = UserValue::merge(Leader, EC); 780 } 781 782 UserValue *LDVImpl::lookupVirtReg(Register VirtReg) { 783 if (UserValue *UV = virtRegToEqClass.lookup(VirtReg)) 784 return UV->getLeader(); 785 return nullptr; 786 } 787 788 bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) { 789 // DBG_VALUE loc, offset, variable, expr 790 // DBG_VALUE_LIST variable, expr, locs... 791 if (!MI.isDebugValue()) { 792 LLVM_DEBUG(dbgs() << "Can't handle non-DBG_VALUE*: " << MI); 793 return false; 794 } 795 if (!MI.getDebugVariableOp().isMetadata()) { 796 LLVM_DEBUG(dbgs() << "Can't handle DBG_VALUE* with invalid variable: " 797 << MI); 798 return false; 799 } 800 if (MI.isNonListDebugValue() && 801 (MI.getNumOperands() != 4 || 802 !(MI.getDebugOffset().isImm() || MI.getDebugOffset().isReg()))) { 803 LLVM_DEBUG(dbgs() << "Can't handle malformed DBG_VALUE: " << MI); 804 return false; 805 } 806 807 // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual 808 // register that hasn't been defined yet. If we do not remove those here, then 809 // the re-insertion of the DBG_VALUE instruction after register allocation 810 // will be incorrect. 811 // TODO: If earlier passes are corrected to generate sane debug information 812 // (and if the machine verifier is improved to catch this), then these checks 813 // could be removed or replaced by asserts. 814 bool Discard = false; 815 for (const MachineOperand &Op : MI.debug_operands()) { 816 if (Op.isReg() && Register::isVirtualRegister(Op.getReg())) { 817 const Register Reg = Op.getReg(); 818 if (!LIS->hasInterval(Reg)) { 819 // The DBG_VALUE is described by a virtual register that does not have a 820 // live interval. Discard the DBG_VALUE. 821 Discard = true; 822 LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx 823 << " " << MI); 824 } else { 825 // The DBG_VALUE is only valid if either Reg is live out from Idx, or 826 // Reg is defined dead at Idx (where Idx is the slot index for the 827 // instruction preceding the DBG_VALUE). 828 const LiveInterval &LI = LIS->getInterval(Reg); 829 LiveQueryResult LRQ = LI.Query(Idx); 830 if (!LRQ.valueOutOrDead()) { 831 // We have found a DBG_VALUE with the value in a virtual register that 832 // is not live. Discard the DBG_VALUE. 833 Discard = true; 834 LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx 835 << " " << MI); 836 } 837 } 838 } 839 } 840 841 // Get or create the UserValue for (variable,offset) here. 842 bool IsIndirect = MI.isDebugOffsetImm(); 843 if (IsIndirect) 844 assert(MI.getDebugOffset().getImm() == 0 && 845 "DBG_VALUE with nonzero offset"); 846 bool IsList = MI.isDebugValueList(); 847 const DILocalVariable *Var = MI.getDebugVariable(); 848 const DIExpression *Expr = MI.getDebugExpression(); 849 UserValue *UV = getUserValue(Var, Expr->getFragmentInfo(), MI.getDebugLoc()); 850 if (!Discard) 851 UV->addDef(Idx, 852 ArrayRef<MachineOperand>(MI.debug_operands().begin(), 853 MI.debug_operands().end()), 854 IsIndirect, IsList, *Expr); 855 else { 856 MachineOperand MO = MachineOperand::CreateReg(0U, false); 857 MO.setIsDebug(); 858 // We should still pass a list the same size as MI.debug_operands() even if 859 // all MOs are undef, so that DbgVariableValue can correctly adjust the 860 // expression while removing the duplicated undefs. 861 SmallVector<MachineOperand, 4> UndefMOs(MI.getNumDebugOperands(), MO); 862 UV->addDef(Idx, UndefMOs, false, IsList, *Expr); 863 } 864 return true; 865 } 866 867 bool LDVImpl::handleDebugInstrRef(MachineInstr &MI, SlotIndex Idx) { 868 assert(MI.isDebugRef()); 869 unsigned InstrNum = MI.getOperand(0).getImm(); 870 unsigned OperandNum = MI.getOperand(1).getImm(); 871 auto *Var = MI.getDebugVariable(); 872 auto *Expr = MI.getDebugExpression(); 873 auto &DL = MI.getDebugLoc(); 874 StashedInstrRef Stashed = 875 std::make_tuple(InstrNum, OperandNum, Var, Expr, DL); 876 StashedInstrReferences[Idx].push_back(Stashed); 877 return true; 878 } 879 880 bool LDVImpl::handleDebugLabel(MachineInstr &MI, SlotIndex Idx) { 881 // DBG_LABEL label 882 if (MI.getNumOperands() != 1 || !MI.getOperand(0).isMetadata()) { 883 LLVM_DEBUG(dbgs() << "Can't handle " << MI); 884 return false; 885 } 886 887 // Get or create the UserLabel for label here. 888 const DILabel *Label = MI.getDebugLabel(); 889 const DebugLoc &DL = MI.getDebugLoc(); 890 bool Found = false; 891 for (auto const &L : userLabels) { 892 if (L->matches(Label, DL->getInlinedAt(), Idx)) { 893 Found = true; 894 break; 895 } 896 } 897 if (!Found) 898 userLabels.push_back(std::make_unique<UserLabel>(Label, DL, Idx)); 899 900 return true; 901 } 902 903 bool LDVImpl::collectDebugValues(MachineFunction &mf) { 904 bool Changed = false; 905 for (MachineBasicBlock &MBB : mf) { 906 for (MachineBasicBlock::iterator MBBI = MBB.begin(), MBBE = MBB.end(); 907 MBBI != MBBE;) { 908 // Use the first debug instruction in the sequence to get a SlotIndex 909 // for following consecutive debug instructions. 910 if (!MBBI->isDebugOrPseudoInstr()) { 911 ++MBBI; 912 continue; 913 } 914 // Debug instructions has no slot index. Use the previous 915 // non-debug instruction's SlotIndex as its SlotIndex. 916 SlotIndex Idx = 917 MBBI == MBB.begin() 918 ? LIS->getMBBStartIdx(&MBB) 919 : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot(); 920 // Handle consecutive debug instructions with the same slot index. 921 do { 922 // Only handle DBG_VALUE in handleDebugValue(). Skip all other 923 // kinds of debug instructions. 924 if ((MBBI->isDebugValue() && handleDebugValue(*MBBI, Idx)) || 925 (MBBI->isDebugRef() && handleDebugInstrRef(*MBBI, Idx)) || 926 (MBBI->isDebugLabel() && handleDebugLabel(*MBBI, Idx))) { 927 MBBI = MBB.erase(MBBI); 928 Changed = true; 929 } else 930 ++MBBI; 931 } while (MBBI != MBBE && MBBI->isDebugOrPseudoInstr()); 932 } 933 } 934 return Changed; 935 } 936 937 void UserValue::extendDef( 938 SlotIndex Idx, DbgVariableValue DbgValue, 939 SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>> 940 &LiveIntervalInfo, 941 Optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills, 942 LiveIntervals &LIS) { 943 SlotIndex Start = Idx; 944 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start); 945 SlotIndex Stop = LIS.getMBBEndIdx(MBB); 946 LocMap::iterator I = locInts.find(Start); 947 948 // Limit to the intersection of the VNIs' live ranges. 949 for (auto &LII : LiveIntervalInfo) { 950 LiveRange *LR = LII.second.first; 951 assert(LR && LII.second.second && "Missing range info for Idx."); 952 LiveInterval::Segment *Segment = LR->getSegmentContaining(Start); 953 assert(Segment && Segment->valno == LII.second.second && 954 "Invalid VNInfo for Idx given?"); 955 if (Segment->end < Stop) { 956 Stop = Segment->end; 957 Kills = {Stop, {LII.first}}; 958 } else if (Segment->end == Stop && Kills.hasValue()) { 959 // If multiple locations end at the same place, track all of them in 960 // Kills. 961 Kills->second.push_back(LII.first); 962 } 963 } 964 965 // There could already be a short def at Start. 966 if (I.valid() && I.start() <= Start) { 967 // Stop when meeting a different location or an already extended interval. 968 Start = Start.getNextSlot(); 969 if (I.value() != DbgValue || I.stop() != Start) { 970 // Clear `Kills`, as we have a new def available. 971 Kills = None; 972 return; 973 } 974 // This is a one-slot placeholder. Just skip it. 975 ++I; 976 } 977 978 // Limited by the next def. 979 if (I.valid() && I.start() < Stop) { 980 Stop = I.start(); 981 // Clear `Kills`, as we have a new def available. 982 Kills = None; 983 } 984 985 if (Start < Stop) { 986 DbgVariableValue ExtDbgValue(DbgValue); 987 I.insert(Start, Stop, std::move(ExtDbgValue)); 988 } 989 } 990 991 void UserValue::addDefsFromCopies( 992 DbgVariableValue DbgValue, 993 SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals, 994 SlotIndex KilledAt, 995 SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs, 996 MachineRegisterInfo &MRI, LiveIntervals &LIS) { 997 // Don't track copies from physregs, there are too many uses. 998 if (any_of(LocIntervals, [](auto LocI) { 999 return !Register::isVirtualRegister(LocI.second->reg()); 1000 })) 1001 return; 1002 1003 // Collect all the (vreg, valno) pairs that are copies of LI. 1004 SmallDenseMap<unsigned, 1005 SmallVector<std::pair<LiveInterval *, const VNInfo *>, 4>> 1006 CopyValues; 1007 for (auto &LocInterval : LocIntervals) { 1008 unsigned LocNo = LocInterval.first; 1009 LiveInterval *LI = LocInterval.second; 1010 for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg())) { 1011 MachineInstr *MI = MO.getParent(); 1012 // Copies of the full value. 1013 if (MO.getSubReg() || !MI->isCopy()) 1014 continue; 1015 Register DstReg = MI->getOperand(0).getReg(); 1016 1017 // Don't follow copies to physregs. These are usually setting up call 1018 // arguments, and the argument registers are always call clobbered. We are 1019 // better off in the source register which could be a callee-saved 1020 // register, or it could be spilled. 1021 if (!Register::isVirtualRegister(DstReg)) 1022 continue; 1023 1024 // Is the value extended to reach this copy? If not, another def may be 1025 // blocking it, or we are looking at a wrong value of LI. 1026 SlotIndex Idx = LIS.getInstructionIndex(*MI); 1027 LocMap::iterator I = locInts.find(Idx.getRegSlot(true)); 1028 if (!I.valid() || I.value() != DbgValue) 1029 continue; 1030 1031 if (!LIS.hasInterval(DstReg)) 1032 continue; 1033 LiveInterval *DstLI = &LIS.getInterval(DstReg); 1034 const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot()); 1035 assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value"); 1036 CopyValues[LocNo].push_back(std::make_pair(DstLI, DstVNI)); 1037 } 1038 } 1039 1040 if (CopyValues.empty()) 1041 return; 1042 1043 #if !defined(NDEBUG) 1044 for (auto &LocInterval : LocIntervals) 1045 LLVM_DEBUG(dbgs() << "Got " << CopyValues[LocInterval.first].size() 1046 << " copies of " << *LocInterval.second << '\n'); 1047 #endif 1048 1049 // Try to add defs of the copied values for the kill point. Check that there 1050 // isn't already a def at Idx. 1051 LocMap::iterator I = locInts.find(KilledAt); 1052 if (I.valid() && I.start() <= KilledAt) 1053 return; 1054 DbgVariableValue NewValue(DbgValue); 1055 for (auto &LocInterval : LocIntervals) { 1056 unsigned LocNo = LocInterval.first; 1057 bool FoundCopy = false; 1058 for (auto &LIAndVNI : CopyValues[LocNo]) { 1059 LiveInterval *DstLI = LIAndVNI.first; 1060 const VNInfo *DstVNI = LIAndVNI.second; 1061 if (DstLI->getVNInfoAt(KilledAt) != DstVNI) 1062 continue; 1063 LLVM_DEBUG(dbgs() << "Kill at " << KilledAt << " covered by valno #" 1064 << DstVNI->id << " in " << *DstLI << '\n'); 1065 MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def); 1066 assert(CopyMI && CopyMI->isCopy() && "Bad copy value"); 1067 unsigned NewLocNo = getLocationNo(CopyMI->getOperand(0)); 1068 NewValue = NewValue.changeLocNo(LocNo, NewLocNo); 1069 FoundCopy = true; 1070 break; 1071 } 1072 // If there are any killed locations we can't find a copy for, we can't 1073 // extend the variable value. 1074 if (!FoundCopy) 1075 return; 1076 } 1077 I.insert(KilledAt, KilledAt.getNextSlot(), NewValue); 1078 NewDefs.push_back(std::make_pair(KilledAt, NewValue)); 1079 } 1080 1081 void UserValue::computeIntervals(MachineRegisterInfo &MRI, 1082 const TargetRegisterInfo &TRI, 1083 LiveIntervals &LIS, LexicalScopes &LS) { 1084 SmallVector<std::pair<SlotIndex, DbgVariableValue>, 16> Defs; 1085 1086 // Collect all defs to be extended (Skipping undefs). 1087 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) 1088 if (!I.value().isUndef()) 1089 Defs.push_back(std::make_pair(I.start(), I.value())); 1090 1091 // Extend all defs, and possibly add new ones along the way. 1092 for (unsigned i = 0; i != Defs.size(); ++i) { 1093 SlotIndex Idx = Defs[i].first; 1094 DbgVariableValue DbgValue = Defs[i].second; 1095 SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>> LIs; 1096 SmallVector<const VNInfo *, 4> VNIs; 1097 bool ShouldExtendDef = false; 1098 for (unsigned LocNo : DbgValue.loc_nos()) { 1099 const MachineOperand &LocMO = locations[LocNo]; 1100 if (!LocMO.isReg() || !Register::isVirtualRegister(LocMO.getReg())) { 1101 ShouldExtendDef |= !LocMO.isReg(); 1102 continue; 1103 } 1104 ShouldExtendDef = true; 1105 LiveInterval *LI = nullptr; 1106 const VNInfo *VNI = nullptr; 1107 if (LIS.hasInterval(LocMO.getReg())) { 1108 LI = &LIS.getInterval(LocMO.getReg()); 1109 VNI = LI->getVNInfoAt(Idx); 1110 } 1111 if (LI && VNI) 1112 LIs[LocNo] = {LI, VNI}; 1113 } 1114 if (ShouldExtendDef) { 1115 Optional<std::pair<SlotIndex, SmallVector<unsigned>>> Kills; 1116 extendDef(Idx, DbgValue, LIs, Kills, LIS); 1117 1118 if (Kills) { 1119 SmallVector<std::pair<unsigned, LiveInterval *>, 2> KilledLocIntervals; 1120 bool AnySubreg = false; 1121 for (unsigned LocNo : Kills->second) { 1122 const MachineOperand &LocMO = this->locations[LocNo]; 1123 if (LocMO.getSubReg()) { 1124 AnySubreg = true; 1125 break; 1126 } 1127 LiveInterval *LI = &LIS.getInterval(LocMO.getReg()); 1128 KilledLocIntervals.push_back({LocNo, LI}); 1129 } 1130 1131 // FIXME: Handle sub-registers in addDefsFromCopies. The problem is that 1132 // if the original location for example is %vreg0:sub_hi, and we find a 1133 // full register copy in addDefsFromCopies (at the moment it only 1134 // handles full register copies), then we must add the sub1 sub-register 1135 // index to the new location. However, that is only possible if the new 1136 // virtual register is of the same regclass (or if there is an 1137 // equivalent sub-register in that regclass). For now, simply skip 1138 // handling copies if a sub-register is involved. 1139 if (!AnySubreg) 1140 addDefsFromCopies(DbgValue, KilledLocIntervals, Kills->first, Defs, 1141 MRI, LIS); 1142 } 1143 } 1144 1145 // For physregs, we only mark the start slot idx. DwarfDebug will see it 1146 // as if the DBG_VALUE is valid up until the end of the basic block, or 1147 // the next def of the physical register. So we do not need to extend the 1148 // range. It might actually happen that the DBG_VALUE is the last use of 1149 // the physical register (e.g. if this is an unused input argument to a 1150 // function). 1151 } 1152 1153 // The computed intervals may extend beyond the range of the debug 1154 // location's lexical scope. In this case, splitting of an interval 1155 // can result in an interval outside of the scope being created, 1156 // causing extra unnecessary DBG_VALUEs to be emitted. To prevent 1157 // this, trim the intervals to the lexical scope. 1158 1159 LexicalScope *Scope = LS.findLexicalScope(dl); 1160 if (!Scope) 1161 return; 1162 1163 SlotIndex PrevEnd; 1164 LocMap::iterator I = locInts.begin(); 1165 1166 // Iterate over the lexical scope ranges. Each time round the loop 1167 // we check the intervals for overlap with the end of the previous 1168 // range and the start of the next. The first range is handled as 1169 // a special case where there is no PrevEnd. 1170 for (const InsnRange &Range : Scope->getRanges()) { 1171 SlotIndex RStart = LIS.getInstructionIndex(*Range.first); 1172 SlotIndex REnd = LIS.getInstructionIndex(*Range.second); 1173 1174 // Variable locations at the first instruction of a block should be 1175 // based on the block's SlotIndex, not the first instruction's index. 1176 if (Range.first == Range.first->getParent()->begin()) 1177 RStart = LIS.getSlotIndexes()->getIndexBefore(*Range.first); 1178 1179 // At the start of each iteration I has been advanced so that 1180 // I.stop() >= PrevEnd. Check for overlap. 1181 if (PrevEnd && I.start() < PrevEnd) { 1182 SlotIndex IStop = I.stop(); 1183 DbgVariableValue DbgValue = I.value(); 1184 1185 // Stop overlaps previous end - trim the end of the interval to 1186 // the scope range. 1187 I.setStopUnchecked(PrevEnd); 1188 ++I; 1189 1190 // If the interval also overlaps the start of the "next" (i.e. 1191 // current) range create a new interval for the remainder (which 1192 // may be further trimmed). 1193 if (RStart < IStop) 1194 I.insert(RStart, IStop, DbgValue); 1195 } 1196 1197 // Advance I so that I.stop() >= RStart, and check for overlap. 1198 I.advanceTo(RStart); 1199 if (!I.valid()) 1200 return; 1201 1202 if (I.start() < RStart) { 1203 // Interval start overlaps range - trim to the scope range. 1204 I.setStartUnchecked(RStart); 1205 // Remember that this interval was trimmed. 1206 trimmedDefs.insert(RStart); 1207 } 1208 1209 // The end of a lexical scope range is the last instruction in the 1210 // range. To convert to an interval we need the index of the 1211 // instruction after it. 1212 REnd = REnd.getNextIndex(); 1213 1214 // Advance I to first interval outside current range. 1215 I.advanceTo(REnd); 1216 if (!I.valid()) 1217 return; 1218 1219 PrevEnd = REnd; 1220 } 1221 1222 // Check for overlap with end of final range. 1223 if (PrevEnd && I.start() < PrevEnd) 1224 I.setStopUnchecked(PrevEnd); 1225 } 1226 1227 void LDVImpl::computeIntervals() { 1228 LexicalScopes LS; 1229 LS.initialize(*MF); 1230 1231 for (unsigned i = 0, e = userValues.size(); i != e; ++i) { 1232 userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS); 1233 userValues[i]->mapVirtRegs(this); 1234 } 1235 } 1236 1237 bool LDVImpl::runOnMachineFunction(MachineFunction &mf) { 1238 clear(); 1239 MF = &mf; 1240 LIS = &pass.getAnalysis<LiveIntervals>(); 1241 TRI = mf.getSubtarget().getRegisterInfo(); 1242 LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: " 1243 << mf.getName() << " **********\n"); 1244 1245 bool Changed = collectDebugValues(mf); 1246 computeIntervals(); 1247 LLVM_DEBUG(print(dbgs())); 1248 1249 // Collect the set of VReg / SlotIndexs where PHIs occur; index the sensitive 1250 // VRegs too, for when we're notified of a range split. 1251 SlotIndexes *Slots = LIS->getSlotIndexes(); 1252 for (const auto &PHIIt : MF->DebugPHIPositions) { 1253 const MachineFunction::DebugPHIRegallocPos &Position = PHIIt.second; 1254 MachineBasicBlock *MBB = Position.MBB; 1255 Register Reg = Position.Reg; 1256 unsigned SubReg = Position.SubReg; 1257 SlotIndex SI = Slots->getMBBStartIdx(MBB); 1258 PHIValPos VP = {SI, Reg, SubReg}; 1259 PHIValToPos.insert(std::make_pair(PHIIt.first, VP)); 1260 RegToPHIIdx[Reg].push_back(PHIIt.first); 1261 } 1262 1263 ModifiedMF = Changed; 1264 return Changed; 1265 } 1266 1267 static void removeDebugInstrs(MachineFunction &mf) { 1268 for (MachineBasicBlock &MBB : mf) { 1269 for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) { 1270 if (!MBBI->isDebugInstr()) { 1271 ++MBBI; 1272 continue; 1273 } 1274 MBBI = MBB.erase(MBBI); 1275 } 1276 } 1277 } 1278 1279 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) { 1280 if (!EnableLDV) 1281 return false; 1282 if (!mf.getFunction().getSubprogram()) { 1283 removeDebugInstrs(mf); 1284 return false; 1285 } 1286 if (!pImpl) 1287 pImpl = new LDVImpl(this); 1288 return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf); 1289 } 1290 1291 void LiveDebugVariables::releaseMemory() { 1292 if (pImpl) 1293 static_cast<LDVImpl*>(pImpl)->clear(); 1294 } 1295 1296 LiveDebugVariables::~LiveDebugVariables() { 1297 if (pImpl) 1298 delete static_cast<LDVImpl*>(pImpl); 1299 } 1300 1301 //===----------------------------------------------------------------------===// 1302 // Live Range Splitting 1303 //===----------------------------------------------------------------------===// 1304 1305 bool 1306 UserValue::splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs, 1307 LiveIntervals& LIS) { 1308 LLVM_DEBUG({ 1309 dbgs() << "Splitting Loc" << OldLocNo << '\t'; 1310 print(dbgs(), nullptr); 1311 }); 1312 bool DidChange = false; 1313 LocMap::iterator LocMapI; 1314 LocMapI.setMap(locInts); 1315 for (unsigned i = 0; i != NewRegs.size(); ++i) { 1316 LiveInterval *LI = &LIS.getInterval(NewRegs[i]); 1317 if (LI->empty()) 1318 continue; 1319 1320 // Don't allocate the new LocNo until it is needed. 1321 unsigned NewLocNo = UndefLocNo; 1322 1323 // Iterate over the overlaps between locInts and LI. 1324 LocMapI.find(LI->beginIndex()); 1325 if (!LocMapI.valid()) 1326 continue; 1327 LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start()); 1328 LiveInterval::iterator LIE = LI->end(); 1329 while (LocMapI.valid() && LII != LIE) { 1330 // At this point, we know that LocMapI.stop() > LII->start. 1331 LII = LI->advanceTo(LII, LocMapI.start()); 1332 if (LII == LIE) 1333 break; 1334 1335 // Now LII->end > LocMapI.start(). Do we have an overlap? 1336 if (LocMapI.value().containsLocNo(OldLocNo) && 1337 LII->start < LocMapI.stop()) { 1338 // Overlapping correct location. Allocate NewLocNo now. 1339 if (NewLocNo == UndefLocNo) { 1340 MachineOperand MO = MachineOperand::CreateReg(LI->reg(), false); 1341 MO.setSubReg(locations[OldLocNo].getSubReg()); 1342 NewLocNo = getLocationNo(MO); 1343 DidChange = true; 1344 } 1345 1346 SlotIndex LStart = LocMapI.start(); 1347 SlotIndex LStop = LocMapI.stop(); 1348 DbgVariableValue OldDbgValue = LocMapI.value(); 1349 1350 // Trim LocMapI down to the LII overlap. 1351 if (LStart < LII->start) 1352 LocMapI.setStartUnchecked(LII->start); 1353 if (LStop > LII->end) 1354 LocMapI.setStopUnchecked(LII->end); 1355 1356 // Change the value in the overlap. This may trigger coalescing. 1357 LocMapI.setValue(OldDbgValue.changeLocNo(OldLocNo, NewLocNo)); 1358 1359 // Re-insert any removed OldDbgValue ranges. 1360 if (LStart < LocMapI.start()) { 1361 LocMapI.insert(LStart, LocMapI.start(), OldDbgValue); 1362 ++LocMapI; 1363 assert(LocMapI.valid() && "Unexpected coalescing"); 1364 } 1365 if (LStop > LocMapI.stop()) { 1366 ++LocMapI; 1367 LocMapI.insert(LII->end, LStop, OldDbgValue); 1368 --LocMapI; 1369 } 1370 } 1371 1372 // Advance to the next overlap. 1373 if (LII->end < LocMapI.stop()) { 1374 if (++LII == LIE) 1375 break; 1376 LocMapI.advanceTo(LII->start); 1377 } else { 1378 ++LocMapI; 1379 if (!LocMapI.valid()) 1380 break; 1381 LII = LI->advanceTo(LII, LocMapI.start()); 1382 } 1383 } 1384 } 1385 1386 // Finally, remove OldLocNo unless it is still used by some interval in the 1387 // locInts map. One case when OldLocNo still is in use is when the register 1388 // has been spilled. In such situations the spilled register is kept as a 1389 // location until rewriteLocations is called (VirtRegMap is mapping the old 1390 // register to the spill slot). So for a while we can have locations that map 1391 // to virtual registers that have been removed from both the MachineFunction 1392 // and from LiveIntervals. 1393 // 1394 // We may also just be using the location for a value with a different 1395 // expression. 1396 removeLocationIfUnused(OldLocNo); 1397 1398 LLVM_DEBUG({ 1399 dbgs() << "Split result: \t"; 1400 print(dbgs(), nullptr); 1401 }); 1402 return DidChange; 1403 } 1404 1405 bool 1406 UserValue::splitRegister(Register OldReg, ArrayRef<Register> NewRegs, 1407 LiveIntervals &LIS) { 1408 bool DidChange = false; 1409 // Split locations referring to OldReg. Iterate backwards so splitLocation can 1410 // safely erase unused locations. 1411 for (unsigned i = locations.size(); i ; --i) { 1412 unsigned LocNo = i-1; 1413 const MachineOperand *Loc = &locations[LocNo]; 1414 if (!Loc->isReg() || Loc->getReg() != OldReg) 1415 continue; 1416 DidChange |= splitLocation(LocNo, NewRegs, LIS); 1417 } 1418 return DidChange; 1419 } 1420 1421 void LDVImpl::splitPHIRegister(Register OldReg, ArrayRef<Register> NewRegs) { 1422 auto RegIt = RegToPHIIdx.find(OldReg); 1423 if (RegIt == RegToPHIIdx.end()) 1424 return; 1425 1426 std::vector<std::pair<Register, unsigned>> NewRegIdxes; 1427 // Iterate over all the debug instruction numbers affected by this split. 1428 for (unsigned InstrID : RegIt->second) { 1429 auto PHIIt = PHIValToPos.find(InstrID); 1430 assert(PHIIt != PHIValToPos.end()); 1431 const SlotIndex &Slot = PHIIt->second.SI; 1432 assert(OldReg == PHIIt->second.Reg); 1433 1434 // Find the new register that covers this position. 1435 for (auto NewReg : NewRegs) { 1436 const LiveInterval &LI = LIS->getInterval(NewReg); 1437 auto LII = LI.find(Slot); 1438 if (LII != LI.end() && LII->start <= Slot) { 1439 // This new register covers this PHI position, record this for indexing. 1440 NewRegIdxes.push_back(std::make_pair(NewReg, InstrID)); 1441 // Record that this value lives in a different VReg now. 1442 PHIIt->second.Reg = NewReg; 1443 break; 1444 } 1445 } 1446 1447 // If we do not find a new register covering this PHI, then register 1448 // allocation has dropped its location, for example because it's not live. 1449 // The old VReg will not be mapped to a physreg, and the instruction 1450 // number will have been optimized out. 1451 } 1452 1453 // Re-create register index using the new register numbers. 1454 RegToPHIIdx.erase(RegIt); 1455 for (auto &RegAndInstr : NewRegIdxes) 1456 RegToPHIIdx[RegAndInstr.first].push_back(RegAndInstr.second); 1457 } 1458 1459 void LDVImpl::splitRegister(Register OldReg, ArrayRef<Register> NewRegs) { 1460 // Consider whether this split range affects any PHI locations. 1461 splitPHIRegister(OldReg, NewRegs); 1462 1463 // Check whether any intervals mapped by a DBG_VALUE were split and need 1464 // updating. 1465 bool DidChange = false; 1466 for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext()) 1467 DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS); 1468 1469 if (!DidChange) 1470 return; 1471 1472 // Map all of the new virtual registers. 1473 UserValue *UV = lookupVirtReg(OldReg); 1474 for (unsigned i = 0; i != NewRegs.size(); ++i) 1475 mapVirtReg(NewRegs[i], UV); 1476 } 1477 1478 void LiveDebugVariables:: 1479 splitRegister(Register OldReg, ArrayRef<Register> NewRegs, LiveIntervals &LIS) { 1480 if (pImpl) 1481 static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs); 1482 } 1483 1484 void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF, 1485 const TargetInstrInfo &TII, 1486 const TargetRegisterInfo &TRI, 1487 SpillOffsetMap &SpillOffsets) { 1488 // Build a set of new locations with new numbers so we can coalesce our 1489 // IntervalMap if two vreg intervals collapse to the same physical location. 1490 // Use MapVector instead of SetVector because MapVector::insert returns the 1491 // position of the previously or newly inserted element. The boolean value 1492 // tracks if the location was produced by a spill. 1493 // FIXME: This will be problematic if we ever support direct and indirect 1494 // frame index locations, i.e. expressing both variables in memory and 1495 // 'int x, *px = &x'. The "spilled" bit must become part of the location. 1496 MapVector<MachineOperand, std::pair<bool, unsigned>> NewLocations; 1497 SmallVector<unsigned, 4> LocNoMap(locations.size()); 1498 for (unsigned I = 0, E = locations.size(); I != E; ++I) { 1499 bool Spilled = false; 1500 unsigned SpillOffset = 0; 1501 MachineOperand Loc = locations[I]; 1502 // Only virtual registers are rewritten. 1503 if (Loc.isReg() && Loc.getReg() && 1504 Register::isVirtualRegister(Loc.getReg())) { 1505 Register VirtReg = Loc.getReg(); 1506 if (VRM.isAssignedReg(VirtReg) && 1507 Register::isPhysicalRegister(VRM.getPhys(VirtReg))) { 1508 // This can create a %noreg operand in rare cases when the sub-register 1509 // index is no longer available. That means the user value is in a 1510 // non-existent sub-register, and %noreg is exactly what we want. 1511 Loc.substPhysReg(VRM.getPhys(VirtReg), TRI); 1512 } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) { 1513 // Retrieve the stack slot offset. 1514 unsigned SpillSize; 1515 const MachineRegisterInfo &MRI = MF.getRegInfo(); 1516 const TargetRegisterClass *TRC = MRI.getRegClass(VirtReg); 1517 bool Success = TII.getStackSlotRange(TRC, Loc.getSubReg(), SpillSize, 1518 SpillOffset, MF); 1519 1520 // FIXME: Invalidate the location if the offset couldn't be calculated. 1521 (void)Success; 1522 1523 Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg)); 1524 Spilled = true; 1525 } else { 1526 Loc.setReg(0); 1527 Loc.setSubReg(0); 1528 } 1529 } 1530 1531 // Insert this location if it doesn't already exist and record a mapping 1532 // from the old number to the new number. 1533 auto InsertResult = NewLocations.insert({Loc, {Spilled, SpillOffset}}); 1534 unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first); 1535 LocNoMap[I] = NewLocNo; 1536 } 1537 1538 // Rewrite the locations and record the stack slot offsets for spills. 1539 locations.clear(); 1540 SpillOffsets.clear(); 1541 for (auto &Pair : NewLocations) { 1542 bool Spilled; 1543 unsigned SpillOffset; 1544 std::tie(Spilled, SpillOffset) = Pair.second; 1545 locations.push_back(Pair.first); 1546 if (Spilled) { 1547 unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair); 1548 SpillOffsets[NewLocNo] = SpillOffset; 1549 } 1550 } 1551 1552 // Update the interval map, but only coalesce left, since intervals to the 1553 // right use the old location numbers. This should merge two contiguous 1554 // DBG_VALUE intervals with different vregs that were allocated to the same 1555 // physical register. 1556 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) { 1557 I.setValueUnchecked(I.value().remapLocNos(LocNoMap)); 1558 I.setStart(I.start()); 1559 } 1560 } 1561 1562 /// Find an iterator for inserting a DBG_VALUE instruction. 1563 static MachineBasicBlock::iterator 1564 findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx, LiveIntervals &LIS, 1565 BlockSkipInstsMap &BBSkipInstsMap) { 1566 SlotIndex Start = LIS.getMBBStartIdx(MBB); 1567 Idx = Idx.getBaseIndex(); 1568 1569 // Try to find an insert location by going backwards from Idx. 1570 MachineInstr *MI; 1571 while (!(MI = LIS.getInstructionFromIndex(Idx))) { 1572 // We've reached the beginning of MBB. 1573 if (Idx == Start) { 1574 // Retrieve the last PHI/Label/Debug location found when calling 1575 // SkipPHIsLabelsAndDebug last time. Start searching from there. 1576 // 1577 // Note the iterator kept in BBSkipInstsMap is one step back based 1578 // on the iterator returned by SkipPHIsLabelsAndDebug last time. 1579 // One exception is when SkipPHIsLabelsAndDebug returns MBB->begin(), 1580 // BBSkipInstsMap won't save it. This is to consider the case that 1581 // new instructions may be inserted at the beginning of MBB after 1582 // last call of SkipPHIsLabelsAndDebug. If we save MBB->begin() in 1583 // BBSkipInstsMap, after new non-phi/non-label/non-debug instructions 1584 // are inserted at the beginning of the MBB, the iterator in 1585 // BBSkipInstsMap won't point to the beginning of the MBB anymore. 1586 // Therefore The next search in SkipPHIsLabelsAndDebug will skip those 1587 // newly added instructions and that is unwanted. 1588 MachineBasicBlock::iterator BeginIt; 1589 auto MapIt = BBSkipInstsMap.find(MBB); 1590 if (MapIt == BBSkipInstsMap.end()) 1591 BeginIt = MBB->begin(); 1592 else 1593 BeginIt = std::next(MapIt->second); 1594 auto I = MBB->SkipPHIsLabelsAndDebug(BeginIt); 1595 if (I != BeginIt) 1596 BBSkipInstsMap[MBB] = std::prev(I); 1597 return I; 1598 } 1599 Idx = Idx.getPrevIndex(); 1600 } 1601 1602 // Don't insert anything after the first terminator, though. 1603 return MI->isTerminator() ? MBB->getFirstTerminator() : 1604 std::next(MachineBasicBlock::iterator(MI)); 1605 } 1606 1607 /// Find an iterator for inserting the next DBG_VALUE instruction 1608 /// (or end if no more insert locations found). 1609 static MachineBasicBlock::iterator 1610 findNextInsertLocation(MachineBasicBlock *MBB, MachineBasicBlock::iterator I, 1611 SlotIndex StopIdx, ArrayRef<MachineOperand> LocMOs, 1612 LiveIntervals &LIS, const TargetRegisterInfo &TRI) { 1613 SmallVector<Register, 4> Regs; 1614 for (const MachineOperand &LocMO : LocMOs) 1615 if (LocMO.isReg()) 1616 Regs.push_back(LocMO.getReg()); 1617 if (Regs.empty()) 1618 return MBB->instr_end(); 1619 1620 // Find the next instruction in the MBB that define the register Reg. 1621 while (I != MBB->end() && !I->isTerminator()) { 1622 if (!LIS.isNotInMIMap(*I) && 1623 SlotIndex::isEarlierEqualInstr(StopIdx, LIS.getInstructionIndex(*I))) 1624 break; 1625 if (any_of(Regs, [&I, &TRI](Register &Reg) { 1626 return I->definesRegister(Reg, &TRI); 1627 })) 1628 // The insert location is directly after the instruction/bundle. 1629 return std::next(I); 1630 ++I; 1631 } 1632 return MBB->end(); 1633 } 1634 1635 void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx, 1636 SlotIndex StopIdx, DbgVariableValue DbgValue, 1637 ArrayRef<bool> LocSpills, 1638 ArrayRef<unsigned> SpillOffsets, 1639 LiveIntervals &LIS, const TargetInstrInfo &TII, 1640 const TargetRegisterInfo &TRI, 1641 BlockSkipInstsMap &BBSkipInstsMap) { 1642 SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB); 1643 // Only search within the current MBB. 1644 StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx; 1645 MachineBasicBlock::iterator I = 1646 findInsertLocation(MBB, StartIdx, LIS, BBSkipInstsMap); 1647 // Undef values don't exist in locations so create new "noreg" register MOs 1648 // for them. See getLocationNo(). 1649 SmallVector<MachineOperand, 8> MOs; 1650 if (DbgValue.isUndef()) { 1651 MOs.assign(DbgValue.loc_nos().size(), 1652 MachineOperand::CreateReg( 1653 /* Reg */ 0, /* isDef */ false, /* isImp */ false, 1654 /* isKill */ false, /* isDead */ false, 1655 /* isUndef */ false, /* isEarlyClobber */ false, 1656 /* SubReg */ 0, /* isDebug */ true)); 1657 } else { 1658 for (unsigned LocNo : DbgValue.loc_nos()) 1659 MOs.push_back(locations[LocNo]); 1660 } 1661 1662 ++NumInsertedDebugValues; 1663 1664 assert(cast<DILocalVariable>(Variable) 1665 ->isValidLocationForIntrinsic(getDebugLoc()) && 1666 "Expected inlined-at fields to agree"); 1667 1668 // If the location was spilled, the new DBG_VALUE will be indirect. If the 1669 // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate 1670 // that the original virtual register was a pointer. Also, add the stack slot 1671 // offset for the spilled register to the expression. 1672 const DIExpression *Expr = DbgValue.getExpression(); 1673 bool IsIndirect = DbgValue.getWasIndirect(); 1674 bool IsList = DbgValue.getWasList(); 1675 for (unsigned I = 0, E = LocSpills.size(); I != E; ++I) { 1676 if (LocSpills[I]) { 1677 if (!IsList) { 1678 uint8_t DIExprFlags = DIExpression::ApplyOffset; 1679 if (IsIndirect) 1680 DIExprFlags |= DIExpression::DerefAfter; 1681 Expr = DIExpression::prepend(Expr, DIExprFlags, SpillOffsets[I]); 1682 IsIndirect = true; 1683 } else { 1684 SmallVector<uint64_t, 4> Ops; 1685 DIExpression::appendOffset(Ops, SpillOffsets[I]); 1686 Ops.push_back(dwarf::DW_OP_deref); 1687 Expr = DIExpression::appendOpsToArg(Expr, Ops, I); 1688 } 1689 } 1690 1691 assert((!LocSpills[I] || MOs[I].isFI()) && 1692 "a spilled location must be a frame index"); 1693 } 1694 1695 unsigned DbgValueOpcode = 1696 IsList ? TargetOpcode::DBG_VALUE_LIST : TargetOpcode::DBG_VALUE; 1697 do { 1698 BuildMI(*MBB, I, getDebugLoc(), TII.get(DbgValueOpcode), IsIndirect, MOs, 1699 Variable, Expr); 1700 1701 // Continue and insert DBG_VALUES after every redefinition of a register 1702 // associated with the debug value within the range 1703 I = findNextInsertLocation(MBB, I, StopIdx, MOs, LIS, TRI); 1704 } while (I != MBB->end()); 1705 } 1706 1707 void UserLabel::insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx, 1708 LiveIntervals &LIS, const TargetInstrInfo &TII, 1709 BlockSkipInstsMap &BBSkipInstsMap) { 1710 MachineBasicBlock::iterator I = 1711 findInsertLocation(MBB, Idx, LIS, BBSkipInstsMap); 1712 ++NumInsertedDebugLabels; 1713 BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_LABEL)) 1714 .addMetadata(Label); 1715 } 1716 1717 void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS, 1718 const TargetInstrInfo &TII, 1719 const TargetRegisterInfo &TRI, 1720 const SpillOffsetMap &SpillOffsets, 1721 BlockSkipInstsMap &BBSkipInstsMap) { 1722 MachineFunction::iterator MFEnd = VRM->getMachineFunction().end(); 1723 1724 for (LocMap::const_iterator I = locInts.begin(); I.valid();) { 1725 SlotIndex Start = I.start(); 1726 SlotIndex Stop = I.stop(); 1727 DbgVariableValue DbgValue = I.value(); 1728 1729 SmallVector<bool> SpilledLocs; 1730 SmallVector<unsigned> LocSpillOffsets; 1731 for (unsigned LocNo : DbgValue.loc_nos()) { 1732 auto SpillIt = 1733 !DbgValue.isUndef() ? SpillOffsets.find(LocNo) : SpillOffsets.end(); 1734 bool Spilled = SpillIt != SpillOffsets.end(); 1735 SpilledLocs.push_back(Spilled); 1736 LocSpillOffsets.push_back(Spilled ? SpillIt->second : 0); 1737 } 1738 1739 // If the interval start was trimmed to the lexical scope insert the 1740 // DBG_VALUE at the previous index (otherwise it appears after the 1741 // first instruction in the range). 1742 if (trimmedDefs.count(Start)) 1743 Start = Start.getPrevIndex(); 1744 1745 LLVM_DEBUG(auto &dbg = dbgs(); dbg << "\t[" << Start << ';' << Stop << "):"; 1746 DbgValue.printLocNos(dbg)); 1747 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator(); 1748 SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB); 1749 1750 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd); 1751 insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs, LocSpillOffsets, 1752 LIS, TII, TRI, BBSkipInstsMap); 1753 // This interval may span multiple basic blocks. 1754 // Insert a DBG_VALUE into each one. 1755 while (Stop > MBBEnd) { 1756 // Move to the next block. 1757 Start = MBBEnd; 1758 if (++MBB == MFEnd) 1759 break; 1760 MBBEnd = LIS.getMBBEndIdx(&*MBB); 1761 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd); 1762 insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs, 1763 LocSpillOffsets, LIS, TII, TRI, BBSkipInstsMap); 1764 } 1765 LLVM_DEBUG(dbgs() << '\n'); 1766 if (MBB == MFEnd) 1767 break; 1768 1769 ++I; 1770 } 1771 } 1772 1773 void UserLabel::emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII, 1774 BlockSkipInstsMap &BBSkipInstsMap) { 1775 LLVM_DEBUG(dbgs() << "\t" << loc); 1776 MachineFunction::iterator MBB = LIS.getMBBFromIndex(loc)->getIterator(); 1777 1778 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB)); 1779 insertDebugLabel(&*MBB, loc, LIS, TII, BBSkipInstsMap); 1780 1781 LLVM_DEBUG(dbgs() << '\n'); 1782 } 1783 1784 void LDVImpl::emitDebugValues(VirtRegMap *VRM) { 1785 LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n"); 1786 if (!MF) 1787 return; 1788 1789 BlockSkipInstsMap BBSkipInstsMap; 1790 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 1791 SpillOffsetMap SpillOffsets; 1792 for (auto &userValue : userValues) { 1793 LLVM_DEBUG(userValue->print(dbgs(), TRI)); 1794 userValue->rewriteLocations(*VRM, *MF, *TII, *TRI, SpillOffsets); 1795 userValue->emitDebugValues(VRM, *LIS, *TII, *TRI, SpillOffsets, 1796 BBSkipInstsMap); 1797 } 1798 LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG LABELS **********\n"); 1799 for (auto &userLabel : userLabels) { 1800 LLVM_DEBUG(userLabel->print(dbgs(), TRI)); 1801 userLabel->emitDebugLabel(*LIS, *TII, BBSkipInstsMap); 1802 } 1803 1804 LLVM_DEBUG(dbgs() << "********** EMITTING DEBUG PHIS **********\n"); 1805 1806 auto Slots = LIS->getSlotIndexes(); 1807 for (auto &It : PHIValToPos) { 1808 // For each ex-PHI, identify its physreg location or stack slot, and emit 1809 // a DBG_PHI for it. 1810 unsigned InstNum = It.first; 1811 auto Slot = It.second.SI; 1812 Register Reg = It.second.Reg; 1813 unsigned SubReg = It.second.SubReg; 1814 1815 MachineBasicBlock *OrigMBB = Slots->getMBBFromIndex(Slot); 1816 if (VRM->isAssignedReg(Reg) && 1817 Register::isPhysicalRegister(VRM->getPhys(Reg))) { 1818 unsigned PhysReg = VRM->getPhys(Reg); 1819 if (SubReg != 0) 1820 PhysReg = TRI->getSubReg(PhysReg, SubReg); 1821 1822 auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(), 1823 TII->get(TargetOpcode::DBG_PHI)); 1824 Builder.addReg(PhysReg); 1825 Builder.addImm(InstNum); 1826 } else if (VRM->getStackSlot(Reg) != VirtRegMap::NO_STACK_SLOT) { 1827 const MachineRegisterInfo &MRI = MF->getRegInfo(); 1828 const TargetRegisterClass *TRC = MRI.getRegClass(Reg); 1829 unsigned SpillSize, SpillOffset; 1830 1831 // Test whether this location is legal with the given subreg. 1832 bool Success = 1833 TII->getStackSlotRange(TRC, SubReg, SpillSize, SpillOffset, *MF); 1834 1835 if (Success) { 1836 auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(), 1837 TII->get(TargetOpcode::DBG_PHI)); 1838 Builder.addFrameIndex(VRM->getStackSlot(Reg)); 1839 Builder.addImm(InstNum); 1840 } 1841 } 1842 // If there was no mapping for a value ID, it's optimized out. Create no 1843 // DBG_PHI, and any variables using this value will become optimized out. 1844 } 1845 MF->DebugPHIPositions.clear(); 1846 1847 LLVM_DEBUG(dbgs() << "********** EMITTING INSTR REFERENCES **********\n"); 1848 1849 // Re-insert any DBG_INSTR_REFs back in the position they were. Ordering 1850 // is preserved by vector. 1851 const MCInstrDesc &RefII = TII->get(TargetOpcode::DBG_INSTR_REF); 1852 for (auto &P : StashedInstrReferences) { 1853 const SlotIndex &Idx = P.first; 1854 auto *MBB = Slots->getMBBFromIndex(Idx); 1855 MachineBasicBlock::iterator insertPos = 1856 findInsertLocation(MBB, Idx, *LIS, BBSkipInstsMap); 1857 for (auto &Stashed : P.second) { 1858 auto MIB = BuildMI(*MF, std::get<4>(Stashed), RefII); 1859 MIB.addImm(std::get<0>(Stashed)); 1860 MIB.addImm(std::get<1>(Stashed)); 1861 MIB.addMetadata(std::get<2>(Stashed)); 1862 MIB.addMetadata(std::get<3>(Stashed)); 1863 MachineInstr *New = MIB; 1864 MBB->insert(insertPos, New); 1865 } 1866 } 1867 1868 EmitDone = true; 1869 BBSkipInstsMap.clear(); 1870 } 1871 1872 void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) { 1873 if (pImpl) 1874 static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM); 1875 } 1876 1877 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1878 LLVM_DUMP_METHOD void LiveDebugVariables::dump() const { 1879 if (pImpl) 1880 static_cast<LDVImpl*>(pImpl)->print(dbgs()); 1881 } 1882 #endif 1883