LLVM 23.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"
49#include "llvm/Config/llvm-config.h"
51#include "llvm/IR/DebugLoc.h"
52#include "llvm/IR/Function.h"
54#include "llvm/Pass.h"
57#include "llvm/Support/Debug.h"
59#include <algorithm>
60#include <cassert>
61#include <iterator>
62#include <map>
63#include <memory>
64#include <optional>
65#include <utility>
66
67using namespace llvm;
68
69#define DEBUG_TYPE "livedebugvars"
70
71static cl::opt<bool>
72EnableLDV("live-debug-variables", cl::init(true),
73 cl::desc("Enable the live debug variables pass"), cl::Hidden);
74
75STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
76STATISTIC(NumInsertedDebugLabels, "Number of DBG_LABELs inserted");
77
79
81 "Debug Variable Analysis", false, false)
85 "Debug Variable Analysis", false, true)
86
88 AnalysisUsage &AU) const {
89 AU.addRequired<MachineDominatorTreeWrapperPass>();
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 /// Rewrite virtual register locations according to the provided virtual
479 /// register map. Record the stack slot offsets for the locations that
480 /// were spilled.
481 void rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
482 const TargetInstrInfo &TII,
483 const TargetRegisterInfo &TRI,
484 SpillOffsetMap &SpillOffsets);
485
486 /// Recreate DBG_VALUE instruction from data structures.
487 void emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
488 const TargetInstrInfo &TII,
489 const TargetRegisterInfo &TRI,
490 const SpillOffsetMap &SpillOffsets,
491 BlockSkipInstsMap &BBSkipInstsMap);
492
493 /// Return DebugLoc of this UserValue.
494 const DebugLoc &getDebugLoc() { return dl; }
495
496 void print(raw_ostream &, const TargetRegisterInfo *);
497};
498
499/// A user label is a part of a debug info user label.
500class UserLabel {
501 const DILabel *Label; ///< The debug info label we are part of.
502 DebugLoc dl; ///< The debug location for the label. This is
503 ///< used by dwarf writer to find lexical scope.
504 SlotIndex loc; ///< Slot used by the debug label.
505
506 /// Insert a DBG_LABEL into MBB at Idx.
507 void insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
508 LiveIntervals &LIS, const TargetInstrInfo &TII,
509 BlockSkipInstsMap &BBSkipInstsMap);
510
511public:
512 /// Create a new UserLabel.
513 UserLabel(const DILabel *label, DebugLoc L, SlotIndex Idx)
514 : Label(label), dl(std::move(L)), loc(Idx) {}
515
516 /// Does this UserLabel match the parameters?
517 bool matches(const DILabel *L, const DILocation *IA,
518 const SlotIndex Index) const {
519 return Label == L && dl->getInlinedAt() == IA && loc == Index;
520 }
521
522 /// Recreate DBG_LABEL instruction from data structures.
523 void emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
524 BlockSkipInstsMap &BBSkipInstsMap);
525
526 /// Return DebugLoc of this UserLabel.
527 const DebugLoc &getDebugLoc() { return dl; }
528
529 void print(raw_ostream &, const TargetRegisterInfo *);
530};
531
532} // end anonymous namespace
533
534namespace llvm {
535
537 LocMap::Allocator allocator;
538 MachineFunction *MF = nullptr;
539 LiveIntervals *LIS;
540 const TargetRegisterInfo *TRI;
541
542 /// Position and VReg of a PHI instruction during register allocation.
543 struct PHIValPos {
544 SlotIndex SI; /// Slot where this PHI occurs.
545 Register Reg; /// VReg this PHI occurs in.
546 unsigned SubReg; /// Qualifiying subregister for Reg.
547 };
548
549 /// Map from debug instruction number to PHI position during allocation.
550 std::map<unsigned, PHIValPos> PHIValToPos;
551 /// Index of, for each VReg, which debug instruction numbers and corresponding
552 /// PHIs are sensitive to splitting. Each VReg may have multiple PHI defs,
553 /// at different positions.
555
556 /// Record for any debug instructions unlinked from their blocks during
557 /// regalloc. Stores the instr and it's location, so that they can be
558 /// re-inserted after regalloc is over.
559 struct InstrPos {
560 MachineInstr *MI; ///< Debug instruction, unlinked from it's block.
561 SlotIndex Idx; ///< Slot position where MI should be re-inserted.
562 MachineBasicBlock *MBB; ///< Block that MI was in.
563 };
564
565 /// Collection of stored debug instructions, preserved until after regalloc.
566 SmallVector<InstrPos, 32> StashedDebugInstrs;
567
568 /// Whether emitDebugValues is called.
569 bool EmitDone = false;
570
571 /// Whether the machine function is modified during the pass.
572 bool ModifiedMF = false;
573
574 /// All allocated UserValue instances.
576
577 /// All allocated UserLabel instances.
579
580 /// Map virtual register to eq class leader.
582 VRMap virtRegToEqClass;
583
584 /// Map to find existing UserValue instances.
586 UVMap userVarMap;
587
588 /// Find or create a UserValue.
589 UserValue *getUserValue(const DILocalVariable *Var,
590 std::optional<DIExpression::FragmentInfo> Fragment,
591 const DebugLoc &DL);
592
593 /// Find the EC leader for VirtReg or null.
594 UserValue *lookupVirtReg(Register VirtReg);
595
596 /// Add DBG_VALUE instruction to our maps.
597 ///
598 /// \param MI DBG_VALUE instruction
599 /// \param Idx Last valid SLotIndex before instruction.
600 ///
601 /// \returns True if the DBG_VALUE instruction should be deleted.
602 bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
603
604 /// Track variable location debug instructions while using the instruction
605 /// referencing implementation. Such debug instructions do not need to be
606 /// updated during regalloc because they identify instructions rather than
607 /// register locations. However, they needs to be removed from the
608 /// MachineFunction during regalloc, then re-inserted later, to avoid
609 /// disrupting the allocator.
610 ///
611 /// \param MI Any DBG_VALUE / DBG_INSTR_REF / DBG_PHI instruction
612 /// \param Idx Last valid SlotIndex before instruction
613 ///
614 /// \returns Iterator to continue processing from after unlinking.
616
617 /// Add DBG_LABEL instruction to UserLabel.
618 ///
619 /// \param MI DBG_LABEL instruction
620 /// \param Idx Last valid SlotIndex before instruction.
621 ///
622 /// \returns True if the DBG_LABEL instruction should be deleted.
623 bool handleDebugLabel(MachineInstr &MI, SlotIndex Idx);
624
625 /// Collect and erase all DBG_VALUE instructions, adding a UserValue def
626 /// for each instruction.
627 ///
628 /// \param mf MachineFunction to be scanned.
629 /// \param InstrRef Whether to operate in instruction referencing mode. If
630 /// true, most of LiveDebugVariables doesn't run.
631 ///
632 /// \returns True if any debug values were found.
633 bool collectDebugValues(MachineFunction &mf, bool InstrRef);
634
635 /// Compute the live intervals of all user values after collecting all
636 /// their def points.
637 void computeIntervals();
638
639public:
640 LDVImpl(LiveIntervals *LIS) : LIS(LIS) {}
641
642 bool runOnMachineFunction(MachineFunction &mf, bool InstrRef);
643
644 /// Release all memory.
645 void clear() {
646 MF = nullptr;
647 PHIValToPos.clear();
648 RegToPHIIdx.clear();
649 StashedDebugInstrs.clear();
650 userValues.clear();
651 userLabels.clear();
652 virtRegToEqClass.clear();
653 userVarMap.clear();
654 // Make sure we call emitDebugValues if the machine function was modified.
655 assert((!ModifiedMF || EmitDone) &&
656 "Dbg values are not emitted in LDV");
657 EmitDone = false;
658 ModifiedMF = false;
659 }
660
661 /// Map virtual register to an equivalence class.
662 void mapVirtReg(Register VirtReg, UserValue *EC);
663
664 /// Replace any PHI referring to OldReg with its corresponding NewReg, if
665 /// present.
666 void splitPHIRegister(Register OldReg, ArrayRef<Register> NewRegs);
667
668 /// Replace all references to OldReg with NewRegs.
669 void splitRegister(Register OldReg, ArrayRef<Register> NewRegs);
670
671 /// Recreate DBG_VALUE instruction from data structures.
672 void emitDebugValues(VirtRegMap *VRM);
673
674 void print(raw_ostream&);
675};
676
677/// Implementation of the LiveDebugVariables pass.
678
682
683} // namespace llvm
684
685static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
686 const LLVMContext &Ctx) {
687 if (!DL)
688 return;
689
690 auto *Scope = cast<DIScope>(DL.getScope());
691 // Omit the directory, because it's likely to be long and uninteresting.
692 CommentOS << Scope->getFilename();
693 CommentOS << ':' << DL.getLine();
694 if (DL.getCol() != 0)
695 CommentOS << ':' << DL.getCol();
696
697 DebugLoc InlinedAtDL = DL.getInlinedAt();
698 if (!InlinedAtDL)
699 return;
700
701 CommentOS << " @[ ";
702 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
703 CommentOS << " ]";
704}
705
706static void printExtendedName(raw_ostream &OS, const DINode *Node,
707 const DILocation *DL) {
708 const LLVMContext &Ctx = Node->getContext();
709 StringRef Res;
710 unsigned Line = 0;
711 if (const auto *V = dyn_cast<const DILocalVariable>(Node)) {
712 Res = V->getName();
713 Line = V->getLine();
714 } else if (const auto *L = dyn_cast<const DILabel>(Node)) {
715 Res = L->getName();
716 Line = L->getLine();
717 }
718
719 if (!Res.empty())
720 OS << Res << "," << Line;
721 auto *InlinedAt = DL ? DL->getInlinedAt() : nullptr;
722 if (InlinedAt) {
723 if (DebugLoc InlinedAtDL = InlinedAt) {
724 OS << " @[";
725 printDebugLoc(InlinedAtDL, OS, Ctx);
726 OS << "]";
727 }
728 }
729}
730
731void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
732 OS << "!\"";
733 printExtendedName(OS, Variable, dl);
734
735 OS << "\"\t";
736 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
737 OS << " [" << I.start() << ';' << I.stop() << "):";
738 if (I.value().isUndef())
739 OS << " undef";
740 else {
741 I.value().printLocNos(OS);
742 if (I.value().getWasIndirect())
743 OS << " ind";
744 else if (I.value().getWasList())
745 OS << " list";
746 }
747 }
748 for (unsigned i = 0, e = locations.size(); i != e; ++i) {
749 OS << " Loc" << i << '=';
750 locations[i].print(OS, TRI);
751 }
752 OS << '\n';
753}
754
755void UserLabel::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
756 OS << "!\"";
757 printExtendedName(OS, Label, dl);
758
759 OS << "\"\t";
760 OS << loc;
761 OS << '\n';
762}
763
765 OS << "********** DEBUG VARIABLES **********\n";
766 for (auto &userValue : userValues)
767 userValue->print(OS, TRI);
768 OS << "********** DEBUG LABELS **********\n";
769 for (auto &userLabel : userLabels)
770 userLabel->print(OS, TRI);
771}
772
773void UserValue::mapVirtRegs(LiveDebugVariables::LDVImpl *LDV) {
774 for (const MachineOperand &MO : locations)
775 if (MO.isReg() && MO.getReg().isVirtual())
776 LDV->mapVirtReg(MO.getReg(), this);
777}
778
779UserValue *LiveDebugVariables::LDVImpl::getUserValue(
780 const DILocalVariable *Var,
781 std::optional<DIExpression::FragmentInfo> Fragment, const DebugLoc &DL) {
782 // FIXME: Handle partially overlapping fragments. See
783 // https://reviews.llvm.org/D70121#1849741.
784 DebugVariable ID(Var, Fragment, DL->getInlinedAt());
785 UserValue *&UV = userVarMap[ID];
786 if (!UV) {
787 userValues.push_back(
788 std::make_unique<UserValue>(Var, Fragment, DL, allocator));
789 UV = userValues.back().get();
790 }
791 return UV;
792}
793
795 assert(VirtReg.isVirtual() && "Only map VirtRegs");
796 UserValue *&Leader = virtRegToEqClass[VirtReg];
797 Leader = UserValue::merge(Leader, EC);
798}
799
800UserValue *LiveDebugVariables::LDVImpl::lookupVirtReg(Register VirtReg) {
801 if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
802 return UV->getLeader();
803 return nullptr;
804}
805
806bool LiveDebugVariables::LDVImpl::handleDebugValue(MachineInstr &MI,
807 SlotIndex Idx) {
808 // DBG_VALUE loc, offset, variable, expr
809 // DBG_VALUE_LIST variable, expr, locs...
810 if (!MI.isDebugValue()) {
811 LLVM_DEBUG(dbgs() << "Can't handle non-DBG_VALUE*: " << MI);
812 return false;
813 }
814 if (!MI.getDebugVariableOp().isMetadata()) {
815 LLVM_DEBUG(dbgs() << "Can't handle DBG_VALUE* with invalid variable: "
816 << MI);
817 return false;
818 }
819 if (MI.isNonListDebugValue() &&
820 (MI.getNumOperands() != 4 ||
821 !(MI.getDebugOffset().isImm() || MI.getDebugOffset().isReg()))) {
822 LLVM_DEBUG(dbgs() << "Can't handle malformed DBG_VALUE: " << MI);
823 return false;
824 }
825
826 // Detect invalid DBG_VALUE instructions, with a debug-use of a virtual
827 // register that hasn't been defined yet. If we do not remove those here, then
828 // the re-insertion of the DBG_VALUE instruction after register allocation
829 // will be incorrect.
830 bool Discard = false;
831 for (const MachineOperand &Op : MI.debug_operands()) {
832 if (Op.isReg() && Op.getReg().isVirtual()) {
833 const Register Reg = Op.getReg();
834 if (!LIS->hasInterval(Reg)) {
835 // The DBG_VALUE is described by a virtual register that does not have a
836 // live interval. Discard the DBG_VALUE.
837 Discard = true;
838 LLVM_DEBUG(dbgs() << "Discarding debug info (no LIS interval): " << Idx
839 << " " << MI);
840 } else {
841 // The DBG_VALUE is only valid if either Reg is live out from Idx, or
842 // Reg is defined dead at Idx (where Idx is the slot index for the
843 // instruction preceding the DBG_VALUE).
844 const LiveInterval &LI = LIS->getInterval(Reg);
845 LiveQueryResult LRQ = LI.Query(Idx);
846 if (!LRQ.valueOutOrDead()) {
847 // We have found a DBG_VALUE with the value in a virtual register that
848 // is not live. Discard the DBG_VALUE.
849 Discard = true;
850 LLVM_DEBUG(dbgs() << "Discarding debug info (reg not live): " << Idx
851 << " " << MI);
852 }
853 }
854 }
855 }
856
857 // Get or create the UserValue for (variable,offset) here.
858 bool IsIndirect = MI.isDebugOffsetImm();
859 if (IsIndirect)
860 assert(MI.getDebugOffset().getImm() == 0 &&
861 "DBG_VALUE with nonzero offset");
862 bool IsList = MI.isDebugValueList();
863 const DILocalVariable *Var = MI.getDebugVariable();
864 const DIExpression *Expr = MI.getDebugExpression();
865 UserValue *UV = getUserValue(Var, Expr->getFragmentInfo(), MI.getDebugLoc());
866 if (!Discard)
867 UV->addDef(Idx,
868 ArrayRef<MachineOperand>(MI.debug_operands().begin(),
869 MI.debug_operands().end()),
870 IsIndirect, IsList, *Expr);
871 else {
872 MachineOperand MO = MachineOperand::CreateReg(0U, false);
873 MO.setIsDebug();
874 // We should still pass a list the same size as MI.debug_operands() even if
875 // all MOs are undef, so that DbgVariableValue can correctly adjust the
876 // expression while removing the duplicated undefs.
877 SmallVector<MachineOperand, 4> UndefMOs(MI.getNumDebugOperands(), MO);
878 UV->addDef(Idx, UndefMOs, false, IsList, *Expr);
879 }
880 return true;
881}
882
884LiveDebugVariables::LDVImpl::handleDebugInstr(MachineInstr &MI, SlotIndex Idx) {
885 assert(MI.isDebugValueLike() || MI.isDebugPHI());
886
887 // In instruction referencing mode, there should be no DBG_VALUE instructions
888 // that refer to virtual registers. They might still refer to constants.
889 if (MI.isDebugValueLike())
890 assert(none_of(MI.debug_operands(),
891 [](const MachineOperand &MO) {
892 return MO.isReg() && MO.getReg().isVirtual();
893 }) &&
894 "MIs should not refer to Virtual Registers in InstrRef mode.");
895
896 // Unlink the instruction, store it in the debug instructions collection.
897 auto NextInst = std::next(MI.getIterator());
898 auto *MBB = MI.getParent();
899 MI.removeFromParent();
900 StashedDebugInstrs.push_back({&MI, Idx, MBB});
901 return NextInst;
902}
903
904bool LiveDebugVariables::LDVImpl::handleDebugLabel(MachineInstr &MI,
905 SlotIndex Idx) {
906 // DBG_LABEL label
907 if (MI.getNumOperands() != 1 || !MI.getOperand(0).isMetadata()) {
908 LLVM_DEBUG(dbgs() << "Can't handle " << MI);
909 return false;
910 }
911
912 // Get or create the UserLabel for label here.
913 const DILabel *Label = MI.getDebugLabel();
914 const DebugLoc &DL = MI.getDebugLoc();
915 bool Found = false;
916 for (auto const &L : userLabels) {
917 if (L->matches(Label, DL->getInlinedAt(), Idx)) {
918 Found = true;
919 break;
920 }
921 }
922 if (!Found)
923 userLabels.push_back(std::make_unique<UserLabel>(Label, DL, Idx));
924
925 return true;
926}
927
928bool LiveDebugVariables::LDVImpl::collectDebugValues(MachineFunction &mf,
929 bool InstrRef) {
930 bool Changed = false;
931 for (MachineBasicBlock &MBB : mf) {
932 for (MachineBasicBlock::iterator MBBI = MBB.begin(), MBBE = MBB.end();
933 MBBI != MBBE;) {
934 // Use the first debug instruction in the sequence to get a SlotIndex
935 // for following consecutive debug instructions.
936 if (!MBBI->isDebugOrPseudoInstr()) {
937 ++MBBI;
938 continue;
939 }
940 // Debug instructions has no slot index. Use the previous
941 // non-debug instruction's SlotIndex as its SlotIndex.
942 SlotIndex Idx =
943 MBBI == MBB.begin()
944 ? LIS->getMBBStartIdx(&MBB)
945 : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
946 // Handle consecutive debug instructions with the same slot index.
947 do {
948 // In instruction referencing mode, pass each instr to handleDebugInstr
949 // to be unlinked. Ignore DBG_VALUE_LISTs -- they refer to vregs, and
950 // need to go through the normal live interval splitting process.
951 if (InstrRef && (MBBI->isNonListDebugValue() || MBBI->isDebugPHI() ||
952 MBBI->isDebugRef())) {
953 MBBI = handleDebugInstr(*MBBI, Idx);
954 Changed = true;
955 // In normal debug mode, use the dedicated DBG_VALUE / DBG_LABEL handler
956 // to track things through register allocation, and erase the instr.
957 } else if ((MBBI->isDebugValue() && handleDebugValue(*MBBI, Idx)) ||
958 (MBBI->isDebugLabel() && handleDebugLabel(*MBBI, Idx))) {
959 MBBI = MBB.erase(MBBI);
960 Changed = true;
961 } else
962 ++MBBI;
963 } while (MBBI != MBBE && MBBI->isDebugOrPseudoInstr());
964 }
965 }
966 return Changed;
967}
968
969void UserValue::extendDef(
970 SlotIndex Idx, DbgVariableValue DbgValue,
971 SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>>
972 &LiveIntervalInfo,
973 std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> &Kills,
974 LiveIntervals &LIS) {
975 SlotIndex Start = Idx;
976 MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
977 SlotIndex Stop = LIS.getMBBEndIdx(MBB);
978 LocMap::iterator I = locInts.find(Start);
979
980 // Limit to the intersection of the VNIs' live ranges.
981 for (auto &LII : LiveIntervalInfo) {
982 LiveRange *LR = LII.second.first;
983 assert(LR && LII.second.second && "Missing range info for Idx.");
984 LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
985 assert(Segment && Segment->valno == LII.second.second &&
986 "Invalid VNInfo for Idx given?");
987 if (Segment->end < Stop) {
988 Stop = Segment->end;
989 Kills = {Stop, {LII.first}};
990 } else if (Segment->end == Stop && Kills) {
991 // If multiple locations end at the same place, track all of them in
992 // Kills.
993 Kills->second.push_back(LII.first);
994 }
995 }
996
997 // There could already be a short def at Start.
998 if (I.valid() && I.start() <= Start) {
999 // Stop when meeting a different location or an already extended interval.
1000 Start = Start.getNextSlot();
1001 if (I.value() != DbgValue || I.stop() != Start) {
1002 // Clear `Kills`, as we have a new def available.
1003 Kills = std::nullopt;
1004 return;
1005 }
1006 // This is a one-slot placeholder. Just skip it.
1007 ++I;
1008 }
1009
1010 // Limited by the next def.
1011 if (I.valid() && I.start() < Stop) {
1012 Stop = I.start();
1013 // Clear `Kills`, as we have a new def available.
1014 Kills = std::nullopt;
1015 }
1016
1017 if (Start < Stop) {
1018 DbgVariableValue ExtDbgValue(DbgValue);
1019 I.insert(Start, Stop, std::move(ExtDbgValue));
1020 }
1021}
1022
1023void UserValue::addDefsFromCopies(
1024 DbgVariableValue DbgValue,
1025 SmallVectorImpl<std::pair<unsigned, LiveInterval *>> &LocIntervals,
1026 SlotIndex KilledAt,
1027 SmallVectorImpl<std::pair<SlotIndex, DbgVariableValue>> &NewDefs,
1028 MachineRegisterInfo &MRI, LiveIntervals &LIS) {
1029 // Don't track copies from physregs, there are too many uses.
1030 if (any_of(LocIntervals,
1031 [](auto LocI) { return !LocI.second->reg().isVirtual(); }))
1032 return;
1033
1034 // Collect all the (vreg, valno) pairs that are copies of LI.
1035 SmallDenseMap<unsigned,
1037 CopyValues;
1038 for (auto &LocInterval : LocIntervals) {
1039 unsigned LocNo = LocInterval.first;
1040 LiveInterval *LI = LocInterval.second;
1041 for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg())) {
1042 MachineInstr *MI = MO.getParent();
1043 // Copies of the full value.
1044 if (MO.getSubReg() || !MI->isCopy())
1045 continue;
1046 Register DstReg = MI->getOperand(0).getReg();
1047
1048 // Don't follow copies to physregs. These are usually setting up call
1049 // arguments, and the argument registers are always call clobbered. We are
1050 // better off in the source register which could be a callee-saved
1051 // register, or it could be spilled.
1052 if (!DstReg.isVirtual())
1053 continue;
1054
1055 // Is the value extended to reach this copy? If not, another def may be
1056 // blocking it, or we are looking at a wrong value of LI.
1057 SlotIndex Idx = LIS.getInstructionIndex(*MI);
1058 LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
1059 if (!I.valid() || I.value() != DbgValue)
1060 continue;
1061
1062 if (!LIS.hasInterval(DstReg))
1063 continue;
1064 LiveInterval *DstLI = &LIS.getInterval(DstReg);
1065 const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
1066 assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
1067 CopyValues[LocNo].push_back(std::make_pair(DstLI, DstVNI));
1068 }
1069 }
1070
1071 if (CopyValues.empty())
1072 return;
1073
1074#if !defined(NDEBUG)
1075 for (auto &LocInterval : LocIntervals)
1076 LLVM_DEBUG(dbgs() << "Got " << CopyValues[LocInterval.first].size()
1077 << " copies of " << *LocInterval.second << '\n');
1078#endif
1079
1080 // Try to add defs of the copied values for the kill point. Check that there
1081 // isn't already a def at Idx.
1082 LocMap::iterator I = locInts.find(KilledAt);
1083 if (I.valid() && I.start() <= KilledAt)
1084 return;
1085 DbgVariableValue NewValue(DbgValue);
1086 for (auto &LocInterval : LocIntervals) {
1087 unsigned LocNo = LocInterval.first;
1088 bool FoundCopy = false;
1089 for (auto &LIAndVNI : CopyValues[LocNo]) {
1090 LiveInterval *DstLI = LIAndVNI.first;
1091 const VNInfo *DstVNI = LIAndVNI.second;
1092 if (DstLI->getVNInfoAt(KilledAt) != DstVNI)
1093 continue;
1094 LLVM_DEBUG(dbgs() << "Kill at " << KilledAt << " covered by valno #"
1095 << DstVNI->id << " in " << *DstLI << '\n');
1096 MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
1097 assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
1098 unsigned NewLocNo = getLocationNo(CopyMI->getOperand(0));
1099 NewValue = NewValue.changeLocNo(LocNo, NewLocNo);
1100 FoundCopy = true;
1101 break;
1102 }
1103 // If there are any killed locations we can't find a copy for, we can't
1104 // extend the variable value.
1105 if (!FoundCopy)
1106 return;
1107 }
1108 I.insert(KilledAt, KilledAt.getNextSlot(), NewValue);
1109 NewDefs.push_back(std::make_pair(KilledAt, NewValue));
1110}
1111
1112void UserValue::computeIntervals(MachineRegisterInfo &MRI,
1113 const TargetRegisterInfo &TRI,
1114 LiveIntervals &LIS, LexicalScopes &LS) {
1116
1117 // Collect all defs to be extended (Skipping undefs).
1118 for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
1119 if (!I.value().isUndef())
1120 Defs.push_back(std::make_pair(I.start(), I.value()));
1121
1122 // Extend all defs, and possibly add new ones along the way.
1123 for (unsigned i = 0; i != Defs.size(); ++i) {
1124 SlotIndex Idx = Defs[i].first;
1125 DbgVariableValue DbgValue = Defs[i].second;
1126 SmallDenseMap<unsigned, std::pair<LiveRange *, const VNInfo *>> LIs;
1127 bool ShouldExtendDef = false;
1128 for (unsigned LocNo : DbgValue.loc_nos()) {
1129 const MachineOperand &LocMO = locations[LocNo];
1130 if (!LocMO.isReg() || !LocMO.getReg().isVirtual()) {
1131 ShouldExtendDef |= !LocMO.isReg();
1132 continue;
1133 }
1134 ShouldExtendDef = true;
1135 LiveInterval *LI = nullptr;
1136 const VNInfo *VNI = nullptr;
1137 if (LIS.hasInterval(LocMO.getReg())) {
1138 LI = &LIS.getInterval(LocMO.getReg());
1139 VNI = LI->getVNInfoAt(Idx);
1140 }
1141 if (LI && VNI)
1142 LIs[LocNo] = {LI, VNI};
1143 }
1144 if (ShouldExtendDef) {
1145 std::optional<std::pair<SlotIndex, SmallVector<unsigned>>> Kills;
1146 extendDef(Idx, DbgValue, LIs, Kills, LIS);
1147
1148 if (Kills) {
1150 bool AnySubreg = false;
1151 for (unsigned LocNo : Kills->second) {
1152 const MachineOperand &LocMO = this->locations[LocNo];
1153 if (LocMO.getSubReg()) {
1154 AnySubreg = true;
1155 break;
1156 }
1157 LiveInterval *LI = &LIS.getInterval(LocMO.getReg());
1158 KilledLocIntervals.push_back({LocNo, LI});
1159 }
1160
1161 // FIXME: Handle sub-registers in addDefsFromCopies. The problem is that
1162 // if the original location for example is %vreg0:sub_hi, and we find a
1163 // full register copy in addDefsFromCopies (at the moment it only
1164 // handles full register copies), then we must add the sub1 sub-register
1165 // index to the new location. However, that is only possible if the new
1166 // virtual register is of the same regclass (or if there is an
1167 // equivalent sub-register in that regclass). For now, simply skip
1168 // handling copies if a sub-register is involved.
1169 if (!AnySubreg)
1170 addDefsFromCopies(DbgValue, KilledLocIntervals, Kills->first, Defs,
1171 MRI, LIS);
1172 }
1173 }
1174
1175 // For physregs, we only mark the start slot idx. DwarfDebug will see it
1176 // as if the DBG_VALUE is valid up until the end of the basic block, or
1177 // the next def of the physical register. So we do not need to extend the
1178 // range. It might actually happen that the DBG_VALUE is the last use of
1179 // the physical register (e.g. if this is an unused input argument to a
1180 // function).
1181 }
1182
1183 // The computed intervals may extend beyond the range of the debug
1184 // location's lexical scope. In this case, splitting of an interval
1185 // can result in an interval outside of the scope being created,
1186 // causing extra unnecessary DBG_VALUEs to be emitted. To prevent
1187 // this, trim the intervals to the lexical scope in the case of inlined
1188 // variables, since heavy inlining may cause production of dramatically big
1189 // number of DBG_VALUEs to be generated.
1190 if (!dl.getInlinedAt())
1191 return;
1192
1193 LexicalScope *Scope = LS.findLexicalScope(dl);
1194 if (!Scope)
1195 return;
1196
1197 SlotIndex PrevEnd;
1198 LocMap::iterator I = locInts.begin();
1199
1200 // Iterate over the lexical scope ranges. Each time round the loop
1201 // we check the intervals for overlap with the end of the previous
1202 // range and the start of the next. The first range is handled as
1203 // a special case where there is no PrevEnd.
1204 for (const InsnRange &Range : Scope->getRanges()) {
1205 SlotIndex RStart = LIS.getInstructionIndex(*Range.first);
1206 SlotIndex REnd = LIS.getInstructionIndex(*Range.second);
1207
1208 // Variable locations at the first instruction of a block should be
1209 // based on the block's SlotIndex, not the first instruction's index.
1210 if (Range.first == Range.first->getParent()->begin())
1211 RStart = LIS.getSlotIndexes()->getIndexBefore(*Range.first);
1212
1213 // At the start of each iteration I has been advanced so that
1214 // I.stop() >= PrevEnd. Check for overlap.
1215 if (PrevEnd && I.start() < PrevEnd) {
1216 SlotIndex IStop = I.stop();
1217 DbgVariableValue DbgValue = I.value();
1218
1219 // Stop overlaps previous end - trim the end of the interval to
1220 // the scope range.
1221 I.setStopUnchecked(PrevEnd);
1222 ++I;
1223
1224 // If the interval also overlaps the start of the "next" (i.e.
1225 // current) range create a new interval for the remainder (which
1226 // may be further trimmed).
1227 if (RStart < IStop)
1228 I.insert(RStart, IStop, DbgValue);
1229 }
1230
1231 // Advance I so that I.stop() >= RStart, and check for overlap.
1232 I.advanceTo(RStart);
1233 if (!I.valid())
1234 return;
1235
1236 if (I.start() < RStart) {
1237 // Interval start overlaps range - trim to the scope range.
1238 I.setStartUnchecked(RStart);
1239 // Remember that this interval was trimmed.
1240 trimmedDefs.insert(RStart);
1241 }
1242
1243 // The end of a lexical scope range is the last instruction in the
1244 // range. To convert to an interval we need the index of the
1245 // instruction after it.
1246 REnd = REnd.getNextIndex();
1247
1248 // Advance I to first interval outside current range.
1249 I.advanceTo(REnd);
1250 if (!I.valid())
1251 return;
1252
1253 PrevEnd = REnd;
1254 }
1255
1256 // Check for overlap with end of final range.
1257 if (PrevEnd && I.start() < PrevEnd)
1258 I.setStopUnchecked(PrevEnd);
1259}
1260
1261void LiveDebugVariables::LDVImpl::computeIntervals() {
1262 LexicalScopes LS;
1263 LS.scanFunction(*MF);
1264
1265 for (const auto &UV : userValues) {
1266 UV->computeIntervals(MF->getRegInfo(), *TRI, *LIS, LS);
1267 UV->mapVirtRegs(this);
1268 }
1269}
1270
1272 bool InstrRef) {
1273 clear();
1274 MF = &mf;
1275 TRI = mf.getSubtarget().getRegisterInfo();
1276 LLVM_DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
1277 << mf.getName() << " **********\n");
1278
1279 bool Changed = collectDebugValues(mf, InstrRef);
1280 computeIntervals();
1281 LLVM_DEBUG(print(dbgs()));
1282
1283 // Collect the set of VReg / SlotIndexs where PHIs occur; index the sensitive
1284 // VRegs too, for when we're notified of a range split.
1285 SlotIndexes *Slots = LIS->getSlotIndexes();
1286 for (const auto &PHIIt : MF->DebugPHIPositions) {
1287 const MachineFunction::DebugPHIRegallocPos &Position = PHIIt.second;
1288 MachineBasicBlock *MBB = Position.MBB;
1289 Register Reg = Position.Reg;
1290 unsigned SubReg = Position.SubReg;
1291 SlotIndex SI = Slots->getMBBStartIdx(MBB);
1292 PHIValPos VP = {SI, Reg, SubReg};
1293 PHIValToPos.insert(std::make_pair(PHIIt.first, VP));
1294 RegToPHIIdx[Reg].push_back(PHIIt.first);
1295 }
1296
1297 ModifiedMF = Changed;
1298 return Changed;
1299}
1300
1302 for (MachineBasicBlock &MBB : mf) {
1304 if (MI.isDebugInstr())
1305 MBB.erase(&MI);
1306 }
1307}
1308
1310 MachineFunction &mf) {
1311 auto *LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
1312
1313 Impl = std::make_unique<LiveDebugVariables>();
1314 Impl->analyze(mf, LIS);
1315 return false;
1316}
1317
1318AnalysisKey LiveDebugVariablesAnalysis::Key;
1319
1323 MFPropsModifier _(*this, MF);
1324
1325 auto *LIS = &MFAM.getResult<LiveIntervalsAnalysis>(MF);
1327 LDV.analyze(MF, LIS);
1328 return LDV;
1329}
1330
1338
1340 if (PImpl)
1341 PImpl->clear();
1342}
1343
1346 MachineFunctionAnalysisManager::Invalidator &) {
1347 auto PAC = PA.getChecker<LiveDebugVariablesAnalysis>();
1348 // Some architectures split the register allocation into multiple phases based
1349 // on register classes. This requires preserving analyses between the phases
1350 // by default.
1351 return !PAC.preservedWhenStateless();
1352}
1353
1355 if (!EnableLDV)
1356 return;
1357 if (!MF.getFunction().getSubprogram()) {
1359 return;
1360 }
1361
1362 PImpl.reset(new LDVImpl(LIS));
1363
1364 // Have we been asked to track variable locations using instruction
1365 // referencing?
1366 bool InstrRef = MF.useDebugInstrRef();
1367 PImpl->runOnMachineFunction(MF, InstrRef);
1368}
1369
1370//===----------------------------------------------------------------------===//
1371// Live Range Splitting
1372//===----------------------------------------------------------------------===//
1373
1374bool
1375UserValue::splitLocation(unsigned OldLocNo, ArrayRef<Register> NewRegs,
1376 LiveIntervals& LIS) {
1377 LLVM_DEBUG({
1378 dbgs() << "Splitting Loc" << OldLocNo << '\t';
1379 print(dbgs(), nullptr);
1380 });
1381 bool DidChange = false;
1382 LocMap::iterator LocMapI;
1383 LocMapI.setMap(locInts);
1384 for (Register NewReg : NewRegs) {
1385 LiveInterval *LI = &LIS.getInterval(NewReg);
1386 if (LI->empty())
1387 continue;
1388
1389 // Don't allocate the new LocNo until it is needed.
1390 unsigned NewLocNo = UndefLocNo;
1391
1392 // Iterate over the overlaps between locInts and LI.
1393 LocMapI.find(LI->beginIndex());
1394 if (!LocMapI.valid())
1395 continue;
1396 LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
1397 LiveInterval::iterator LIE = LI->end();
1398 while (LocMapI.valid() && LII != LIE) {
1399 // At this point, we know that LocMapI.stop() > LII->start.
1400 LII = LI->advanceTo(LII, LocMapI.start());
1401 if (LII == LIE)
1402 break;
1403
1404 // Now LII->end > LocMapI.start(). Do we have an overlap?
1405 if (LocMapI.value().containsLocNo(OldLocNo) &&
1406 LII->start < LocMapI.stop()) {
1407 // Overlapping correct location. Allocate NewLocNo now.
1408 if (NewLocNo == UndefLocNo) {
1409 MachineOperand MO = MachineOperand::CreateReg(LI->reg(), false);
1410 MO.setSubReg(locations[OldLocNo].getSubReg());
1411 NewLocNo = getLocationNo(MO);
1412 DidChange = true;
1413 }
1414
1415 SlotIndex LStart = LocMapI.start();
1416 SlotIndex LStop = LocMapI.stop();
1417 DbgVariableValue OldDbgValue = LocMapI.value();
1418
1419 // Trim LocMapI down to the LII overlap.
1420 if (LStart < LII->start)
1421 LocMapI.setStartUnchecked(LII->start);
1422 if (LStop > LII->end)
1423 LocMapI.setStopUnchecked(LII->end);
1424
1425 // Change the value in the overlap. This may trigger coalescing.
1426 LocMapI.setValue(OldDbgValue.changeLocNo(OldLocNo, NewLocNo));
1427
1428 // Re-insert any removed OldDbgValue ranges.
1429 if (LStart < LocMapI.start()) {
1430 LocMapI.insert(LStart, LocMapI.start(), OldDbgValue);
1431 ++LocMapI;
1432 assert(LocMapI.valid() && "Unexpected coalescing");
1433 }
1434 if (LStop > LocMapI.stop()) {
1435 ++LocMapI;
1436 LocMapI.insert(LII->end, LStop, OldDbgValue);
1437 --LocMapI;
1438 }
1439 }
1440
1441 // Advance to the next overlap.
1442 if (LII->end < LocMapI.stop()) {
1443 if (++LII == LIE)
1444 break;
1445 LocMapI.advanceTo(LII->start);
1446 } else {
1447 ++LocMapI;
1448 if (!LocMapI.valid())
1449 break;
1450 LII = LI->advanceTo(LII, LocMapI.start());
1451 }
1452 }
1453 }
1454
1455 // Finally, remove OldLocNo unless it is still used by some interval in the
1456 // locInts map. One case when OldLocNo still is in use is when the register
1457 // has been spilled. In such situations the spilled register is kept as a
1458 // location until rewriteLocations is called (VirtRegMap is mapping the old
1459 // register to the spill slot). So for a while we can have locations that map
1460 // to virtual registers that have been removed from both the MachineFunction
1461 // and from LiveIntervals.
1462 //
1463 // We may also just be using the location for a value with a different
1464 // expression.
1465 removeLocationIfUnused(OldLocNo);
1466
1467 LLVM_DEBUG({
1468 dbgs() << "Split result: \t";
1469 print(dbgs(), nullptr);
1470 });
1471 return DidChange;
1472}
1473
1474bool
1475UserValue::splitRegister(Register OldReg, ArrayRef<Register> NewRegs,
1476 LiveIntervals &LIS) {
1477 bool DidChange = false;
1478 // Split locations referring to OldReg. Iterate backwards so splitLocation can
1479 // safely erase unused locations.
1480 for (unsigned i = locations.size(); i ; --i) {
1481 unsigned LocNo = i-1;
1482 const MachineOperand *Loc = &locations[LocNo];
1483 if (!Loc->isReg() || Loc->getReg() != OldReg)
1484 continue;
1485 DidChange |= splitLocation(LocNo, NewRegs, LIS);
1486 }
1487 return DidChange;
1488}
1489
1491 ArrayRef<Register> NewRegs) {
1492 auto RegIt = RegToPHIIdx.find(OldReg);
1493 if (RegIt == RegToPHIIdx.end())
1494 return;
1495
1496 std::vector<std::pair<Register, unsigned>> NewRegIdxes;
1497 // Iterate over all the debug instruction numbers affected by this split.
1498 for (unsigned InstrID : RegIt->second) {
1499 auto PHIIt = PHIValToPos.find(InstrID);
1500 assert(PHIIt != PHIValToPos.end());
1501 const SlotIndex &Slot = PHIIt->second.SI;
1502 assert(OldReg == PHIIt->second.Reg);
1503
1504 // Find the new register that covers this position.
1505 for (auto NewReg : NewRegs) {
1506 const LiveInterval &LI = LIS->getInterval(NewReg);
1507 auto LII = LI.find(Slot);
1508 if (LII != LI.end() && LII->start <= Slot) {
1509 // This new register covers this PHI position, record this for indexing.
1510 NewRegIdxes.push_back(std::make_pair(NewReg, InstrID));
1511 // Record that this value lives in a different VReg now.
1512 PHIIt->second.Reg = NewReg;
1513 break;
1514 }
1515 }
1516
1517 // If we do not find a new register covering this PHI, then register
1518 // allocation has dropped its location, for example because it's not live.
1519 // The old VReg will not be mapped to a physreg, and the instruction
1520 // number will have been optimized out.
1521 }
1522
1523 // Re-create register index using the new register numbers.
1524 RegToPHIIdx.erase(RegIt);
1525 for (auto &RegAndInstr : NewRegIdxes)
1526 RegToPHIIdx[RegAndInstr.first].push_back(RegAndInstr.second);
1527}
1528
1530 ArrayRef<Register> NewRegs) {
1531 // Consider whether this split range affects any PHI locations.
1532 splitPHIRegister(OldReg, NewRegs);
1533
1534 // Check whether any intervals mapped by a DBG_VALUE were split and need
1535 // updating.
1536 bool DidChange = false;
1537 for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
1538 DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
1539
1540 if (!DidChange)
1541 return;
1542
1543 // Map all of the new virtual registers.
1544 UserValue *UV = lookupVirtReg(OldReg);
1545 for (Register NewReg : NewRegs)
1546 mapVirtReg(NewReg, UV);
1547}
1548
1551 if (PImpl)
1552 PImpl->splitRegister(OldReg, NewRegs);
1553}
1554
1555void UserValue::rewriteLocations(VirtRegMap &VRM, const MachineFunction &MF,
1556 const TargetInstrInfo &TII,
1557 const TargetRegisterInfo &TRI,
1558 SpillOffsetMap &SpillOffsets) {
1559 // Build a set of new locations with new numbers so we can coalesce our
1560 // IntervalMap if two vreg intervals collapse to the same physical location.
1561 // Use MapVector instead of SetVector because MapVector::insert returns the
1562 // position of the previously or newly inserted element. The boolean value
1563 // tracks if the location was produced by a spill.
1564 // FIXME: This will be problematic if we ever support direct and indirect
1565 // frame index locations, i.e. expressing both variables in memory and
1566 // 'int x, *px = &x'. The "spilled" bit must become part of the location.
1568 SmallVector<unsigned, 4> LocNoMap(locations.size());
1569 for (unsigned I = 0, E = locations.size(); I != E; ++I) {
1570 bool Spilled = false;
1571 unsigned SpillOffset = 0;
1572 MachineOperand Loc = locations[I];
1573 // Only virtual registers are rewritten.
1574 if (Loc.isReg() && Loc.getReg() && Loc.getReg().isVirtual()) {
1575 Register VirtReg = Loc.getReg();
1576 if (VRM.isAssignedReg(VirtReg) && VRM.hasPhys(VirtReg)) {
1577 // This can create a %noreg operand in rare cases when the sub-register
1578 // index is no longer available. That means the user value is in a
1579 // non-existent sub-register, and %noreg is exactly what we want.
1580 Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
1581 } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
1582 // Retrieve the stack slot offset.
1583 unsigned SpillSize;
1584 const MachineRegisterInfo &MRI = MF.getRegInfo();
1585 const TargetRegisterClass *TRC = MRI.getRegClass(VirtReg);
1586 bool Success = TII.getStackSlotRange(TRC, Loc.getSubReg(), SpillSize,
1587 SpillOffset, MF);
1588
1589 // FIXME: Invalidate the location if the offset couldn't be calculated.
1590 (void)Success;
1591
1593 Spilled = true;
1594 } else {
1595 Loc.setReg(0);
1596 Loc.setSubReg(0);
1597 }
1598 }
1599
1600 // Insert this location if it doesn't already exist and record a mapping
1601 // from the old number to the new number.
1602 auto InsertResult = NewLocations.insert({Loc, {Spilled, SpillOffset}});
1603 unsigned NewLocNo = std::distance(NewLocations.begin(), InsertResult.first);
1604 LocNoMap[I] = NewLocNo;
1605 }
1606
1607 // Rewrite the locations and record the stack slot offsets for spills.
1608 locations.clear();
1609 SpillOffsets.clear();
1610 for (auto &Pair : NewLocations) {
1611 bool Spilled;
1612 unsigned SpillOffset;
1613 std::tie(Spilled, SpillOffset) = Pair.second;
1614 locations.push_back(Pair.first);
1615 if (Spilled) {
1616 unsigned NewLocNo = std::distance(&*NewLocations.begin(), &Pair);
1617 SpillOffsets[NewLocNo] = SpillOffset;
1618 }
1619 }
1620
1621 // Update the interval map, but only coalesce left, since intervals to the
1622 // right use the old location numbers. This should merge two contiguous
1623 // DBG_VALUE intervals with different vregs that were allocated to the same
1624 // physical register.
1625 for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
1626 I.setValueUnchecked(I.value().remapLocNos(LocNoMap));
1627 I.setStart(I.start());
1628 }
1629}
1630
1631/// Find an iterator for inserting a DBG_VALUE instruction.
1634 BlockSkipInstsMap &BBSkipInstsMap) {
1635 SlotIndex Start = LIS.getMBBStartIdx(MBB);
1636 Idx = Idx.getBaseIndex();
1637
1638 // Try to find an insert location by going backwards from Idx.
1640 while (!(MI = LIS.getInstructionFromIndex(Idx))) {
1641 // We've reached the beginning of MBB.
1642 if (Idx == Start) {
1643 // Retrieve the last PHI/Label/Debug location found when calling
1644 // SkipPHIsLabelsAndDebug last time. Start searching from there.
1645 //
1646 // Note the iterator kept in BBSkipInstsMap is one step back based
1647 // on the iterator returned by SkipPHIsLabelsAndDebug last time.
1648 // One exception is when SkipPHIsLabelsAndDebug returns MBB->begin(),
1649 // BBSkipInstsMap won't save it. This is to consider the case that
1650 // new instructions may be inserted at the beginning of MBB after
1651 // last call of SkipPHIsLabelsAndDebug. If we save MBB->begin() in
1652 // BBSkipInstsMap, after new non-phi/non-label/non-debug instructions
1653 // are inserted at the beginning of the MBB, the iterator in
1654 // BBSkipInstsMap won't point to the beginning of the MBB anymore.
1655 // Therefore The next search in SkipPHIsLabelsAndDebug will skip those
1656 // newly added instructions and that is unwanted.
1658 auto MapIt = BBSkipInstsMap.find(MBB);
1659 if (MapIt == BBSkipInstsMap.end())
1660 BeginIt = MBB->begin();
1661 else
1662 BeginIt = std::next(MapIt->second);
1663 auto I = MBB->SkipPHIsLabelsAndDebug(BeginIt);
1664 if (I != BeginIt)
1665 BBSkipInstsMap[MBB] = std::prev(I);
1666 return I;
1667 }
1668 Idx = Idx.getPrevIndex();
1669 }
1670
1671 // Don't insert anything after the first terminator, though.
1672 auto It = MI->isTerminator() ? MBB->getFirstTerminator()
1673 : std::next(MachineBasicBlock::iterator(MI));
1674 return skipDebugInstructionsForward(It, MBB->end());
1675}
1676
1677/// Find an iterator for inserting the next DBG_VALUE instruction
1678/// (or end if no more insert locations found).
1681 SlotIndex StopIdx, ArrayRef<MachineOperand> LocMOs,
1682 LiveIntervals &LIS, const TargetRegisterInfo &TRI) {
1684 for (const MachineOperand &LocMO : LocMOs)
1685 if (LocMO.isReg())
1686 Regs.push_back(LocMO.getReg());
1687 if (Regs.empty())
1688 return MBB->instr_end();
1689
1690 // Find the next instruction in the MBB that define the register Reg.
1691 while (I != MBB->end() && !I->isTerminator()) {
1692 if (!LIS.isNotInMIMap(*I) &&
1694 break;
1695 if (any_of(Regs, [&I, &TRI](Register &Reg) {
1696 return I->definesRegister(Reg, &TRI);
1697 }))
1698 // The insert location is directly after the instruction/bundle.
1699 return std::next(I);
1700 ++I;
1701 }
1702 return MBB->end();
1703}
1704
1705void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex StartIdx,
1706 SlotIndex StopIdx, DbgVariableValue DbgValue,
1707 ArrayRef<bool> LocSpills,
1708 ArrayRef<unsigned> SpillOffsets,
1709 LiveIntervals &LIS, const TargetInstrInfo &TII,
1710 const TargetRegisterInfo &TRI,
1711 BlockSkipInstsMap &BBSkipInstsMap) {
1712 SlotIndex MBBEndIdx = LIS.getMBBEndIdx(&*MBB);
1713 // Only search within the current MBB.
1714 StopIdx = (MBBEndIdx < StopIdx) ? MBBEndIdx : StopIdx;
1716 findInsertLocation(MBB, StartIdx, LIS, BBSkipInstsMap);
1717 // Undef values don't exist in locations so create new "noreg" register MOs
1718 // for them. See getLocationNo().
1720 if (DbgValue.isUndef()) {
1721 MOs.assign(DbgValue.loc_nos().size(),
1723 /* Reg */ 0, /* isDef */ false, /* isImp */ false,
1724 /* isKill */ false, /* isDead */ false,
1725 /* isUndef */ false, /* isEarlyClobber */ false,
1726 /* SubReg */ 0, /* isDebug */ true));
1727 } else {
1728 for (unsigned LocNo : DbgValue.loc_nos())
1729 MOs.push_back(locations[LocNo]);
1730 }
1731
1732 ++NumInsertedDebugValues;
1733
1735 ->isValidLocationForIntrinsic(getDebugLoc()) &&
1736 "Expected inlined-at fields to agree");
1737
1738 // If the location was spilled, the new DBG_VALUE will be indirect. If the
1739 // original DBG_VALUE was indirect, we need to add DW_OP_deref to indicate
1740 // that the original virtual register was a pointer. Also, add the stack slot
1741 // offset for the spilled register to the expression.
1742 const DIExpression *Expr = DbgValue.getExpression();
1743 bool IsIndirect = DbgValue.getWasIndirect();
1744 bool IsList = DbgValue.getWasList();
1745 for (unsigned I = 0, E = LocSpills.size(); I != E; ++I) {
1746 if (LocSpills[I]) {
1747 if (!IsList) {
1748 uint8_t DIExprFlags = DIExpression::ApplyOffset;
1749 if (IsIndirect)
1750 DIExprFlags |= DIExpression::DerefAfter;
1751 Expr = DIExpression::prepend(Expr, DIExprFlags, SpillOffsets[I]);
1752 IsIndirect = true;
1753 } else {
1754 SmallVector<uint64_t, 4> Ops;
1755 DIExpression::appendOffset(Ops, SpillOffsets[I]);
1756 Ops.push_back(dwarf::DW_OP_deref);
1757 Expr = DIExpression::appendOpsToArg(Expr, Ops, I);
1758 }
1759 }
1760
1761 assert((!LocSpills[I] || MOs[I].isFI()) &&
1762 "a spilled location must be a frame index");
1763 }
1764
1765 unsigned DbgValueOpcode =
1766 IsList ? TargetOpcode::DBG_VALUE_LIST : TargetOpcode::DBG_VALUE;
1767 do {
1768 BuildMI(*MBB, I, getDebugLoc(), TII.get(DbgValueOpcode), IsIndirect, MOs,
1769 Variable, Expr);
1770
1771 // Continue and insert DBG_VALUES after every redefinition of a register
1772 // associated with the debug value within the range
1773 I = findNextInsertLocation(MBB, I, StopIdx, MOs, LIS, TRI);
1774 } while (I != MBB->end());
1775}
1776
1777void UserLabel::insertDebugLabel(MachineBasicBlock *MBB, SlotIndex Idx,
1778 LiveIntervals &LIS, const TargetInstrInfo &TII,
1779 BlockSkipInstsMap &BBSkipInstsMap) {
1781 findInsertLocation(MBB, Idx, LIS, BBSkipInstsMap);
1782 ++NumInsertedDebugLabels;
1783 BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_LABEL))
1784 .addMetadata(Label);
1785}
1786
1787void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
1788 const TargetInstrInfo &TII,
1789 const TargetRegisterInfo &TRI,
1790 const SpillOffsetMap &SpillOffsets,
1791 BlockSkipInstsMap &BBSkipInstsMap) {
1793
1794 for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
1795 SlotIndex Start = I.start();
1796 SlotIndex Stop = I.stop();
1797 DbgVariableValue DbgValue = I.value();
1798
1799 SmallVector<bool> SpilledLocs;
1800 SmallVector<unsigned> LocSpillOffsets;
1801 for (unsigned LocNo : DbgValue.loc_nos()) {
1802 auto SpillIt =
1803 !DbgValue.isUndef() ? SpillOffsets.find(LocNo) : SpillOffsets.end();
1804 bool Spilled = SpillIt != SpillOffsets.end();
1805 SpilledLocs.push_back(Spilled);
1806 LocSpillOffsets.push_back(Spilled ? SpillIt->second : 0);
1807 }
1808
1809 // If the interval start was trimmed to the lexical scope insert the
1810 // DBG_VALUE at the previous index (otherwise it appears after the
1811 // first instruction in the range).
1812 if (trimmedDefs.count(Start))
1813 Start = Start.getPrevIndex();
1814
1815 LLVM_DEBUG(auto &dbg = dbgs(); dbg << "\t[" << Start << ';' << Stop << "):";
1816 DbgValue.printLocNos(dbg));
1818 SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
1819
1820 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1821 insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs, LocSpillOffsets,
1822 LIS, TII, TRI, BBSkipInstsMap);
1823 // This interval may span multiple basic blocks.
1824 // Insert a DBG_VALUE into each one.
1825 while (Stop > MBBEnd) {
1826 // Move to the next block.
1827 Start = MBBEnd;
1828 if (++MBB == MFEnd)
1829 break;
1830 MBBEnd = LIS.getMBBEndIdx(&*MBB);
1831 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB) << '-' << MBBEnd);
1832 insertDebugValue(&*MBB, Start, Stop, DbgValue, SpilledLocs,
1833 LocSpillOffsets, LIS, TII, TRI, BBSkipInstsMap);
1834 }
1835 LLVM_DEBUG(dbgs() << '\n');
1836 if (MBB == MFEnd)
1837 break;
1838
1839 ++I;
1840 }
1841}
1842
1843void UserLabel::emitDebugLabel(LiveIntervals &LIS, const TargetInstrInfo &TII,
1844 BlockSkipInstsMap &BBSkipInstsMap) {
1845 LLVM_DEBUG(dbgs() << "\t" << loc);
1847
1848 LLVM_DEBUG(dbgs() << ' ' << printMBBReference(*MBB));
1849 insertDebugLabel(&*MBB, loc, LIS, TII, BBSkipInstsMap);
1850
1851 LLVM_DEBUG(dbgs() << '\n');
1852}
1853
1855 LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
1856 if (!MF)
1857 return;
1858
1859 BlockSkipInstsMap BBSkipInstsMap;
1860 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1861 SpillOffsetMap SpillOffsets;
1862 for (auto &userValue : userValues) {
1863 LLVM_DEBUG(userValue->print(dbgs(), TRI));
1864 userValue->rewriteLocations(*VRM, *MF, *TII, *TRI, SpillOffsets);
1865 userValue->emitDebugValues(VRM, *LIS, *TII, *TRI, SpillOffsets,
1866 BBSkipInstsMap);
1867 }
1868 LLVM_DEBUG(dbgs() << "********** EMITTING LIVE DEBUG LABELS **********\n");
1869 for (auto &userLabel : userLabels) {
1870 LLVM_DEBUG(userLabel->print(dbgs(), TRI));
1871 userLabel->emitDebugLabel(*LIS, *TII, BBSkipInstsMap);
1872 }
1873
1874 LLVM_DEBUG(dbgs() << "********** EMITTING DEBUG PHIS **********\n");
1875
1876 auto Slots = LIS->getSlotIndexes();
1877 for (auto &It : PHIValToPos) {
1878 // For each ex-PHI, identify its physreg location or stack slot, and emit
1879 // a DBG_PHI for it.
1880 unsigned InstNum = It.first;
1881 auto Slot = It.second.SI;
1882 Register Reg = It.second.Reg;
1883 unsigned SubReg = It.second.SubReg;
1884
1885 MachineBasicBlock *OrigMBB = Slots->getMBBFromIndex(Slot);
1886 if (VRM->isAssignedReg(Reg) && VRM->hasPhys(Reg)) {
1887 unsigned PhysReg = VRM->getPhys(Reg);
1888 if (SubReg != 0)
1889 PhysReg = TRI->getSubReg(PhysReg, SubReg);
1890
1891 auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(),
1892 TII->get(TargetOpcode::DBG_PHI));
1893 Builder.addReg(PhysReg);
1894 Builder.addImm(InstNum);
1895 } else if (VRM->getStackSlot(Reg) != VirtRegMap::NO_STACK_SLOT) {
1896 const MachineRegisterInfo &MRI = MF->getRegInfo();
1897 const TargetRegisterClass *TRC = MRI.getRegClass(Reg);
1898 unsigned SpillSize, SpillOffset;
1899
1900 unsigned regSizeInBits = TRI->getRegSizeInBits(*TRC);
1901 if (SubReg)
1902 regSizeInBits = TRI->getSubRegIdxSize(SubReg);
1903
1904 // Test whether this location is legal with the given subreg. If the
1905 // subregister has a nonzero offset, drop this location, it's too complex
1906 // to describe. (TODO: future work).
1907 bool Success =
1908 TII->getStackSlotRange(TRC, SubReg, SpillSize, SpillOffset, *MF);
1909
1910 if (Success && SpillOffset == 0) {
1911 auto Builder = BuildMI(*OrigMBB, OrigMBB->begin(), DebugLoc(),
1912 TII->get(TargetOpcode::DBG_PHI));
1913 Builder.addFrameIndex(VRM->getStackSlot(Reg));
1914 Builder.addImm(InstNum);
1915 // Record how large the original value is. The stack slot might be
1916 // merged and altered during optimisation, but we will want to know how
1917 // large the value is, at this DBG_PHI.
1918 Builder.addImm(regSizeInBits);
1919 }
1920
1921 LLVM_DEBUG(if (SpillOffset != 0) {
1922 dbgs() << "DBG_PHI for " << printReg(Reg, TRI, SubReg)
1923 << " has nonzero offset\n";
1924 });
1925 }
1926 // If there was no mapping for a value ID, it's optimized out. Create no
1927 // DBG_PHI, and any variables using this value will become optimized out.
1928 }
1929 MF->DebugPHIPositions.clear();
1930
1931 LLVM_DEBUG(dbgs() << "********** EMITTING INSTR REFERENCES **********\n");
1932
1933 // Re-insert any debug instrs back in the position they were. We must
1934 // re-insert in the same order to ensure that debug instructions don't swap,
1935 // which could re-order assignments. Do so in a batch -- once we find the
1936 // insert position, insert all instructions at the same SlotIdx. They are
1937 // guaranteed to appear in-sequence in StashedDebugInstrs because we insert
1938 // them in order.
1939 for (auto *StashIt = StashedDebugInstrs.begin();
1940 StashIt != StashedDebugInstrs.end(); ++StashIt) {
1941 SlotIndex Idx = StashIt->Idx;
1942 MachineBasicBlock *MBB = StashIt->MBB;
1943 MachineInstr *MI = StashIt->MI;
1944
1945 auto EmitInstsHere = [this, &StashIt, MBB, Idx,
1946 MI](MachineBasicBlock::iterator InsertPos) {
1947 // Insert this debug instruction.
1948 MBB->insert(InsertPos, MI);
1949
1950 // Look at subsequent stashed debug instructions: if they're at the same
1951 // index, insert those too.
1952 auto NextItem = std::next(StashIt);
1953 while (NextItem != StashedDebugInstrs.end() && NextItem->Idx == Idx) {
1954 assert(NextItem->MBB == MBB && "Instrs with same slot index should be"
1955 "in the same block");
1956 MBB->insert(InsertPos, NextItem->MI);
1957 StashIt = NextItem;
1958 NextItem = std::next(StashIt);
1959 };
1960 };
1961
1962 // Start block index: find the first non-debug instr in the block, and
1963 // insert before it.
1964 if (Idx == Slots->getMBBStartIdx(MBB)) {
1965 MachineBasicBlock::iterator InsertPos =
1966 findInsertLocation(MBB, Idx, *LIS, BBSkipInstsMap);
1967 EmitInstsHere(InsertPos);
1968 continue;
1969 }
1970
1971 if (MachineInstr *Pos = Slots->getInstructionFromIndex(Idx)) {
1972 // Insert at the end of any debug instructions.
1973 auto PostDebug = std::next(MachineBasicBlock::iterator(Pos));
1974 PostDebug = skipDebugInstructionsForward(PostDebug, MBB->end());
1975 EmitInstsHere(PostDebug);
1976 } else {
1977 // Insert position disappeared; walk forwards through slots until we
1978 // find a new one.
1979 SlotIndex End = Slots->getMBBEndIdx(MBB);
1980 for (; Idx < End; Idx = Slots->getNextNonNullIndex(Idx)) {
1981 Pos = Slots->getInstructionFromIndex(Idx);
1982 if (Pos) {
1983 EmitInstsHere(Pos->getIterator());
1984 break;
1985 }
1986 }
1987
1988 // We have reached the end of the block and didn't find anywhere to
1989 // insert! It's not safe to discard any debug instructions; place them
1990 // in front of the first terminator, or in front of end().
1991 if (Idx >= End) {
1992 auto TermIt = MBB->getFirstTerminator();
1993 EmitInstsHere(TermIt);
1994 }
1995 }
1996 }
1997
1998 EmitDone = true;
1999 BBSkipInstsMap.clear();
2000}
2001
2003 if (PImpl)
2004 PImpl->emitDebugValues(VRM);
2005}
2006
2007#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2009#endif
2010
2012 if (PImpl)
2013 PImpl->print(OS);
2014}
unsigned SubReg
unsigned const MachineRegisterInfo * MRI
#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:661
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 DebugLoc getDebugLoc(MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
Return the first DebugLoc that has line number information, given a range of instructions.
static bool isUndef(const MachineInstr &MI)
Register Reg
Register const TargetRegisterInfo * TRI
This file implements a map that provides insertion order iteration.
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)
MachineInstr unsigned OpIdx
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#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
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:114
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.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
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:123
Identifies a unique instance of a variable.
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:178
bool empty() const
Definition DenseMap.h:109
iterator end()
Definition DenseMap.h:81
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...
Result run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
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 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.
void dump() const
dump - Print data structures to dbgs().
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.
LiveDebugVariables()
Implementation of the LiveDebugVariables pass.
void print(raw_ostream &OS) const
void analyze(MachineFunction &MF, LiveIntervals *LIS)
void emitDebugValues(VirtRegMap *VRM)
emitDebugValues - Emit new DBG_VALUE instructions reflecting the changes that happened during registe...
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:1243
An RAII based helper class to modify MachineFunctionProperties when running pass.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
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.
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,...
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:36
iterator begin()
Definition MapVector.h:65
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:124
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 getBaseIndex() const
Returns the base index for associated with this index.
SlotIndex getPrevIndex() const
Returns the previous index.
SlotIndex getNextSlot() const
Returns the next slot in the index list.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
SlotIndexes pass.
SlotIndex getMBBStartIdx(unsigned Num) const
Returns the first index in the given basic block number.
SlotIndex getIndexBefore(const MachineInstr &MI) const
getIndexBefore - Returns the index of the last indexed instruction before MI, or the start index of i...
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:133
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.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:143
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
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
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:1763
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:2122
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:632
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.
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:1744
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
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:1751
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:1883
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:1945
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.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29