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