LLVM 24.0.0git
LiveDebugVariables.cpp
Go to the documentation of this file.
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
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/MapVector.h"
26#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/SmallSet.h"
29#include "llvm/ADT/Statistic.h"
30#include "llvm/ADT/StringRef.h"
48#include "llvm/Config/llvm-config.h"
50#include "llvm/IR/DebugLoc.h"
51#include "llvm/IR/Function.h"
53#include "llvm/Pass.h"
56#include "llvm/Support/Debug.h"
58#include <algorithm>
59#include <cassert>
60#include <iterator>
61#include <map>
62#include <memory>
63#include <optional>
64#include <utility>
65
66using namespace llvm;
67
68#define DEBUG_TYPE "livedebugvars"
69
70static cl::opt<bool>
71EnableLDV("live-debug-variables", cl::init(true),
72 cl::desc("Enable the live debug variables pass"), cl::Hidden);
73
74STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
75STATISTIC(NumInsertedDebugLabels, "Number of DBG_LABELs inserted");
76STATISTIC(NumStaleIndexes, "Number of stale SlotIndexes repaired");
77STATISTIC(NumMergedIntervals,
78 "Number of debug value intervals merged while repairing indexes");
79
81
83 "Debug Variable Analysis", false, false)
86 "Debug Variable Analysis", false, true)
87
89 AnalysisUsage &AU) const {
90 AU.addRequiredTransitive<LiveIntervalsWrapperPass>();
91 AU.setPreservesAll();
93}
94
97
98enum : unsigned { UndefLocNo = ~0U };
99
100namespace {
101/// Describes a debug variable value by location number and expression along
102/// with some flags about the original usage of the location.
103class DbgVariableValue {
104public:
105 DbgVariableValue(ArrayRef<unsigned> NewLocs, bool WasIndirect, bool WasList,
106 const DIExpression &Expr)
107 : WasIndirect(WasIndirect), WasList(WasList), Expression(&Expr) {
108 assert(!(WasIndirect && WasList) &&
109 "DBG_VALUE_LISTs should not be indirect.");
110 SmallVector<unsigned> LocNoVec;
111 for (unsigned LocNo : NewLocs) {
112 auto It = find(LocNoVec, LocNo);
113 if (It == LocNoVec.end())
114 LocNoVec.push_back(LocNo);
115 else {
116 // Loc duplicates an element in LocNos; replace references to Op
117 // with references to the duplicating element.
118 unsigned OpIdx = LocNoVec.size();
119 unsigned DuplicatingIdx = std::distance(LocNoVec.begin(), It);
120 Expression =
121 DIExpression::replaceArg(Expression, OpIdx, DuplicatingIdx);
122 }
123 }
124 // FIXME: Debug values referencing 64+ unique machine locations are rare and
125 // currently unsupported for performance reasons. If we can verify that
126 // performance is acceptable for such debug values, we can increase the
127 // bit-width of LocNoCount to 14 to enable up to 16384 unique machine
128 // locations. We will also need to verify that this does not cause issues
129 // with LiveDebugVariables' use of IntervalMap.
130 if (LocNoVec.size() < 64) {
131 LocNoCount = LocNoVec.size();
132 if (LocNoCount > 0) {
133 LocNos = std::make_unique<unsigned[]>(LocNoCount);
134 llvm::copy(LocNoVec, loc_nos_begin());
135 }
136 } else {
137 LLVM_DEBUG(dbgs() << "Found debug value with 64+ unique machine "
138 "locations, dropping...\n");
139 LocNoCount = 1;
140 // Turn this into an undef debug value list; right now, the simplest form
141 // of this is an expression with one arg, and an undef debug operand.
142 Expression =
143 DIExpression::get(Expr.getContext(), {dwarf::DW_OP_LLVM_arg, 0});
144 if (auto FragmentInfoOpt = Expr.getFragmentInfo())
146 Expression, FragmentInfoOpt->OffsetInBits,
147 FragmentInfoOpt->SizeInBits);
148 LocNos = std::make_unique<unsigned[]>(LocNoCount);
149 LocNos[0] = UndefLocNo;
150 }
151 }
152
153 DbgVariableValue() : LocNoCount(0), WasIndirect(false), WasList(false) {}
154 DbgVariableValue(const DbgVariableValue &Other)
155 : LocNoCount(Other.LocNoCount), WasIndirect(Other.getWasIndirect()),
156 WasList(Other.getWasList()), Expression(Other.getExpression()) {
157 if (Other.getLocNoCount()) {
158 LocNos.reset(new unsigned[Other.getLocNoCount()]);
159 std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin());
160 }
161 }
162
163 DbgVariableValue &operator=(const DbgVariableValue &Other) {
164 if (this == &Other)
165 return *this;
166 if (Other.getLocNoCount()) {
167 LocNos.reset(new unsigned[Other.getLocNoCount()]);
168 std::copy(Other.loc_nos_begin(), Other.loc_nos_end(), loc_nos_begin());
169 } else {
170 LocNos.release();
171 }
172 LocNoCount = Other.getLocNoCount();
173 WasIndirect = Other.getWasIndirect();
174 WasList = Other.getWasList();
175 Expression = Other.getExpression();
176 return *this;
177 }
178
179 const DIExpression *getExpression() const { return Expression; }
180 uint8_t getLocNoCount() const { return LocNoCount; }
181 bool containsLocNo(unsigned LocNo) const {
182 return is_contained(loc_nos(), LocNo);
183 }
184 bool getWasIndirect() const { return WasIndirect; }
185 bool getWasList() const { return WasList; }
186 bool isUndef() const { return LocNoCount == 0 || containsLocNo(UndefLocNo); }
187
188 DbgVariableValue decrementLocNosAfterPivot(unsigned Pivot) const {
189 SmallVector<unsigned, 4> NewLocNos;
190 for (unsigned LocNo : loc_nos())
191 NewLocNos.push_back(LocNo != UndefLocNo && LocNo > Pivot ? LocNo - 1
192 : LocNo);
193 return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
194 }
195
196 DbgVariableValue remapLocNos(ArrayRef<unsigned> LocNoMap) const {
197 SmallVector<unsigned> NewLocNos;
198 for (unsigned LocNo : loc_nos())
199 // Undef values don't exist in locations (and thus not in LocNoMap
200 // either) so skip over them. See getLocationNo().
201 NewLocNos.push_back(LocNo == UndefLocNo ? UndefLocNo : LocNoMap[LocNo]);
202 return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
203 }
204
205 DbgVariableValue changeLocNo(unsigned OldLocNo, unsigned NewLocNo) const {
206 SmallVector<unsigned> NewLocNos;
207 NewLocNos.assign(loc_nos_begin(), loc_nos_end());
208 auto OldLocIt = find(NewLocNos, OldLocNo);
209 assert(OldLocIt != NewLocNos.end() && "Old location must be present.");
210 *OldLocIt = NewLocNo;
211 return DbgVariableValue(NewLocNos, WasIndirect, WasList, *Expression);
212 }
213
214 bool hasLocNoGreaterThan(unsigned LocNo) const {
215 return any_of(loc_nos(),
216 [LocNo](unsigned ThisLocNo) { return ThisLocNo > LocNo; });
217 }
218
219 void printLocNos(llvm::raw_ostream &OS) const {
220 for (const unsigned &Loc : loc_nos())
221 OS << (&Loc == loc_nos_begin() ? " " : ", ") << Loc;
222 }
223
224 friend inline bool operator==(const DbgVariableValue &LHS,
225 const DbgVariableValue &RHS) {
226 if (std::tie(LHS.LocNoCount, LHS.WasIndirect, LHS.WasList,
227 LHS.Expression) !=
228 std::tie(RHS.LocNoCount, RHS.WasIndirect, RHS.WasList, RHS.Expression))
229 return false;
230 return std::equal(LHS.loc_nos_begin(), LHS.loc_nos_end(),
231 RHS.loc_nos_begin());
232 }
233
234 friend inline bool operator!=(const DbgVariableValue &LHS,
235 const DbgVariableValue &RHS) {
236 return !(LHS == RHS);
237 }
238
239 unsigned *loc_nos_begin() { return LocNos.get(); }
240 const unsigned *loc_nos_begin() const { return LocNos.get(); }
241 unsigned *loc_nos_end() { return LocNos.get() + LocNoCount; }
242 const unsigned *loc_nos_end() const { return LocNos.get() + LocNoCount; }
243 ArrayRef<unsigned> loc_nos() const {
244 return ArrayRef<unsigned>(LocNos.get(), LocNoCount);
245 }
246
247private:
248 // IntervalMap requires the value object to be very small, to the extent
249 // that we do not have enough room for an std::vector. Using a C-style array
250 // (with a unique_ptr wrapper for convenience) allows us to optimize for this
251 // specific case by packing the array size into only 6 bits (it is highly
252 // unlikely that any debug value will need 64+ locations).
253 std::unique_ptr<unsigned[]> LocNos;
254 uint8_t LocNoCount : 6;
255 bool WasIndirect : 1;
256 bool WasList : 1;
257 const DIExpression *Expression = nullptr;
258};
259} // namespace
260
261/// Map of where a user value is live to that value.
263
264/// Map of stack slot offsets for spilled locations.
265/// Non-spilled locations are not added to the map.
267
268/// Cache to save the location where it can be used as the starting
269/// position as input for calling MachineBasicBlock::SkipPHIsLabelsAndDebug.
270/// This is to prevent MachineBasicBlock::SkipPHIsLabelsAndDebug from
271/// repeatedly searching the same set of PHIs/Labels/Debug instructions
272/// if it is called many times for the same block.
275
276namespace {
277
278/// A user value is a part of a debug info user variable.
279///
280/// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
281/// holds part of a user variable. The part is identified by a byte offset.
282///
283/// UserValues are grouped into equivalence classes for easier searching. Two
284/// user values are related if they are held by the same virtual register. The
285/// equivalence class is the transitive closure of that relation.
286class UserValue {
288
289 const DILocalVariable *Variable; ///< The debug info variable we are part of.
290 /// The part of the variable we describe.
291 const std::optional<DIExpression::FragmentInfo> Fragment;
292 DebugLoc dl; ///< The debug location for the variable. This is
293 ///< used by dwarf writer to find lexical scope.
294 UserValue *leader; ///< Equivalence class leader.
295 UserValue *next = nullptr; ///< Next value in equivalence class, or null.
296
297 /// Numbered locations referenced by locmap.
299
300 /// Map of slot indices where this value is live.
301 LocMap locInts;
302
303 /// Set of interval start indexes that have been trimmed to the
304 /// lexical scope.
305 SmallSet<SlotIndex, 2> trimmedDefs;
306
307 /// Insert a DBG_VALUE into MBB at Idx for DbgValue.
308 void insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
309 SlotIndex StopIdx, DbgVariableValue DbgValue,
310 ArrayRef<bool> LocSpills,
311 ArrayRef<unsigned> SpillOffsets, LiveIntervals &LIS,
312 const TargetInstrInfo &TII,
313 const TargetRegisterInfo &TRI,
314 BlockSkipInstsMap &BBSkipInstsMap);
315
316 /// Replace OldLocNo ranges with NewRegs ranges where NewRegs
317 /// is live. Returns true if any changes were made.
318 bool splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs,
319 LiveIntervals &LIS);
320
321public:
322 /// Create a new UserValue.
323 UserValue(const DILocalVariable *var,
324 std::optional<DIExpression::FragmentInfo> Fragment, DebugLoc L,
325 LocMap::Allocator &alloc)
326 : Variable(var), Fragment(Fragment), dl(std::move(L)), leader(this),
327 locInts(alloc) {}
328
329 /// Get the leader of this value's equivalence class.
330 UserValue *getLeader() {
331 UserValue *l = leader;
332 while (l != l->leader)
333 l = l->leader;
334 return leader = l;
335 }
336
337 /// Return the next UserValue in the equivalence class.
338 UserValue *getNext() const { return next; }
339
340 /// Merge equivalence classes.
341 static UserValue *merge(UserValue *L1, UserValue *L2) {
342 L2 = L2->getLeader();
343 if (!L1)
344 return L2;
345 L1 = L1->getLeader();
346 if (L1 == L2)
347 return L1;
348 // Splice L2 before L1's members.
349 UserValue *End = L2;
350 while (End->next) {
351 End->leader = L1;
352 End = End->next;
353 }
354 End->leader = L1;
355 End->next = L1->next;
356 L1->next = L2;
357 return L1;
358 }
359
360 /// Return the location number that matches Loc.
361 ///
362 /// For undef values we always return location number UndefLocNo without
363 /// inserting anything in locations. Since locations is a vector and the
364 /// location number is the position in the vector and UndefLocNo is ~0,
365 /// we would need a very big vector to put the value at the right position.
366 unsigned getLocationNo(const MachineOperand &LocMO) {
367 if (LocMO.isReg()) {
368 if (LocMO.getReg() == 0)
369 return UndefLocNo;
370 // For register locations we dont care about use/def and other flags.
371 for (unsigned i = 0, e = locations.size(); i != e; ++i)
372 if (locations[i].isReg() &&
373 locations[i].getReg() == LocMO.getReg() &&
374 locations[i].getSubReg() == LocMO.getSubReg())
375 return i;
376 } else
377 for (unsigned i = 0, e = locations.size(); i != e; ++i)
378 if (LocMO.isIdenticalTo(locations[i]))
379 return i;
380 locations.push_back(LocMO);
381 // We are storing a MachineOperand outside a MachineInstr.
382 locations.back().clearParent();
383 // Don't store def operands.
384 if (locations.back().isReg()) {
385 if (locations.back().isDef())
386 locations.back().setIsDead(false);
387 locations.back().setIsUse();
388 }
389 return locations.size() - 1;
390 }
391
392 /// Remove (recycle) a location number. If \p LocNo still is used by the
393 /// locInts nothing is done.
394 void removeLocationIfUnused(unsigned LocNo) {
395 // Bail out if LocNo still is used.
396 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
397 const DbgVariableValue &DbgValue = I.value();
398 if (DbgValue.containsLocNo(LocNo))
399 return;
400 }
401 // Remove the entry in the locations vector, and adjust all references to
402 // location numbers above the removed entry.
403 locations.erase(locations.begin() + LocNo);
404 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
405 const DbgVariableValue &DbgValue = I.value();
406 if (DbgValue.hasLocNoGreaterThan(LocNo))
407 I.setValueUnchecked(DbgValue.decrementLocNosAfterPivot(LocNo));
408 }
409 }
410
411 /// Ensure that all virtual register locations are mapped.
412 void mapVirtRegs(LDVImpl *LDV);
413
414 /// Add a definition point to this user value.
415 void addDef(SlotIndex Idx, ArrayRef<MachineOperand> LocMOs, bool IsIndirect,
416 bool IsList, const DIExpression &Expr) {
418 for (const MachineOperand &Op : LocMOs)
419 Locs.push_back(getLocationNo(Op));
420 DbgVariableValue DbgValue(Locs, IsIndirect, IsList, Expr);
421 // Add a singular (Idx,Idx) -> value mapping.
422 LocMap::iterator I = locInts.find(Idx);
423 if (!I.valid() || I.start() != Idx)
424 I.insert(Idx, Idx.getNextSlot(), std::move(DbgValue));
425 else
426 // A later DBG_VALUE at the same SlotIndex overrides the old location.
427 I.setValue(std::move(DbgValue));
428 }
429
430 /// Extend the current definition as far as possible down.
431 ///
432 /// Stop when meeting an existing def or when leaving the live
433 /// range of VNI. End points where VNI is no longer live are added to Kills.
434 ///
435 /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
436 /// data-flow analysis to propagate them beyond basic block boundaries.
437 ///
438 /// \param Idx Starting point for the definition.
439 /// \param DbgValue value to propagate.
440 /// \param LiveIntervalInfo For each location number key in this map,
441 /// restricts liveness to where the LiveRange has the value equal to the\
442 /// VNInfo.
443 /// \param [out] Kills Append end points of VNI's live range to Kills.
444 /// \param LIS Live intervals analysis.
445 void
446 extendDef(SlotIndex Idx, DbgVariableValue DbgValue,
447 SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>>
448 &LiveIntervalInfo,
449 std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills,
450 LiveIntervals &LIS);
451
452 /// The value in LI may be copies to other registers. Determine if
453 /// any of the copies are available at the kill points, and add defs if
454 /// possible.
455 ///
456 /// \param DbgValue Location number of LI->reg, and DIExpression.
457 /// \param LocIntervals Scan for copies of the value for each location in the
458 /// corresponding LiveInterval->reg.
459 /// \param KilledAt The point where the range of DbgValue could be extended.
460 /// \param [in,out] NewDefs Append (Idx, DbgValue) of inserted defs here.
461 void addDefsFromCopies(
462 DbgVariableValue DbgValue,
463 SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals,
464 SlotIndex KilledAt,
465 SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
467
468 /// Compute the live intervals of all locations after collecting all their
469 /// def points.
470 void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
471 LiveIntervals &LIS, LexicalScopes &LS);
472
473 /// Replace OldReg ranges with NewRegs ranges where NewRegs is
474 /// live. Returns true if any changes were made.
475 bool splitRegister(Register OldReg, ArrayRef<Register> NewRegs,
476 LiveIntervals &LIS);
477
478 /// Replace the stale indexes in locInts and trimmedDefs.
479 void canonicalizeIndexes(const SlotIndexes &SI);
480
481 /// Rewrite virtual register locations according to the provided virtual
482 /// register map. Record the stack slot offsets for the locations that
483 /// were spilled.
484 void rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
485 const TargetInstrInfo &TII,
486 const TargetRegisterInfo &TRI,
487 SpillOffsetMap &SpillOffsets);
488
489 /// Recreate DBG_VALUE instruction from data structures.
490 void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
491 const TargetInstrInfo &TII,
492 const TargetRegisterInfo &TRI,
493 const SpillOffsetMap &SpillOffsets,
494 BlockSkipInstsMap &BBSkipInstsMap);
495
496 /// Return DebugLoc of this UserValue.
497 const DebugLoc &getDebugLoc() { return dl; }
498
499 void print(raw_ostream &, const TargetRegisterInfo *);
500};
501
502/// A user label is a part of a debug info user label.
503class UserLabel {
504 const DILabel *Label; ///< The debug info label we are part of.
505 DebugLoc dl; ///< The debug location for the label. This is
506 ///< used by dwarf writer to find lexical scope.
507 SlotIndex loc; ///< Slot used by the debug label.
508
509 /// Insert a DBG_LABEL into MBB at Idx.
510 void insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
511 LiveIntervals &LIS, const TargetInstrInfo &TII,
512 BlockSkipInstsMap &BBSkipInstsMap);
513
514public:
515 /// Create a new UserLabel.
516 UserLabel(const DILabel *label, DebugLoc L, SlotIndex Idx)
517 : Label(label), dl(std::move(L)), loc(Idx) {}
518
519 /// Does this UserLabel match the parameters?
520 bool matches(const DILabel *L, const DILocation *IA,
521 const SlotIndex Index) const {
522 return Label == L && dl->getInlinedAt() == IA && loc == Index;
523 }
524
525 /// Recreate DBG_LABEL instruction from data structures.
526 void emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
527 BlockSkipInstsMap &BBSkipInstsMap);
528
529 /// Replace loc if it is stale, and report whether it was.
530 bool canonicalizeIndex(const SlotIndexes &SI) {
531 bool WasStale = SI.isStaleIndex(loc);
532 loc = SI.canonicalizeIndex(loc);
533 assert(!SI.isStaleIndex(loc) &&
534 "Canonicalized label still refers to an erased instruction");
535 return WasStale;
536 }
537
538 /// Return DebugLoc of this UserLabel.
539 const DebugLoc &getDebugLoc() { return dl; }
540
541 void print(raw_ostream &, const TargetRegisterInfo *);
542};
543
544} // end anonymous namespace
545
546namespace llvm {
547
549 LocMap::Allocator allocator;
550 MachineFunction *MF = nullptr;
551 LiveIntervals *LIS;
552 const TargetRegisterInfo *TRI;
553
554 /// Position and VReg of a PHI instruction during register allocation.
555 struct PHIValPos {
556 SlotIndex SI; /// Slot where this PHI occurs.
557 Register Reg; /// VReg this PHI occurs in.
558 unsigned SubReg; /// Qualifiying subregister for Reg.
559 };
560
561 /// Map from debug instruction number to PHI position during allocation.
562 std::map<unsigned, PHIValPos> PHIValToPos;
563 /// Index of, for each VReg, which debug instruction numbers and corresponding
564 /// PHIs are sensitive to splitting. Each VReg may have multiple PHI defs,
565 /// at different positions.
567
568 /// Record for any debug instructions unlinked from their blocks during
569 /// regalloc. Stores the instr and it's location, so that they can be
570 /// re-inserted after regalloc is over.
571 struct InstrPos {
572 MachineInstr *MI; ///< Debug instruction, unlinked from it's block.
573 SlotIndex Idx; ///< Slot position where MI should be re-inserted.
574 MachineBasicBlock *MBB; ///< Block that MI was in.
575 };
576
577 /// Collection of stored debug instructions, preserved until after regalloc.
578 SmallVector<InstrPos, 32> StashedDebugInstrs;
579
580 /// Whether emitDebugValues is called.
581 bool EmitDone = false;
582
583 /// Whether the machine function is modified during the pass.
584 bool ModifiedMF = false;
585
586 /// All allocated UserValue instances.
588
589 /// All allocated UserLabel instances.
591
592 /// Map virtual register to eq class leader.
594 VRMap virtRegToEqClass;
595
596 /// Map to find existing UserValue instances.
598 UVMap userVarMap;
599
600 /// Find or create a UserValue.
601 UserValue *getUserValue(const DILocalVariable *Var,
602 std::optional<DIExpression::FragmentInfo> Fragment,
603 const DebugLoc &DL);
604
605 /// Find the EC leader for VirtReg or null.
606 UserValue *lookupVirtReg(Register VirtReg);
607
608 /// Add DBG_VALUE instruction to our maps.
609 ///
610 /// \param MI DBG_VALUE instruction
611 /// \param Idx Last valid SLotIndex before instruction.
612 ///
613 /// \returns True if the DBG_VALUE instruction should be deleted.
614 bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
615
616 /// Track variable location debug instructions while using the instruction
617 /// referencing implementation. Such debug instructions do not need to be
618 /// updated during regalloc because they identify instructions rather than
619 /// register locations. However, they needs to be removed from the
620 /// MachineFunction during regalloc, then re-inserted later, to avoid
621 /// disrupting the allocator.
622 ///
623 /// \param MI Any DBG_VALUE / DBG_INSTR_REF / DBG_PHI instruction
624 /// \param Idx Last valid SlotIndex before instruction
625 ///
626 /// \returns Iterator to continue processing from after unlinking.
628
629 /// Add DBG_LABEL instruction to UserLabel.
630 ///
631 /// \param MI DBG_LABEL instruction
632 /// \param Idx Last valid SlotIndex before instruction.
633 ///
634 /// \returns True if the DBG_LABEL instruction should be deleted.
635 bool handleDebugLabel(MachineInstr &MI, SlotIndex Idx);
636
637 /// Collect and erase all DBG_VALUE instructions, adding a UserValue def
638 /// for each instruction.
639 ///
640 /// \param mf MachineFunction to be scanned.
641 /// \param InstrRef Whether to operate in instruction referencing mode. If
642 /// true, most of LiveDebugVariables doesn't run.
643 ///
644 /// \returns True if any debug values were found.
645 bool collectDebugValues(MachineFunction &mf, bool InstrRef);
646
647 /// Compute the live intervals of all user values after collecting all
648 /// their def points.
649 void computeIntervals();
650
651public:
652 LDVImpl(LiveIntervals *LIS) : LIS(LIS) {}
653
654 bool runOnMachineFunction(MachineFunction &mf, bool InstrRef);
655
656 /// Release all memory.
657 void clear() {
658 MF = nullptr;
659 PHIValToPos.clear();
660 RegToPHIIdx.clear();
661 StashedDebugInstrs.clear();
662 userValues.clear();
663 userLabels.clear();
664 virtRegToEqClass.clear();
665 userVarMap.clear();
666 // Make sure we call emitDebugValues if the machine function was modified.
667 assert((!ModifiedMF || EmitDone) &&
668 "Dbg values are not emitted in LDV");
669 EmitDone = false;
670 ModifiedMF = false;
671 }
672
673 /// Map virtual register to an equivalence class.
674 void mapVirtReg(Register VirtReg, UserValue *EC);
675
676 /// Replace any PHI referring to OldReg with its corresponding NewReg, if
677 /// present.
678 void splitPHIRegister(Register OldReg, ArrayRef<Register> NewRegs);
679
680 /// Replace all references to OldReg with NewRegs.
681 void splitRegister(Register OldReg, ArrayRef<Register> NewRegs);
682
683 /// Replace every stale index held by this analysis.
685
686 /// Recreate DBG_VALUE instruction from data structures.
687 void emitDebugValues(VirtRegMap *VRM);
688
689 void print(raw_ostream&);
690};
691
692/// Implementation of the LiveDebugVariables pass.
693
697
698} // namespace llvm
699
700static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
701 const LLVMContext &Ctx) {
702 if (!DL)
703 return;
704
705 auto *Scope = cast<DIScope>(DL.getScope());
706 // Omit the directory, because it's likely to be long and uninteresting.
707 CommentOS << Scope->getFilename();
708 CommentOS << ':' << DL.getLine();
709 if (DL.getCol() != 0)
710 CommentOS << ':' << DL.getCol();
711
712 DebugLoc InlinedAtDL = DL.getInlinedAt();
713 if (!InlinedAtDL)
714 return;
715
716 CommentOS << " @[ ";
717 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
718 CommentOS << " ]";
719}
720
721static void printExtendedName(raw_ostream &OS, const DINode *Node,
722 const DILocation *DL) {
723 const LLVMContext &Ctx = Node->getContext();
724 StringRef Res;
725 unsigned Line = 0;
726 if (const auto *V = dyn_cast<const DILocalVariable>(Node)) {
727 Res = V->getName();
728 Line = V->getLine();
729 } else if (const auto *L = dyn_cast<const DILabel>(Node)) {
730 Res = L->getName();
731 Line = L->getLine();
732 }
733
734 if (!Res.empty())
735 OS << Res << "," << Line;
736 auto *InlinedAt = DL ? DL->getInlinedAt() : nullptr;
737 if (InlinedAt) {
738 if (DebugLoc InlinedAtDL = InlinedAt) {
739 OS << " @[";
740 printDebugLoc(InlinedAtDL, OS, Ctx);
741 OS << "]";
742 }
743 }
744}
745
746void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
747 OS << "!\"";
748 printExtendedName(OS, Variable, dl);
749
750 OS << "\"\t";
751 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
752 OS << " [" << I.start() << ';' << I.stop() << "):";
753 if (I.value().isUndef())
754 OS << " undef";
755 else {
756 I.value().printLocNos(OS);
757 if (I.value().getWasIndirect())
758 OS << " ind";
759 else if (I.value().getWasList())
760 OS << " list";
761 }
762 }
763 for (unsigned i = 0, e = locations.size(); i != e; ++i) {
764 OS << " Loc" << i << '=';
765 locations[i].print(OS, TRI);
766 }
767 OS << '\n';
768}
769
770void UserLabel::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
771 OS << "!\"";
772 printExtendedName(OS, Label, dl);
773
774 OS << "\"\t";
775 OS << loc;
776 OS << '\n';
777}
778
780 OS << "********** DEBUG VARIABLES **********\n";
781 for (auto &userValue : userValues)
782 userValue->print(OS, TRI);
783 OS << "********** DEBUG LABELS **********\n";
784 for (auto &userLabel : userLabels)
785 userLabel->print(OS, TRI);
786}
787
788void UserValue::mapVirtRegs(LiveDebugVariables::LDVImpl *LDV) {
789 for (const MachineOperand &MO : locations)
790 if (MO.isReg() && MO.getReg().isVirtual())
791 LDV->mapVirtReg(MO.getReg(), this);
792}
793
794UserValue *LiveDebugVariables::LDVImpl::getUserValue(
795 const DILocalVariable *Var,
796 std::optional<DIExpression::FragmentInfo> Fragment, const DebugLoc &DL) {
797 // FIXME: Handle partially overlapping fragments. See
798 // https://reviews.llvm.org/D70121#1849741.
799 DebugVariable ID(Var, Fragment, DL->getInlinedAt());
800 UserValue *&UV = userVarMap[ID];
801 if (!UV) {
802 userValues.push_back(
803 std::make_unique<UserValue>(Var, Fragment, DL, allocator));
804 UV = userValues.back().get();
805 }
806 return UV;
807}
808
810 assert(VirtReg.isVirtual() && "Only map VirtRegs");
811 UserValue *&Leader = virtRegToEqClass[VirtReg];
812 Leader = UserValue::merge(Leader, EC);
813}
814
815UserValue *LiveDebugVariables::LDVImpl::lookupVirtReg(Register VirtReg) {
816 if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
817 return UV->getLeader();
818 return nullptr;
819}
820
821bool LiveDebugVariables::LDVImpl::handleDebugValue(MachineInstr &MI,
822 SlotIndex Idx) {
823 // DBG_VALUE loc, offset, variable, expr
824 // DBG_VALUE_LIST variable, expr, locs...
825 if (!MI.isDebugValue()) {
826 LLVM_DEBUG(dbgs() << "Can't handle non-DBG_VALUE*: " << MI);
827 return false;
828 }
829 if (!MI.getDebugVariableOp().isMetadata()) {
830 LLVM_DEBUG(dbgs() << "Can't handle DBG_VALUE* with invalid variable: "
831 << MI);
832 return false;
833 }
834 if (MI.isNonListDebugValue() &&
835 (MI.getNumOperands() != 4 ||
836 !(MI.getDebugOffset().isImm() || MI.getDebugOffset().isReg()))) {
837 LLVM_DEBUG(dbgs() << "Can't handle malformed DBG_VALUE: " << MI);
838 return false;
839 }
840
841 // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual
842 // register that hasn't been defined yet. If we do not remove those here, then
843 // the re-insertion of the DBG_VALUE instruction after register allocation
844 // will be incorrect.
845 bool Discard = false;
846 for (const MachineOperand &Op : MI.debug_operands()) {
847 if (Op.isReg() && Op.getReg().isVirtual()) {
848 const Register Reg = Op.getReg();
849 if (!LIS->hasInterval(Reg)) {
850 // The DBG_VALUE is described by a virtual register that does not have a
851 // live interval. Discard the DBG_VALUE.
852 Discard = true;
853 LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx
854 << " " << MI);
855 } else {
856 // The DBG_VALUE is only valid if either Reg is live out from Idx, or
857 // Reg is defined dead at Idx (where Idx is the slot index for the
858 // instruction preceding the DBG_VALUE).
859 const LiveInterval &LI = LIS->getInterval(Reg);
860 LiveQueryResult LRQ = LI.Query(Idx);
861 if (!LRQ.valueOutOrDead()) {
862 // We have found a DBG_VALUE with the value in a virtual register that
863 // is not live. Discard the DBG_VALUE.
864 Discard = true;
865 LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx
866 << " " << MI);
867 }
868 }
869 }
870 }
871
872 // Get or create the UserValue for (variable,offset) here.
873 bool IsIndirect = MI.isDebugOffsetImm();
874 if (IsIndirect)
875 assert(MI.getDebugOffset().getImm() == 0 &&
876 "DBG_VALUE with nonzero offset");
877 bool IsList = MI.isDebugValueList();
878 const DILocalVariable *Var = MI.getDebugVariable();
879 const DIExpression *Expr = MI.getDebugExpression();
880 UserValue *UV = getUserValue(Var, Expr->getFragmentInfo(), MI.getDebugLoc());
881 if (!Discard)
882 UV->addDef(Idx,
883 ArrayRef<MachineOperand>(MI.debug_operands().begin(),
884 MI.debug_operands().end()),
885 IsIndirect, IsList, *Expr);
886 else {
887 MachineOperand MO = MachineOperand::CreateReg(0U, false);
888 MO.setIsDebug();
889 // We should still pass a list the same size as MI.debug_operands() even if
890 // all MOs are undef, so that DbgVariableValue can correctly adjust the
891 // expression while removing the duplicated undefs.
892 SmallVector<MachineOperand, 4> UndefMOs(MI.getNumDebugOperands(), MO);
893 UV->addDef(Idx, UndefMOs, false, IsList, *Expr);
894 }
895 return true;
896}
897
899LiveDebugVariables::LDVImpl::handleDebugInstr(MachineInstr &MI, SlotIndex Idx) {
900 assert(MI.isDebugValueLike() || MI.isDebugPHI());
901
902 // In instruction referencing mode, there should be no DBG_VALUE instructions
903 // that refer to virtual registers. They might still refer to constants.
904 if (MI.isDebugValueLike())
905 assert(none_of(MI.debug_operands(),
906 [](const MachineOperand &MO) {
907 return MO.isReg() && MO.getReg().isVirtual();
908 }) &&
909 "MIs should not refer to Virtual Registers in InstrRef mode.");
910
911 // Unlink the instruction, store it in the debug instructions collection.
912 auto NextInst = std::next(MI.getIterator());
913 auto *MBB = MI.getParent();
914 MI.removeFromParent();
915 StashedDebugInstrs.push_back({&MI, Idx, MBB});
916 return NextInst;
917}
918
919bool LiveDebugVariables::LDVImpl::handleDebugLabel(MachineInstr &MI,
920 SlotIndex Idx) {
921 // DBG_LABEL label
922 if (MI.getNumOperands() != 1 || !MI.getOperand(0).isMetadata()) {
923 LLVM_DEBUG(dbgs() << "Can't handle " << MI);
924 return false;
925 }
926
927 // Get or create the UserLabel for label here.
928 const DILabel *Label = MI.getDebugLabel();
929 const DebugLoc &DL = MI.getDebugLoc();
930 bool Found = false;
931 for (auto const &L : userLabels) {
932 if (L->matches(Label, DL->getInlinedAt(), Idx)) {
933 Found = true;
934 break;
935 }
936 }
937 if (!Found)
938 userLabels.push_back(std::make_unique<UserLabel>(Label, DL, Idx));
939
940 return true;
941}
942
943bool LiveDebugVariables::LDVImpl::collectDebugValues(MachineFunction &mf,
944 bool InstrRef) {
945 bool Changed = false;
946 for (MachineBasicBlock &MBB : mf) {
947 for (MachineBasicBlock::iterator MBBI = MBB.begin(), MBBE = MBB.end();
948 MBBI != MBBE;) {
949 // Use the first debug instruction in the sequence to get a SlotIndex
950 // for following consecutive debug instructions.
951 if (!MBBI->isDebugOrPseudoInstr()) {
952 ++MBBI;
953 continue;
954 }
955 // Debug instructions has no slot index. Use the previous
956 // non-debug instruction's SlotIndex as its SlotIndex.
957 SlotIndex Idx =
958 MBBI == MBB.begin()
959 ? LIS->getMBBStartIdx(&MBB)
960 : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
961 // Handle consecutive debug instructions with the same slot index.
962 do {
963 // In instruction referencing mode, pass each instr to handleDebugInstr
964 // to be unlinked. Ignore DBG_VALUE_LISTs -- they refer to vregs, and
965 // need to go through the normal live interval splitting process.
966 if (InstrRef && (MBBI->isNonListDebugValue() || MBBI->isDebugPHI() ||
967 MBBI->isDebugRef())) {
968 MBBI = handleDebugInstr(*MBBI, Idx);
969 Changed = true;
970 // In normal debug mode, use the dedicated DBG_VALUE / DBG_LABEL handler
971 // to track things through register allocation, and erase the instr.
972 } else if ((MBBI->isDebugValue() && handleDebugValue(*MBBI, Idx)) ||
973 (MBBI->isDebugLabel() && handleDebugLabel(*MBBI, Idx))) {
974 MBBI = MBB.erase(MBBI);
975 Changed = true;
976 } else
977 ++MBBI;
978 } while (MBBI != MBBE && MBBI->isDebugOrPseudoInstr());
979 }
980 }
981 return Changed;
982}
983
984void UserValue::extendDef(
985 SlotIndex Idx, DbgVariableValue DbgValue,
986 SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>>
987 &LiveIntervalInfo,
988 std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills,
989 LiveIntervals &LIS) {
990 SlotIndex Start = Idx;
991 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
992 SlotIndex Stop = LIS.getMBBEndIdx(MBB);
993 LocMap::iterator I = locInts.find(Start);
994
995 // Limit to the intersection of the VNIs' live ranges.
996 for (auto &LII : LiveIntervalInfo) {
997 LiveRange *LR = LII.second.first;
998 assert(LR && LII.second.second && "Missing range info for Idx.");
999 LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
1000 assert(Segment && Segment->valno == LII.second.second &&
1001 "Invalid VNInfo for Idx given?");
1002 if (Segment->end < Stop) {
1003 Stop = Segment->end;
1004 Kills = {Stop, {LII.first}};
1005 } else if (Segment->end == Stop && Kills) {
1006 // If multiple locations end at the same place, track all of them in
1007 // Kills.
1008 Kills->second.push_back(LII.first);
1009 }
1010 }
1011
1012 // There could already be a short def at Start.
1013 if (I.valid() && I.start() <= Start) {
1014 // Stop when meeting a different location or an already extended interval.
1015 Start = Start.getNextSlot();
1016 if (I.value() != DbgValue || I.stop() != Start) {
1017 // Clear `Kills`, as we have a new def available.
1018 Kills = std::nullopt;
1019 return;
1020 }
1021 // This is a one-slot placeholder. Just skip it.
1022 ++I;
1023 }
1024
1025 // Limited by the next def.
1026 if (I.valid() && I.start() < Stop) {
1027 Stop = I.start();
1028 // Clear `Kills`, as we have a new def available.
1029 Kills = std::nullopt;
1030 }
1031
1032 if (Start < Stop) {
1033 DbgVariableValue ExtDbgValue(DbgValue);
1034 I.insert(Start, Stop, std::move(ExtDbgValue));
1035 }
1036}
1037
1038void UserValue::addDefsFromCopies(
1039 DbgVariableValue DbgValue,
1040 SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals,
1041 SlotIndex KilledAt,
1042 SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
1043 MachineRegisterInfo &MRI, LiveIntervals &LIS) {
1044 // Don't track copies from physregs, there are too many uses.
1045 if (any_of(LocIntervals,
1046 [](auto LocI) { return !LocI.second->reg().isVirtual(); }))
1047 return;
1048
1049 // Collect all the (vreg, valno) pairs that are copies of LI.
1050 SmallDenseMap<unsigned,
1052 CopyValues;
1053 for (auto &LocInterval : LocIntervals) {
1054 unsigned LocNo = LocInterval.first;
1055 LiveInterval *LI = LocInterval.second;
1056 for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg())) {
1057 MachineInstr *MI = MO.getParent();
1058 // Copies of the full value.
1059 if (MO.getSubReg() || !MI->isCopy())
1060 continue;
1061 Register DstReg = MI->getOperand(0).getReg();
1062
1063 // Don't follow copies to physregs. These are usually setting up call
1064 // arguments, and the argument registers are always call clobbered. We are
1065 // better off in the source register which could be a callee-saved
1066 // register, or it could be spilled.
1067 if (!DstReg.isVirtual())
1068 continue;
1069
1070 // Is the value extended to reach this copy? If not, another def may be
1071 // blocking it, or we are looking at a wrong value of LI.
1072 SlotIndex Idx = LIS.getInstructionIndex(*MI);
1073 LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
1074 if (!I.valid() || I.value() != DbgValue)
1075 continue;
1076
1077 if (!LIS.hasInterval(DstReg))
1078 continue;
1079 LiveInterval *DstLI = &LIS.getInterval(DstReg);
1080 const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
1081 assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
1082 CopyValues[LocNo].push_back(std::make_pair(DstLI, DstVNI));
1083 }
1084 }
1085
1086 if (CopyValues.empty())
1087 return;
1088
1089#if !defined(NDEBUG)
1090 for (auto &LocInterval : LocIntervals)
1091 LLVM_DEBUG(dbgs() << "Got " << CopyValues[LocInterval.first].size()
1092 << " copies of " << *LocInterval.second << '\n');
1093#endif
1094
1095 // Try to add defs of the copied values for the kill point. Check that there
1096 // isn't already a def at Idx.
1097 LocMap::iterator I = locInts.find(KilledAt);
1098 if (I.valid() && I.start() <= KilledAt)
1099 return;
1100 DbgVariableValue NewValue(DbgValue);
1101 for (auto &LocInterval : LocIntervals) {
1102 unsigned LocNo = LocInterval.first;
1103 bool FoundCopy = false;
1104 for (auto &LIAndVNI : CopyValues[LocNo]) {
1105 LiveInterval *DstLI = LIAndVNI.first;
1106 const VNInfo *DstVNI = LIAndVNI.second;
1107 if (DstLI->getVNInfoAt(KilledAt) != DstVNI)
1108 continue;
1109 LLVM_DEBUG(dbgs() << "Kill at " << KilledAt << " covered by valno #"
1110 << DstVNI->id << " in " << *DstLI << '\n');
1111 MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
1112 assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
1113 unsigned NewLocNo = getLocationNo(CopyMI->getOperand(0));
1114 NewValue = NewValue.changeLocNo(LocNo, NewLocNo);
1115 FoundCopy = true;
1116 break;
1117 }
1118 // If there are any killed locations we can't find a copy for, we can't
1119 // extend the variable value.
1120 if (!FoundCopy)
1121 return;
1122 }
1123 I.insert(KilledAt, KilledAt.getNextSlot(), NewValue);
1124 NewDefs.push_back(std::make_pair(KilledAt, NewValue));
1125}
1126
1127void UserValue::computeIntervals(MachineRegisterInfo &MRI,
1128 const TargetRegisterInfo &TRI,
1129 LiveIntervals &LIS, LexicalScopes &LS) {
1131
1132 // Collect all defs to be extended (Skipping undefs).
1133 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
1134 if (!I.value().isUndef())
1135 Defs.push_back(std::make_pair(I.start(), I.value()));
1136
1137 // Extend all defs, and possibly add new ones along the way.
1138 for (unsigned i = 0; i != Defs.size(); ++i) {
1139 SlotIndex Idx = Defs[i].first;
1140 DbgVariableValue DbgValue = Defs[i].second;
1141 SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>> LIs;
1142 bool ShouldExtendDef = false;
1143 for (unsigned LocNo : DbgValue.loc_nos()) {
1144 const MachineOperand &LocMO = locations[LocNo];
1145 if (!LocMO.isReg() || !LocMO.getReg().isVirtual()) {
1146 ShouldExtendDef |= !LocMO.isReg();
1147 continue;
1148 }
1149 ShouldExtendDef = true;
1150 LiveInterval *LI = nullptr;
1151 const VNInfo *VNI = nullptr;
1152 if (LIS.hasInterval(LocMO.getReg())) {
1153 LI = &LIS.getInterval(LocMO.getReg());
1154 VNI = LI->getVNInfoAt(Idx);
1155 }
1156 if (LI && VNI)
1157 LIs[LocNo] = {LI, VNI};
1158 }
1159 if (ShouldExtendDef) {
1160 std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> Kills;
1161 extendDef(Idx, DbgValue, LIs, Kills, LIS);
1162
1163 if (Kills) {
1165 bool AnySubreg = false;
1166 for (unsigned LocNo : Kills->second) {
1167 const MachineOperand &LocMO = this->locations[LocNo];
1168 if (LocMO.getSubReg()) {
1169 AnySubreg = true;
1170 break;
1171 }
1172 LiveInterval *LI = &LIS.getInterval(LocMO.getReg());
1173 KilledLocIntervals.push_back({LocNo, LI});
1174 }
1175
1176 // FIXME: Handle sub-registers in addDefsFromCopies. The problem is that
1177 // if the original location for example is %vreg0:sub_hi, and we find a
1178 // full register copy in addDefsFromCopies (at the moment it only
1179 // handles full register copies), then we must add the sub1 sub-register
1180 // index to the new location. However, that is only possible if the new
1181 // virtual register is of the same regclass (or if there is an
1182 // equivalent sub-register in that regclass). For now, simply skip
1183 // handling copies if a sub-register is involved.
1184 if (!AnySubreg)
1185 addDefsFromCopies(DbgValue, KilledLocIntervals, Kills->first, Defs,
1186 MRI, LIS);
1187 }
1188 }
1189
1190 // For physregs, we only mark the start slot idx. DwarfDebug will see it
1191 // as if the DBG_VALUE is valid up until the end of the basic block, or
1192 // the next def of the physical register. So we do not need to extend the
1193 // range. It might actually happen that the DBG_VALUE is the last use of
1194 // the physical register (e.g. if this is an unused input argument to a
1195 // function).
1196 }
1197
1198 // The computed intervals may extend beyond the range of the debug
1199 // location's lexical scope. In this case, splitting of an interval
1200 // can result in an interval outside of the scope being created,
1201 // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
1202 // this, trim the intervals to the lexical scope in the case of inlined
1203 // variables, since heavy inlining may cause production of dramatically big
1204 // number of DBG_VALUEs to be generated.
1205 if (!dl.getInlinedAt())
1206 return;
1207
1208 LexicalScope *Scope = LS.findLexicalScope(dl);
1209 if (!Scope)
1210 return;
1211
1212 SlotIndex PrevEnd;
1213 LocMap::iterator I = locInts.begin();
1214
1215 // Iterate over the lexical scope ranges. Each time round the loop
1216 // we check the intervals for overlap with the end of the previous
1217 // range and the start of the next. The first range is handled as
1218 // a special case where there is no PrevEnd.
1219 for (const InsnRange &Range : Scope->getRanges()) {
1220 SlotIndex RStart = LIS.getInstructionIndex(*Range.first);
1221 SlotIndex REnd = LIS.getInstructionIndex(*Range.second);
1222
1223 // Variable locations at the first instruction of a block should be
1224 // based on the block's SlotIndex, not the first instruction's index.
1225 if (Range.first == Range.first->getParent()->begin())
1226 RStart = LIS.getSlotIndexes()->getIndexBefore(*Range.first);
1227
1228 // At the start of each iteration I has been advanced so that
1229 // I.stop() >= PrevEnd. Check for overlap.
1230 if (PrevEnd && I.start() < PrevEnd) {
1231 SlotIndex IStop = I.stop();
1232 DbgVariableValue DbgValue = I.value();
1233
1234 // Stop overlaps previous end - trim the end of the interval to
1235 // the scope range.
1236 I.setStopUnchecked(PrevEnd);
1237 ++I;
1238
1239 // If the interval also overlaps the start of the "next" (i.e.
1240 // current) range create a new interval for the remainder (which
1241 // may be further trimmed).
1242 if (RStart < IStop)
1243 I.insert(RStart, IStop, DbgValue);
1244 }
1245
1246 // Advance I so that I.stop() >= RStart, and check for overlap.
1247 I.advanceTo(RStart);
1248 if (!I.valid())
1249 return;
1250
1251 if (I.start() < RStart) {
1252 // Interval start overlaps range - trim to the scope range.
1253 I.setStartUnchecked(RStart);
1254 // Remember that this interval was trimmed.
1255 trimmedDefs.insert(RStart);
1256 }
1257
1258 // The end of a lexical scope range is the last instruction in the
1259 // range. To convert to an interval we need the index of the
1260 // instruction after it.
1261 REnd = REnd.getNextIndex();
1262
1263 // Advance I to first interval outside current range.
1264 I.advanceTo(REnd);
1265 if (!I.valid())
1266 return;
1267
1268 PrevEnd = REnd;
1269 }
1270
1271 // Check for overlap with end of final range.
1272 if (PrevEnd && I.start() < PrevEnd)
1273 I.setStopUnchecked(PrevEnd);
1274}
1275
1276void LiveDebugVariables::LDVImpl::computeIntervals() {
1277 LexicalScopes LS;
1278 LS.scanFunction(*MF);
1279
1280 for (const auto &UV : userValues) {
1281 UV->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS);
1282 UV->mapVirtRegs(this);
1283 }
1284}
1285
1287 bool InstrRef) {
1288 clear();
1289 MF = &mf;
1290 TRI = mf.getSubtarget().getRegisterInfo();
1291 LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
1292 << mf.getName() << " **********\n");
1293
1294 bool Changed = collectDebugValues(mf, InstrRef);
1295 computeIntervals();
1296 LLVM_DEBUG(print(dbgs()));
1297
1298 // Collect the set of VReg / SlotIndexs where PHIs occur; index the sensitive
1299 // VRegs too, for when we're notified of a range split.
1300 SlotIndexes *Slots = LIS->getSlotIndexes();
1301 for (const auto &PHIIt : MF->DebugPHIPositions) {
1302 const MachineFunction::DebugPHIRegallocPos &Position = PHIIt.second;
1303 MachineBasicBlock *MBB = Position.MBB;
1304 Register Reg = Position.Reg;
1305 unsigned SubReg = Position.SubReg;
1306 SlotIndex SI = Slots->getMBBStartIdx(MBB);
1307 PHIValPos VP = {SI, Reg, SubReg};
1308 PHIValToPos.insert(std::make_pair(PHIIt.first, VP));
1309 RegToPHIIdx[Reg].push_back(PHIIt.first);
1310 }
1311
1312 ModifiedMF = Changed;
1313 return Changed;
1314}
1315
1317 for (MachineBasicBlock &MBB : mf) {
1319 if (MI.isDebugInstr())
1320 MBB.erase(&MI);
1321 }
1322}
1323
1325 MachineFunction &mf) {
1326 auto *LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
1327
1328 Impl = std::make_unique<LiveDebugVariables>();
1329 Impl->analyze(mf, LIS);
1330 return false;
1331}
1332
1333AnalysisKey LiveDebugVariablesAnalysis::Key;
1334
1338 MFPropsModifier _(*this, MF);
1339
1340 auto *LIS = &MFAM.getResult<LiveIntervalsAnalysis>(MF);
1342 LDV.analyze(MF, LIS);
1343 return LDV;
1344}
1345
1353
1355 if (PImpl)
1356 PImpl->clear();
1357}
1358
1361 MachineFunctionAnalysisManager::Invalidator &) {
1362 auto PAC = PA.getChecker<LiveDebugVariablesAnalysis>();
1363 // Some architectures split the register allocation into multiple phases based
1364 // on register classes. This requires preserving analyses between the phases
1365 // by default.
1366 return !PAC.preservedWhenStateless();
1367}
1368
1370 if (!EnableLDV)
1371 return;
1372 if (!MF.getFunction().getSubprogram()) {
1374 return;
1375 }
1376
1377 PImpl.reset(new LDVImpl(LIS));
1378
1379 // Have we been asked to track variable locations using instruction
1380 // referencing?
1381 bool InstrRef = MF.useDebugInstrRef();
1382 PImpl->runOnMachineFunction(MF, InstrRef);
1383}
1384
1385//===----------------------------------------------------------------------===//
1386// Live Range Splitting
1387//===----------------------------------------------------------------------===//
1388
1389bool
1390UserValue::splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs,
1391 LiveIntervals& LIS) {
1392 LLVM_DEBUG({
1393 dbgs() << "Splitting Loc" << OldLocNo << '\t';
1394 print(dbgs(), nullptr);
1395 });
1396 bool DidChange = false;
1397 LocMap::iterator LocMapI;
1398 LocMapI.setMap(locInts);
1399 for (Register NewReg : NewRegs) {
1400 LiveInterval *LI = &LIS.getInterval(NewReg);
1401 if (LI->empty())
1402 continue;
1403
1404 // Don't allocate the new LocNo until it is needed.
1405 unsigned NewLocNo = UndefLocNo;
1406
1407 // Iterate over the overlaps between locInts and LI.
1408 LocMapI.find(LI->beginIndex());
1409 if (!LocMapI.valid())
1410 continue;
1411 LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
1412 LiveInterval::iterator LIE = LI->end();
1413 while (LocMapI.valid() && LII != LIE) {
1414 // At this point, we know that LocMapI.stop() > LII->start.
1415 LII = LI->advanceTo(LII, LocMapI.start());
1416 if (LII == LIE)
1417 break;
1418
1419 // Now LII->end > LocMapI.start(). Do we have an overlap?
1420 if (LocMapI.value().containsLocNo(OldLocNo) &&
1421 LII->start < LocMapI.stop()) {
1422 // Overlapping correct location. Allocate NewLocNo now.
1423 if (NewLocNo == UndefLocNo) {
1424 MachineOperand MO = MachineOperand::CreateReg(LI->reg(), false);
1425 MO.setSubReg(locations[OldLocNo].getSubReg());
1426 NewLocNo = getLocationNo(MO);
1427 DidChange = true;
1428 }
1429
1430 SlotIndex LStart = LocMapI.start();
1431 SlotIndex LStop = LocMapI.stop();
1432 DbgVariableValue OldDbgValue = LocMapI.value();
1433
1434 // Trim LocMapI down to the LII overlap.
1435 if (LStart < LII->start)
1436 LocMapI.setStartUnchecked(LII->start);
1437 if (LStop > LII->end)
1438 LocMapI.setStopUnchecked(LII->end);
1439
1440 // Change the value in the overlap. This may trigger coalescing.
1441 LocMapI.setValue(OldDbgValue.changeLocNo(OldLocNo, NewLocNo));
1442
1443 // Re-insert any removed OldDbgValue ranges.
1444 if (LStart < LocMapI.start()) {
1445 LocMapI.insert(LStart, LocMapI.start(), OldDbgValue);
1446 ++LocMapI;
1447 assert(LocMapI.valid() && "Unexpected coalescing");
1448 }
1449 if (LStop > LocMapI.stop()) {
1450 ++LocMapI;
1451 LocMapI.insert(LII->end, LStop, OldDbgValue);
1452 --LocMapI;
1453 }
1454 }
1455
1456 // Advance to the next overlap.
1457 if (LII->end < LocMapI.stop()) {
1458 if (++LII == LIE)
1459 break;
1460 LocMapI.advanceTo(LII->start);
1461 } else {
1462 ++LocMapI;
1463 if (!LocMapI.valid())
1464 break;
1465 LII = LI->advanceTo(LII, LocMapI.start());
1466 }
1467 }
1468 }
1469
1470 // Finally, remove OldLocNo unless it is still used by some interval in the
1471 // locInts map. One case when OldLocNo still is in use is when the register
1472 // has been spilled. In such situations the spilled register is kept as a
1473 // location until rewriteLocations is called (VirtRegMap is mapping the old
1474 // register to the spill slot). So for a while we can have locations that map
1475 // to virtual registers that have been removed from both the MachineFunction
1476 // and from LiveIntervals.
1477 //
1478 // We may also just be using the location for a value with a different
1479 // expression.
1480 removeLocationIfUnused(OldLocNo);
1481
1482 LLVM_DEBUG({
1483 dbgs() << "Split result: \t";
1484 print(dbgs(), nullptr);
1485 });
1486 return DidChange;
1487}
1488
1489bool
1490UserValue::splitRegister(Register OldReg, ArrayRef<Register> NewRegs,
1491 LiveIntervals &LIS) {
1492 bool DidChange = false;
1493 // Split locations referring to OldReg. Iterate backwards so splitLocation can
1494 // safely erase unused locations.
1495 for (unsigned i = locations.size(); i ; --i) {
1496 unsigned LocNo = i-1;
1497 const MachineOperand *Loc = &locations[LocNo];
1498 if (!Loc->isReg() || Loc->getReg() != OldReg)
1499 continue;
1500 DidChange |= splitLocation(LocNo, NewRegs, LIS);
1501 }
1502 return DidChange;
1503}
1504
1506 ArrayRef<Register> NewRegs) {
1507 auto RegIt = RegToPHIIdx.find(OldReg);
1508 if (RegIt == RegToPHIIdx.end())
1509 return;
1510
1511 std::vector<std::pair<Register, unsigned>> NewRegIdxes;
1512 // Iterate over all the debug instruction numbers affected by this split.
1513 for (unsigned InstrID : RegIt->second) {
1514 auto PHIIt = PHIValToPos.find(InstrID);
1515 assert(PHIIt != PHIValToPos.end());
1516 const SlotIndex &Slot = PHIIt->second.SI;
1517 assert(OldReg == PHIIt->second.Reg);
1518
1519 // Find the new register that covers this position.
1520 for (auto NewReg : NewRegs) {
1521 const LiveInterval &LI = LIS->getInterval(NewReg);
1522 auto LII = LI.find(Slot);
1523 if (LII != LI.end() && LII->start <= Slot) {
1524 // This new register covers this PHI position, record this for indexing.
1525 NewRegIdxes.push_back(std::make_pair(NewReg, InstrID));
1526 // Record that this value lives in a different VReg now.
1527 PHIIt->second.Reg = NewReg;
1528 break;
1529 }
1530 }
1531
1532 // If we do not find a new register covering this PHI, then register
1533 // allocation has dropped its location, for example because it's not live.
1534 // The old VReg will not be mapped to a physreg, and the instruction
1535 // number will have been optimized out.
1536 }
1537
1538 // Re-create register index using the new register numbers.
1539 RegToPHIIdx.erase(RegIt);
1540 for (auto &RegAndInstr : NewRegIdxes)
1541 RegToPHIIdx[RegAndInstr.first].push_back(RegAndInstr.second);
1542}
1543
1545 ArrayRef<Register> NewRegs) {
1546 // Consider whether this split range affects any PHI locations.
1547 splitPHIRegister(OldReg, NewRegs);
1548
1549 // Check whether any intervals mapped by a DBG_VALUE were split and need
1550 // updating.
1551 bool DidChange = false;
1552 for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
1553 DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
1554
1555 if (!DidChange)
1556 return;
1557
1558 // Map all of the new virtual registers.
1559 UserValue *UV = lookupVirtReg(OldReg);
1560 for (Register NewReg : NewRegs)
1561 mapVirtReg(NewReg, UV);
1562}
1563
1566 if (PImpl)
1567 PImpl->splitRegister(OldReg, NewRegs);
1568}
1569
1570//===----------------------------------------------------------------------===//
1571// Stale Index Canonicalization
1572//===----------------------------------------------------------------------===//
1573
1574void UserValue::canonicalizeIndexes(const SlotIndexes &SI) {
1575 unsigned NumStale = 0;
1576 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
1577 NumStale += SI.isStaleIndex(I.start()) + SI.isStaleIndex(I.stop());
1578 for (SlotIndex Idx : trimmedDefs)
1579 NumStale += SI.isStaleIndex(Idx);
1580 NumStaleIndexes += NumStale;
1581
1582 if (NumStale) {
1583 // trimmedDefs is looked up by interval start. Remapping it here is safe:
1584 // trimmed starts are block slots, so the Stop < Start case below cannot
1585 // reach them, and a merge drops a start that then matches nothing.
1586 if (!trimmedDefs.empty()) {
1587 SmallVector<SlotIndex, 8> Defs(trimmedDefs.begin(), trimmedDefs.end());
1588 trimmedDefs.clear();
1589 for (SlotIndex Idx : Defs) {
1590 SlotIndex Canon = SI.canonicalizeIndex(Idx);
1591 if (!SI.isBlockBoundaryIndex(Canon))
1592 trimmedDefs.insert(Canon);
1593 }
1594 }
1595
1596 // Rebuild rather than move the keys of the existing map: it has to stay
1597 // ordered and non-empty at every step, which canonicalization does not
1598 // respect.
1599 struct CanonicalInterval {
1600 SlotIndex Start;
1601 SlotIndex Stop;
1602 DbgVariableValue Value;
1603 };
1605
1606 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
1607 SlotIndex Start = SI.canonicalizeIndex(I.start());
1608 SlotIndex Stop = SI.canonicalizeIndex(I.stop());
1609
1610 // A stale stop can land below a start that sat on the same instruction's
1611 // dead slot. Both resolve to the same insert location.
1612 if (Stop < Start)
1613 Start = Stop;
1614
1615 if (!Intervals.empty()) {
1616 CanonicalInterval &Prev = Intervals.back();
1617 if (Start <= Prev.Start) {
1618 // Both DBG_VALUEs would be emitted at the same position, where the
1619 // later one overrides the earlier before it covers anything.
1620 Prev.Stop = std::max(Prev.Stop, Stop);
1621 Prev.Value = I.value();
1622 ++NumMergedIntervals;
1623 continue;
1624 }
1625 Prev.Stop = std::min(Prev.Stop, Start);
1626 }
1627 Intervals.push_back({Start, Stop, I.value()});
1628 }
1629
1630 // The map cannot hold empty intervals. Use the smallest extent there is: a
1631 // wider one would span more blocks, and emitDebugValues() emits a DBG_VALUE
1632 // per block covered.
1633 for (CanonicalInterval &Interval : Intervals) {
1634 if (Interval.Stop > Interval.Start)
1635 continue;
1636 Interval.Stop = Interval.Start.getNextSlot();
1637 assert(!SI.isStaleIndex(Interval.Stop) &&
1638 "No room left for a canonicalized interval");
1639 }
1640
1641 locInts.clear();
1642 for (const CanonicalInterval &Interval : Intervals)
1643 locInts.insert(Interval.Start, Interval.Stop, Interval.Value);
1644 }
1645
1646#ifndef NDEBUG
1647 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
1648 assert(!SI.isStaleIndex(I.start()) && !SI.isStaleIndex(I.stop()) &&
1649 "Canonicalized interval still refers to an erased instruction");
1650 for (SlotIndex Idx : trimmedDefs)
1651 assert(!SI.isStaleIndex(Idx) &&
1652 "Canonicalized trimmed def still refers to an erased instruction");
1653#endif
1654}
1655
1657 for (auto &userValue : userValues)
1658 userValue->canonicalizeIndexes(SI);
1659 for (auto &userLabel : userLabels)
1660 NumStaleIndexes += userLabel->canonicalizeIndex(SI);
1661
1662 // emitDebugValues() walks forwards to the next live instruction, which is the
1663 // same iterator as inserting after the preceding one, and stays inside
1664 // InstrPos::MBB. Canonicalization is monotonic, so entries sharing a slot are
1665 // still re-inserted as one batch.
1666 for (InstrPos &Stashed : StashedDebugInstrs) {
1667 if (!SI.isStaleIndex(Stashed.Idx))
1668 continue;
1669 ++NumStaleIndexes;
1670 Stashed.Idx = SI.canonicalizeIndex(Stashed.Idx);
1671 assert(!SI.isStaleIndex(Stashed.Idx) &&
1672 "Canonicalized debug instr still refers to an erased instruction");
1673 }
1674
1675#ifndef NDEBUG
1676 // PHI positions are block starts, which are boundaries. A block erased by
1677 // removeMBBFromMaps() would make one look stale.
1678 for (const auto &P : PHIValToPos)
1679 assert(!SI.isStaleIndex(P.second.SI) &&
1680 "PHI position refers to an erased instruction");
1681#endif
1682}
1683
1685 if (PImpl)
1686 PImpl->canonicalizeIndexes(SI);
1687}
1688
1689void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
1690 const TargetInstrInfo &TII,
1691 const TargetRegisterInfo &TRI,
1692 SpillOffsetMap &SpillOffsets) {
1693 // Build a set of new locations with new numbers so we can coalesce our
1694 // IntervalMap if two vreg intervals collapse to the same physical location.
1695 // Use MapVector instead of SetVector because MapVector::insert returns the
1696 // position of the previously or newly inserted element. The boolean value
1697 // tracks if the location was produced by a spill.
1698 // FIXME: This will be problematic if we ever support direct and indirect
1699 // frame index locations, i.e. expressing both variables in memory and
1700 // 'int x, *px = &x'. The "spilled" bit must become part of the location.
1702 SmallVector<unsigned, 4> LocNoMap(locations.size());
1703 for (unsigned I = 0, E = locations.size(); I != E; ++I) {
1704 bool Spilled = false;
1705 unsigned SpillOffset = 0;
1706 MachineOperand Loc = locations[I];
1707 // Only virtual registers are rewritten.
1708 if (Loc.isReg() && Loc.getReg() && Loc.getReg().isVirtual()) {
1709 Register VirtReg = Loc.getReg();
1710 if (VRM.isAssignedReg(VirtReg) && VRM.hasPhys(VirtReg)) {
1711 // This can create a %noreg operand in rare cases when the sub-register
1712 // index is no longer available. That means the user value is in a
1713 // non-existent sub-register, and %noreg is exactly what we want.
1714 Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
1715 } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
1716 // Retrieve the stack slot offset.
1717 unsigned SpillSize;
1718 const MachineRegisterInfo &MRI = MF.getRegInfo();
1719 const TargetRegisterClass *TRC = MRI.getRegClass(VirtReg);
1720 bool Success = TII.getStackSlotRange(TRC, Loc.getSubReg(), SpillSize,
1721 SpillOffset, MF);
1722
1723 // FIXME: Invalidate the location if the offset couldn't be calculated.
1724 (void)Success;
1725
1727 Spilled = true;
1728 } else {
1729 Loc.setReg(0);
1730 Loc.setSubReg(0);
1731 }
1732 }
1733
1734 // Insert this location if it doesn't already exist and record a mapping
1735 // from the old number to the new number.
1736 auto InsertResult = NewLocations.insert({Loc, {Spilled, SpillOffset}});
1737 unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first);
1738 LocNoMap[I] = NewLocNo;
1739 }
1740
1741 // Rewrite the locations and record the stack slot offsets for spills.
1742 locations.clear();
1743 SpillOffsets.clear();
1744 for (auto &Pair : NewLocations) {
1745 bool Spilled;
1746 unsigned SpillOffset;
1747 std::tie(Spilled, SpillOffset) = Pair.second;
1748 locations.push_back(Pair.first);
1749 if (Spilled) {
1750 unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair);
1751 SpillOffsets[NewLocNo] = SpillOffset;
1752 }
1753 }
1754
1755 // Update the interval map, but only coalesce left, since intervals to the
1756 // right use the old location numbers. This should merge two contiguous
1757 // DBG_VALUE intervals with different vregs that were allocated to the same
1758 // physical register.
1759 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
1760 I.setValueUnchecked(I.value().remapLocNos(LocNoMap));
1761 I.setStart(I.start());
1762 }
1763}
1764
1765/// Find an iterator for inserting a DBG_VALUE instruction.
1768 BlockSkipInstsMap &BBSkipInstsMap) {
1769 SlotIndex Start = LIS.getMBBStartIdx(MBB);
1770 Idx = Idx.getBaseIndex();
1771
1772 // Try to find an insert location by going backwards from Idx.
1774 while (!(MI = LIS.getInstructionFromIndex(Idx))) {
1775 // We've reached the beginning of MBB.
1776 if (Idx == Start) {
1777 // Retrieve the last PHI/Label/Debug location found when calling
1778 // SkipPHIsLabelsAndDebug last time. Start searching from there.
1779 //
1780 // Note the iterator kept in BBSkipInstsMap is one step back based
1781 // on the iterator returned by SkipPHIsLabelsAndDebug last time.
1782 // One exception is when SkipPHIsLabelsAndDebug returns MBB->begin(),
1783 // BBSkipInstsMap won't save it. This is to consider the case that
1784 // new instructions may be inserted at the beginning of MBB after
1785 // last call of SkipPHIsLabelsAndDebug. If we save MBB->begin() in
1786 // BBSkipInstsMap, after new non-phi/non-label/non-debug instructions
1787 // are inserted at the beginning of the MBB, the iterator in
1788 // BBSkipInstsMap won't point to the beginning of the MBB anymore.
1789 // Therefore The next search in SkipPHIsLabelsAndDebug will skip those
1790 // newly added instructions and that is unwanted.
1792 auto MapIt = BBSkipInstsMap.find(MBB);
1793 if (MapIt == BBSkipInstsMap.end())
1794 BeginIt = MBB->begin();
1795 else
1796 BeginIt = std::next(MapIt->second);
1797 auto I = MBB->SkipPHIsLabelsAndDebug(BeginIt);
1798 if (I != BeginIt)
1799 BBSkipInstsMap[MBB] = std::prev(I);
1800 return I;
1801 }
1802 Idx = Idx.getPrevIndex();
1803 }
1804
1805 // Don't insert anything after the first terminator, though.
1806 auto It = MI->isTerminator() ? MBB->getFirstTerminator()
1807 : std::next(MachineBasicBlock::iterator(MI));
1808 return skipDebugInstructionsForward(It, MBB->end());
1809}
1810
1811/// Find an iterator for inserting the next DBG_VALUE instruction
1812/// (or end if no more insert locations found).
1815 SlotIndex StopIdx, ArrayRef<MachineOperand> LocMOs,
1816 LiveIntervals &LIS, const TargetRegisterInfo &TRI) {
1818 for (const MachineOperand &LocMO : LocMOs)
1819 if (LocMO.isReg())
1820 Regs.push_back(LocMO.getReg());
1821 if (Regs.empty())
1822 return MBB->instr_end();
1823
1824 // Find the next instruction in the MBB that define the register Reg.
1825 while (I != MBB->end() && !I->isTerminator()) {
1826 if (!LIS.isNotInMIMap(*I) &&
1828 break;
1829 if (any_of(Regs, [&I, &TRI](Register &Reg) {
1830 return I->definesRegister(Reg, &TRI);
1831 }))
1832 // The insert location is directly after the instruction/bundle.
1833 return std::next(I);
1834 ++I;
1835 }
1836 return MBB->end();
1837}
1838
1839void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
1840 SlotIndex StopIdx, DbgVariableValue DbgValue,
1841 ArrayRef<bool> LocSpills,
1842 ArrayRef<unsigned> SpillOffsets,
1843 LiveIntervals &LIS, const TargetInstrInfo &TII,
1844 const TargetRegisterInfo &TRI,
1845 BlockSkipInstsMap &BBSkipInstsMap) {
1846 SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB);
1847 // Only search within the current MBB.
1848 StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx;
1850 findInsertLocation(MBB, StartIdx, LIS, BBSkipInstsMap);
1851 // Undef values don't exist in locations so create new "noreg" register MOs
1852 // for them. See getLocationNo().
1854 if (DbgValue.isUndef()) {
1855 MOs.assign(DbgValue.loc_nos().size(),
1857 /* Reg */ 0, /* isDef */ false, /* isImp */ false,
1858 /* isKill */ false, /* isDead */ false,
1859 /* isUndef */ false, /* isEarlyClobber */ false,
1860 /* SubReg */ 0, /* isDebug */ true));
1861 } else {
1862 for (unsigned LocNo : DbgValue.loc_nos())
1863 MOs.push_back(locations[LocNo]);
1864 }
1865
1866 ++NumInsertedDebugValues;
1867
1869 ->isValidLocationForIntrinsic(getDebugLoc()) &&
1870 "Expected inlined-at fields to agree");
1871
1872 // If the location was spilled, the new DBG_VALUE will be indirect. If the
1873 // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
1874 // that the original virtual register was a pointer. Also, add the stack slot
1875 // offset for the spilled register to the expression.
1876 const DIExpression *Expr = DbgValue.getExpression();
1877 bool IsIndirect = DbgValue.getWasIndirect();
1878 bool IsList = DbgValue.getWasList();
1879 for (unsigned I = 0, E = LocSpills.size(); I != E; ++I) {
1880 if (LocSpills[I]) {
1881 if (!IsList) {
1882 uint8_t DIExprFlags = DIExpression::ApplyOffset;
1883 if (IsIndirect)
1884 DIExprFlags |= DIExpression::DerefAfter;
1885 Expr = DIExpression::prepend(Expr, DIExprFlags, SpillOffsets[I]);
1886 IsIndirect = true;
1887 } else {
1888 SmallVector<uint64_t, 4> Ops;
1889 DIExpression::appendOffset(Ops, SpillOffsets[I]);
1890 Ops.push_back(dwarf::DW_OP_deref);
1891 Expr = DIExpression::appendOpsToArg(Expr, Ops, I);
1892 }
1893 }
1894
1895 assert((!LocSpills[I] || MOs[I].isFI()) &&
1896 "a spilled location must be a frame index");
1897 }
1898
1899 unsigned DbgValueOpcode =
1900 IsList ? TargetOpcode::DBG_VALUE_LIST : TargetOpcode::DBG_VALUE;
1901 do {
1902 BuildMI(*MBB, I, getDebugLoc(), TII.get(DbgValueOpcode), IsIndirect, MOs,
1903 Variable, Expr);
1904
1905 // Continue and insert DBG_VALUES after every redefinition of a register
1906 // associated with the debug value within the range
1907 I = findNextInsertLocation(MBB, I, StopIdx, MOs, LIS, TRI);
1908 } while (I != MBB->end());
1909}
1910
1911void UserLabel::insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
1912 LiveIntervals &LIS, const TargetInstrInfo &TII,
1913 BlockSkipInstsMap &BBSkipInstsMap) {
1915 findInsertLocation(MBB, Idx, LIS, BBSkipInstsMap);
1916 ++NumInsertedDebugLabels;
1917 BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_LABEL))
1918 .addMetadata(Label);
1919}
1920
1921void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
1922 const TargetInstrInfo &TII,
1923 const TargetRegisterInfo &TRI,
1924 const SpillOffsetMap &SpillOffsets,
1925 BlockSkipInstsMap &BBSkipInstsMap) {
1927
1928 for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
1929 SlotIndex Start = I.start();
1930 SlotIndex Stop = I.stop();
1931 DbgVariableValue DbgValue = I.value();
1932
1933 SmallVector<bool> SpilledLocs;
1934 SmallVector<unsigned> LocSpillOffsets;
1935 for (unsigned LocNo : DbgValue.loc_nos()) {
1936 auto SpillIt =
1937 !DbgValue.isUndef() ? SpillOffsets.find(LocNo) : SpillOffsets.end();
1938 bool Spilled = SpillIt != SpillOffsets.end();
1939 SpilledLocs.push_back(Spilled);
1940 LocSpillOffsets.push_back(Spilled ? SpillIt->second : 0);
1941 }
1942
1943 // If the interval start was trimmed to the lexical scope insert the
1944 // DBG_VALUE at the previous index (otherwise it appears after the
1945 // first instruction in the range).
1946 if (trimmedDefs.count(Start))
1947 Start = Start.getPrevIndex();
1948
1949 LLVM_DEBUG(auto &dbg = dbgs(); dbg << "\t[" << Start << ';' << Stop << "):";
1950 DbgValue.printLocNos(dbg));
1952 SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
1953
1954 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1955 insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs, LocSpillOffsets,
1956 LIS, TII, TRI, BBSkipInstsMap);
1957 // This interval may span multiple basic blocks.
1958 // Insert a DBG_VALUE into each one.
1959 while (Stop > MBBEnd) {
1960 // Move to the next block.
1961 Start = MBBEnd;
1962 if (++MBB == MFEnd)
1963 break;
1964 MBBEnd = LIS.getMBBEndIdx(&*MBB);
1965 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1966 insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs,
1967 LocSpillOffsets, LIS, TII, TRI, BBSkipInstsMap);
1968 }
1969 LLVM_DEBUG(dbgs() << '\n');
1970 if (MBB == MFEnd)
1971 break;
1972
1973 ++I;
1974 }
1975}
1976
1977void UserLabel::emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
1978 BlockSkipInstsMap &BBSkipInstsMap) {
1979 LLVM_DEBUG(dbgs() << "\t" << loc);
1981
1982 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB));
1983 insertDebugLabel(&*MBB, loc, LIS, TII, BBSkipInstsMap);
1984
1985 LLVM_DEBUG(dbgs() << '\n');
1986}
1987
1989 LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
1990 if (!MF)
1991 return;
1992
1993 // Instructions may have been erased since the last allocator run.
1994 canonicalizeIndexes(*LIS->getSlotIndexes());
1995
1996 BlockSkipInstsMap BBSkipInstsMap;
1997 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1998 SpillOffsetMap SpillOffsets;
1999 for (auto &userValue : userValues) {
2000 LLVM_DEBUG(userValue->print(dbgs(), TRI));
2001 userValue->rewriteLocations(*VRM, *MF, *TII, *TRI, SpillOffsets);
2002 userValue->emitDebugValues(VRM, *LIS, *TII, *TRI, SpillOffsets,
2003 BBSkipInstsMap);
2004 }
2005 LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG LABELS **********\n");
2006 for (auto &userLabel : userLabels) {
2007 LLVM_DEBUG(userLabel->print(dbgs(), TRI));
2008 userLabel->emitDebugLabel(*LIS, *TII, BBSkipInstsMap);
2009 }
2010
2011 LLVM_DEBUG(dbgs() << "********** EMITTING DEBUG PHIS **********\n");
2012
2013 auto Slots = LIS->getSlotIndexes();
2014 for (auto &It : PHIValToPos) {
2015 // For each ex-PHI, identify its physreg location or stack slot, and emit
2016 // a DBG_PHI for it.
2017 unsigned InstNum = It.first;
2018 auto Slot = It.second.SI;
2019 Register Reg = It.second.Reg;
2020 unsigned SubReg = It.second.SubReg;
2021
2022 MachineBasicBlock *OrigMBB = Slots->getMBBFromIndex(Slot);
2023 if (VRM->isAssignedReg(Reg) && VRM->hasPhys(Reg)) {
2024 unsigned PhysReg = VRM->getPhys(Reg);
2025 if (SubReg != 0)
2026 PhysReg = TRI->getSubReg(PhysReg, SubReg);
2027
2028 auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(),
2029 TII->get(TargetOpcode::DBG_PHI));
2030 Builder.addReg(PhysReg);
2031 Builder.addImm(InstNum);
2032 } else if (VRM->getStackSlot(Reg) != VirtRegMap::NO_STACK_SLOT) {
2033 const MachineRegisterInfo &MRI = MF->getRegInfo();
2034 const TargetRegisterClass *TRC = MRI.getRegClass(Reg);
2035 unsigned SpillSize, SpillOffset;
2036
2037 unsigned regSizeInBits = TRI->getRegSizeInBits(*TRC);
2038 if (SubReg)
2039 regSizeInBits = TRI->getSubRegIdxSize(SubReg);
2040
2041 // Test whether this location is legal with the given subreg. If the
2042 // subregister has a nonzero offset, drop this location, it's too complex
2043 // to describe. (TODO: future work).
2044 bool Success =
2045 TII->getStackSlotRange(TRC, SubReg, SpillSize, SpillOffset, *MF);
2046
2047 if (Success && SpillOffset == 0) {
2048 auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(),
2049 TII->get(TargetOpcode::DBG_PHI));
2050 Builder.addFrameIndex(VRM->getStackSlot(Reg));
2051 Builder.addImm(InstNum);
2052 // Record how large the original value is. The stack slot might be
2053 // merged and altered during optimisation, but we will want to know how
2054 // large the value is, at this DBG_PHI.
2055 Builder.addImm(regSizeInBits);
2056 }
2057
2058 LLVM_DEBUG(if (SpillOffset != 0) {
2059 dbgs() << "DBG_PHI for " << printReg(Reg, TRI, SubReg)
2060 << " has nonzero offset\n";
2061 });
2062 }
2063 // If there was no mapping for a value ID, it's optimized out. Create no
2064 // DBG_PHI, and any variables using this value will become optimized out.
2065 }
2066 MF->DebugPHIPositions.clear();
2067
2068 LLVM_DEBUG(dbgs() << "********** EMITTING INSTR REFERENCES **********\n");
2069
2070 // Re-insert any debug instrs back in the position they were. We must
2071 // re-insert in the same order to ensure that debug instructions don't swap,
2072 // which could re-order assignments. Do so in a batch -- once we find the
2073 // insert position, insert all instructions at the same SlotIdx. They are
2074 // guaranteed to appear in-sequence in StashedDebugInstrs because we insert
2075 // them in order.
2076 for (auto *StashIt = StashedDebugInstrs.begin();
2077 StashIt != StashedDebugInstrs.end(); ++StashIt) {
2078 SlotIndex Idx = StashIt->Idx;
2079 MachineBasicBlock *MBB = StashIt->MBB;
2080 MachineInstr *MI = StashIt->MI;
2081
2082 auto EmitInstsHere = [this, &StashIt, MBB, Idx,
2083 MI](MachineBasicBlock::iterator InsertPos) {
2084 // Insert this debug instruction.
2085 MBB->insert(InsertPos, MI);
2086
2087 // Look at subsequent stashed debug instructions: if they're at the same
2088 // index, insert those too.
2089 auto NextItem = std::next(StashIt);
2090 while (NextItem != StashedDebugInstrs.end() && NextItem->Idx == Idx) {
2091 assert(NextItem->MBB == MBB && "Instrs with same slot index should be"
2092 "in the same block");
2093 MBB->insert(InsertPos, NextItem->MI);
2094 StashIt = NextItem;
2095 NextItem = std::next(StashIt);
2096 };
2097 };
2098
2099 // Start block index: find the first non-debug instr in the block, and
2100 // insert before it.
2101 if (Idx == Slots->getMBBStartIdx(MBB)) {
2102 MachineBasicBlock::iterator InsertPos =
2103 findInsertLocation(MBB, Idx, *LIS, BBSkipInstsMap);
2104 EmitInstsHere(InsertPos);
2105 continue;
2106 }
2107
2108 if (MachineInstr *Pos = Slots->getInstructionFromIndex(Idx)) {
2109 // Insert at the end of any debug instructions.
2110 auto PostDebug = std::next(MachineBasicBlock::iterator(Pos));
2111 PostDebug = skipDebugInstructionsForward(PostDebug, MBB->end());
2112 EmitInstsHere(PostDebug);
2113 } else {
2114 // Insert position disappeared; walk forwards through slots until we
2115 // find a new one.
2116 SlotIndex End = Slots->getMBBEndIdx(MBB);
2117 for (; Idx < End; Idx = Slots->getNextNonNullIndex(Idx)) {
2118 Pos = Slots->getInstructionFromIndex(Idx);
2119 if (Pos) {
2120 EmitInstsHere(Pos->getIterator());
2121 break;
2122 }
2123 }
2124
2125 // We have reached the end of the block and didn't find anywhere to
2126 // insert! It's not safe to discard any debug instructions; place them
2127 // in front of the first terminator, or in front of end().
2128 if (Idx >= End) {
2129 auto TermIt = MBB->getFirstTerminator();
2130 EmitInstsHere(TermIt);
2131 }
2132 }
2133 }
2134
2135 EmitDone = true;
2136 BBSkipInstsMap.clear();
2137}
2138
2140 if (PImpl)
2141 PImpl->emitDebugValues(VRM);
2142}
2143
2144#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2146#endif
2147
2149 if (PImpl)
2150 PImpl->print(OS);
2151}
#define Success
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
Function Alias Analysis false
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:686
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
This file implements a coalescing interval map for small objects.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static void printExtendedName(raw_ostream &OS, const DINode *Node, const DILocation *DL)
static MachineBasicBlock::iterator findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx, LiveIntervals &LIS, BlockSkipInstsMap &BBSkipInstsMap)
Find an iterator for inserting a DBG_VALUE instruction.
static MachineBasicBlock::iterator findNextInsertLocation(MachineBasicBlock *MBB, MachineBasicBlock::iterator I, SlotIndex StopIdx, ArrayRef< MachineOperand > LocMOs, LiveIntervals &LIS, const TargetRegisterInfo &TRI)
Find an iterator for inserting the next DBG_VALUE instruction (or end if no more insert locations fou...
DenseMap< MachineBasicBlock *, MachineBasicBlock::iterator > BlockSkipInstsMap
Cache to save the location where it can be used as the starting position as input for calling Machine...
IntervalMap< SlotIndex, DbgVariableValue, 4 > LocMap
Map of where a user value is live to that value.
static cl::opt< bool > EnableLDV("live-debug-variables", cl::init(true), cl::desc("Enable the live debug variables pass"), cl::Hidden)
static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS, const LLVMContext &Ctx)
DenseMap< unsigned, unsigned > SpillOffsetMap
Map of stack slot offsets for spilled locations.
static void removeDebugInstrs(MachineFunction &mf)
static LoopDeletionResult merge(LoopDeletionResult A, LoopDeletionResult B)
#define I(x, y, z)
Definition MD5.cpp:57
static bool isUndef(const MachineInstr &MI)
Register Reg
Register const TargetRegisterInfo * TRI
This file implements a map that provides insertion order iteration.
std::pair< uint64_t, uint64_t > Interval
Promote Memory to Register
Definition Mem2Reg.cpp:110
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
static bool isReg(const MCInst &MI, unsigned OpNo)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
SI Optimize VGPR LiveRange
Func MI getDebugLoc()))
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
Class recording the (high level) value of a variable.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
DWARF expression.
static LLVM_ABI void appendOffset(SmallVectorImpl< uint64_t > &Ops, int64_t Offset)
Append Ops with operations to apply the Offset.
static LLVM_ABI DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
static LLVM_ABI std::optional< FragmentInfo > getFragmentInfo(expr_op_iterator Start, expr_op_iterator End)
Retrieve the details of this fragment expression.
static LLVM_ABI DIExpression * replaceArg(const DIExpression *Expr, uint64_t OldArg, uint64_t NewArg)
Create a copy of Expr with each instance of DW_OP_LLVM_arg, \p OldArg replaced with DW_OP_LLVM_arg,...
static LLVM_ABI std::optional< DIExpression * > createFragmentExpression(const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits)
Create a DIExpression to describe one part of an aggregate variable that is fragmented across multipl...
static LLVM_ABI DIExpression * prepend(const DIExpression *Expr, uint8_t Flags, int64_t Offset=0)
Prepend DIExpr with a deref and offset operation and optionally turn it into a stack value or/and an ...
Tagged DWARF-like metadata node.
A debug info location.
Definition DebugLoc.h:126
Identifies a unique instance of a variable.
bool empty() const
Definition DenseMap.h:717
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:767
iterator end()
Definition DenseMap.h:687
DISubprogram * getSubprogram() const
Get the attached subprogram.
const_iterator begin() const
const_iterator find(KeyT x) const
find - Return an iterator pointing to the first interval ending at or after x, or end().
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
This class provides interface to collect and use lexical scoping information from machine instruction...
LLVM_ABI Result run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
bool runOnMachineFunction(MachineFunction &) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
void getAnalysisUsage(AnalysisUsage &) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void splitRegister(Register OldReg, ArrayRef< Register > NewRegs)
Replace all references to OldReg with NewRegs.
bool runOnMachineFunction(MachineFunction &mf, bool InstrRef)
void mapVirtReg(Register VirtReg, UserValue *EC)
Map virtual register to an equivalence class.
void canonicalizeIndexes(const SlotIndexes &SI)
Replace every stale index held by this analysis.
void emitDebugValues(VirtRegMap *VRM)
Recreate DBG_VALUE instruction from data structures.
void splitPHIRegister(Register OldReg, ArrayRef< Register > NewRegs)
Replace any PHI referring to OldReg with its corresponding NewReg, if present.
LLVM_ABI void canonicalizeIndexes(const SlotIndexes &SI)
canonicalizeIndexes - Replace every SlotIndex held by this analysis that refers to an erased instruct...
LLVM_ABI ~LiveDebugVariables()
void dump() const
dump - Print data structures to dbgs().
LLVM_ABI void splitRegister(Register OldReg, ArrayRef< Register > NewRegs, LiveIntervals &LIS)
splitRegister - Move any user variables in OldReg to the live ranges in NewRegs where they are live.
LLVM_ABI LiveDebugVariables()
Implementation of the LiveDebugVariables pass.
LLVM_ABI void print(raw_ostream &OS) const
LLVM_ABI void analyze(MachineFunction &MF, LiveIntervals *LIS)
LLVM_ABI void emitDebugValues(VirtRegMap *VRM)
emitDebugValues - Emit new DBG_VALUE instructions reflecting the changes that happened during registe...
LLVM_ABI bool invalidate(MachineFunction &MF, const PreservedAnalyses &PA, MachineFunctionAnalysisManager::Invalidator &Inv)
LiveInterval - This class represents the liveness of a register, or stack slot.
Register reg() const
bool hasInterval(Register Reg) const
SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const
Return the first index in the given basic block.
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
SlotIndexes * getSlotIndexes() const
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Return the last index in the given basic block.
LiveInterval & getInterval(Register Reg)
bool isNotInMIMap(const MachineInstr &Instr) const
Returns true if the specified machine instr has been removed or was never entered in the map.
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
VNInfo * valueOutOrDead() const
Returns the value alive at the end of the instruction, if any.
Segments::iterator iterator
const Segment * getSegmentContaining(SlotIndex Idx) const
Return the segment that contains the specified index, or null if there is none.
iterator advanceTo(iterator I, SlotIndex Pos)
advanceTo - Advance the specified iterator to point to the Segment containing the specified position,...
bool empty() const
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
iterator begin()
SlotIndex beginIndex() const
beginIndex - Return the lowest numbered slot covered.
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
LLVM_ABI iterator find(SlotIndex Pos)
find - Return an iterator pointing to the first segment that ends after Pos, or end().
LLVMContext & getContext() const
Definition Metadata.h:1245
An RAII based helper class to modify MachineFunctionProperties when running pass.
void push_back(MachineInstr *MI)
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
MachineInstrBundleIterator< MachineInstr > iterator
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Location of a PHI instruction that is also a debug-info variable value, for the duration of register ...
bool useDebugInstrRef() const
Returns true if the function's variable locations are tracked with instruction referencing.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
void push_back(MachineBasicBlock *MBB)
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
const MachineInstrBuilder & addMetadata(const MDNode *MD) const
Representation of each machine instruction.
bool isCopy() const
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
void setIsDebug(bool Val=true)
Register getReg() const
getReg - Returns the register number.
LLVM_ABI bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
static MachineOperand CreateFI(int Idx)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
iterator_range< use_nodbg_iterator > use_nodbg_operands(Register Reg) const
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
iterator begin()
Definition MapVector.h:67
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:126
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:66
SlotIndex getNextIndex() const
Returns the next index.
static bool isEarlierEqualInstr(SlotIndex A, SlotIndex B)
Return true if A refers to the same instruction as B or an earlier one.
SlotIndex getNextSlot() const
Returns the next slot in the index list.
SlotIndexes pass.
SlotIndex getIndexBefore(const MachineInstr &MI) const
getIndexBefore - Returns the index of the last indexed instruction before MI, or the start index of i...
SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const
Returns the first index in the given basic block.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
iterator erase(const_iterator CI)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
unsigned id
The ID number of this value.
SlotIndex def
The index of the defining instruction.
int getStackSlot(Register virtReg) const
returns the stack slot mapped to the specified virtual register
Definition VirtRegMap.h:172
MachineFunction & getMachineFunction() const
Definition VirtRegMap.h:75
MCRegister getPhys(Register virtReg) const
returns the physical register mapped to the specified virtual register
Definition VirtRegMap.h:91
bool hasPhys(Register virtReg) const
returns true if the specified virtual register is mapped to a physical register
Definition VirtRegMap.h:87
bool isAssignedReg(Register virtReg) const
returns true if the specified virtual register is not mapped to a stack slot or rematerialized.
Definition VirtRegMap.h:162
static constexpr int NO_STACK_SLOT
Definition VirtRegMap.h:66
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool operator!=(uint64_t V1, const APInt &V2)
Definition APInt.h:2139
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
std::pair< const MachineInstr *, const MachineInstr * > InsnRange
This is used to track range of instructions with identical lexical scope.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
IterT skipDebugInstructionsForward(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ Success
The lock was released successfully.
@ Other
Any other memory.
Definition ModRef.h:68
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1901
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29