1 //===- VarLocBasedImpl.cpp - Tracking Debug Value MIs with VarLoc class----===//
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 /// \file VarLocBasedImpl.cpp
10 ///
11 /// LiveDebugValues is an optimistic "available expressions" dataflow
12 /// algorithm. The set of expressions is the set of machine locations
13 /// (registers, spill slots, constants) that a variable fragment might be
14 /// located, qualified by a DIExpression and indirect-ness flag, while each
15 /// variable is identified by a DebugVariable object. The availability of an
16 /// expression begins when a DBG_VALUE instruction specifies the location of a
17 /// DebugVariable, and continues until that location is clobbered or
18 /// re-specified by a different DBG_VALUE for the same DebugVariable.
19 ///
20 /// The output of LiveDebugValues is additional DBG_VALUE instructions,
21 /// placed to extend variable locations as far they're available. This file
22 /// and the VarLocBasedLDV class is an implementation that explicitly tracks
23 /// locations, using the VarLoc class.
24 ///
25 /// The canonical "available expressions" problem doesn't have expression
26 /// clobbering, instead when a variable is re-assigned, any expressions using
27 /// that variable get invalidated. LiveDebugValues can map onto "available
28 /// expressions" by having every register represented by a variable, which is
29 /// used in an expression that becomes available at a DBG_VALUE instruction.
30 /// When the register is clobbered, its variable is effectively reassigned, and
31 /// expressions computed from it become unavailable. A similar construct is
32 /// needed when a DebugVariable has its location re-specified, to invalidate
33 /// all other locations for that DebugVariable.
34 ///
35 /// Using the dataflow analysis to compute the available expressions, we create
36 /// a DBG_VALUE at the beginning of each block where the expression is
37 /// live-in. This propagates variable locations into every basic block where
38 /// the location can be determined, rather than only having DBG_VALUEs in blocks
39 /// where locations are specified due to an assignment or some optimization.
40 /// Movements of values between registers and spill slots are annotated with
41 /// DBG_VALUEs too to track variable values bewteen locations. All this allows
42 /// DbgEntityHistoryCalculator to focus on only the locations within individual
43 /// blocks, facilitating testing and improving modularity.
44 ///
45 /// We follow an optimisic dataflow approach, with this lattice:
46 ///
47 /// \verbatim
48 ///                    ┬ "Unknown"
49 ///                          |
50 ///                          v
51 ///                         True
52 ///                          |
53 ///                          v
54 ///                      ⊥ False
55 /// \endverbatim With "True" signifying that the expression is available (and
56 /// thus a DebugVariable's location is the corresponding register), while
57 /// "False" signifies that the expression is unavailable. "Unknown"s never
58 /// survive to the end of the analysis (see below).
59 ///
60 /// Formally, all DebugVariable locations that are live-out of a block are
61 /// initialized to \top.  A blocks live-in values take the meet of the lattice
62 /// value for every predecessors live-outs, except for the entry block, where
63 /// all live-ins are \bot. The usual dataflow propagation occurs: the transfer
64 /// function for a block assigns an expression for a DebugVariable to be "True"
65 /// if a DBG_VALUE in the block specifies it; "False" if the location is
66 /// clobbered; or the live-in value if it is unaffected by the block. We
67 /// visit each block in reverse post order until a fixedpoint is reached. The
68 /// solution produced is maximal.
69 ///
70 /// Intuitively, we start by assuming that every expression / variable location
71 /// is at least "True", and then propagate "False" from the entry block and any
72 /// clobbers until there are no more changes to make. This gives us an accurate
73 /// solution because all incorrect locations will have a "False" propagated into
74 /// them. It also gives us a solution that copes well with loops by assuming
75 /// that variable locations are live-through every loop, and then removing those
76 /// that are not through dataflow.
77 ///
78 /// Within LiveDebugValues: each variable location is represented by a
79 /// VarLoc object that identifies the source variable, its current
80 /// machine-location, and the DBG_VALUE inst that specifies the location. Each
81 /// VarLoc is indexed in the (function-scope) \p VarLocMap, giving each VarLoc a
82 /// unique index. Rather than operate directly on machine locations, the
83 /// dataflow analysis in this pass identifies locations by their index in the
84 /// VarLocMap, meaning all the variable locations in a block can be described
85 /// by a sparse vector of VarLocMap indicies.
86 ///
87 /// All the storage for the dataflow analysis is local to the ExtendRanges
88 /// method and passed down to helper methods. "OutLocs" and "InLocs" record the
89 /// in and out lattice values for each block. "OpenRanges" maintains a list of
90 /// variable locations and, with the "process" method, evaluates the transfer
91 /// function of each block. "flushPendingLocs" installs DBG_VALUEs for each
92 /// live-in location at the start of blocks, while "Transfers" records
93 /// transfers of values between machine-locations.
94 ///
95 /// We avoid explicitly representing the "Unknown" (\top) lattice value in the
96 /// implementation. Instead, unvisited blocks implicitly have all lattice
97 /// values set as "Unknown". After being visited, there will be path back to
98 /// the entry block where the lattice value is "False", and as the transfer
99 /// function cannot make new "Unknown" locations, there are no scenarios where
100 /// a block can have an "Unknown" location after being visited. Similarly, we
101 /// don't enumerate all possible variable locations before exploring the
102 /// function: when a new location is discovered, all blocks previously explored
103 /// were implicitly "False" but unrecorded, and become explicitly "False" when
104 /// a new VarLoc is created with its bit not set in predecessor InLocs or
105 /// OutLocs.
106 ///
107 //===----------------------------------------------------------------------===//
108 
109 #include "LiveDebugValues.h"
110 
111 #include "llvm/ADT/CoalescingBitVector.h"
112 #include "llvm/ADT/DenseMap.h"
113 #include "llvm/ADT/PostOrderIterator.h"
114 #include "llvm/ADT/SmallPtrSet.h"
115 #include "llvm/ADT/SmallSet.h"
116 #include "llvm/ADT/SmallVector.h"
117 #include "llvm/ADT/Statistic.h"
118 #include "llvm/ADT/UniqueVector.h"
119 #include "llvm/CodeGen/LexicalScopes.h"
120 #include "llvm/CodeGen/MachineBasicBlock.h"
121 #include "llvm/CodeGen/MachineFrameInfo.h"
122 #include "llvm/CodeGen/MachineFunction.h"
123 #include "llvm/CodeGen/MachineFunctionPass.h"
124 #include "llvm/CodeGen/MachineInstr.h"
125 #include "llvm/CodeGen/MachineInstrBuilder.h"
126 #include "llvm/CodeGen/MachineMemOperand.h"
127 #include "llvm/CodeGen/MachineOperand.h"
128 #include "llvm/CodeGen/PseudoSourceValue.h"
129 #include "llvm/CodeGen/RegisterScavenging.h"
130 #include "llvm/CodeGen/TargetFrameLowering.h"
131 #include "llvm/CodeGen/TargetInstrInfo.h"
132 #include "llvm/CodeGen/TargetLowering.h"
133 #include "llvm/CodeGen/TargetPassConfig.h"
134 #include "llvm/CodeGen/TargetRegisterInfo.h"
135 #include "llvm/CodeGen/TargetSubtargetInfo.h"
136 #include "llvm/Config/llvm-config.h"
137 #include "llvm/IR/DIBuilder.h"
138 #include "llvm/IR/DebugInfoMetadata.h"
139 #include "llvm/IR/DebugLoc.h"
140 #include "llvm/IR/Function.h"
141 #include "llvm/IR/Module.h"
142 #include "llvm/InitializePasses.h"
143 #include "llvm/MC/MCRegisterInfo.h"
144 #include "llvm/Pass.h"
145 #include "llvm/Support/Casting.h"
146 #include "llvm/Support/Compiler.h"
147 #include "llvm/Support/Debug.h"
148 #include "llvm/Support/TypeSize.h"
149 #include "llvm/Support/raw_ostream.h"
150 #include "llvm/Target/TargetMachine.h"
151 #include <algorithm>
152 #include <cassert>
153 #include <cstdint>
154 #include <functional>
155 #include <queue>
156 #include <tuple>
157 #include <utility>
158 #include <vector>
159 
160 using namespace llvm;
161 
162 #define DEBUG_TYPE "livedebugvalues"
163 
164 STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
165 
166 // Options to prevent pathological compile-time behavior. If InputBBLimit and
167 // InputDbgValueLimit are both exceeded, range extension is disabled.
168 static cl::opt<unsigned> InputBBLimit(
169     "livedebugvalues-input-bb-limit",
170     cl::desc("Maximum input basic blocks before DBG_VALUE limit applies"),
171     cl::init(10000), cl::Hidden);
172 static cl::opt<unsigned> InputDbgValueLimit(
173     "livedebugvalues-input-dbg-value-limit",
174     cl::desc(
175         "Maximum input DBG_VALUE insts supported by debug range extension"),
176     cl::init(50000), cl::Hidden);
177 
178 // If @MI is a DBG_VALUE with debug value described by a defined
179 // register, returns the number of this register. In the other case, returns 0.
180 static Register isDbgValueDescribedByReg(const MachineInstr &MI) {
181   assert(MI.isDebugValue() && "expected a DBG_VALUE");
182   assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
183   // If location of variable is described using a register (directly
184   // or indirectly), this register is always a first operand.
185   return MI.getDebugOperand(0).isReg() ? MI.getDebugOperand(0).getReg()
186                                        : Register();
187 }
188 
189 /// If \p Op is a stack or frame register return true, otherwise return false.
190 /// This is used to avoid basing the debug entry values on the registers, since
191 /// we do not support it at the moment.
192 static bool isRegOtherThanSPAndFP(const MachineOperand &Op,
193                                   const MachineInstr &MI,
194                                   const TargetRegisterInfo *TRI) {
195   if (!Op.isReg())
196     return false;
197 
198   const MachineFunction *MF = MI.getParent()->getParent();
199   const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
200   Register SP = TLI->getStackPointerRegisterToSaveRestore();
201   Register FP = TRI->getFrameRegister(*MF);
202   Register Reg = Op.getReg();
203 
204   return Reg && Reg != SP && Reg != FP;
205 }
206 
207 namespace {
208 
209 // Max out the number of statically allocated elements in DefinedRegsSet, as
210 // this prevents fallback to std::set::count() operations.
211 using DefinedRegsSet = SmallSet<Register, 32>;
212 
213 using VarLocSet = CoalescingBitVector<uint64_t>;
214 
215 /// A type-checked pair of {Register Location (or 0), Index}, used to index
216 /// into a \ref VarLocMap. This can be efficiently converted to a 64-bit int
217 /// for insertion into a \ref VarLocSet, and efficiently converted back. The
218 /// type-checker helps ensure that the conversions aren't lossy.
219 ///
220 /// Why encode a location /into/ the VarLocMap index? This makes it possible
221 /// to find the open VarLocs killed by a register def very quickly. This is a
222 /// performance-critical operation for LiveDebugValues.
223 struct LocIndex {
224   using u32_location_t = uint32_t;
225   using u32_index_t = uint32_t;
226 
227   u32_location_t Location; // Physical registers live in the range [1;2^30) (see
228                            // \ref MCRegister), so we have plenty of range left
229                            // here to encode non-register locations.
230   u32_index_t Index;
231 
232   /// The first location greater than 0 that is not reserved for VarLocs of
233   /// kind RegisterKind.
234   static constexpr u32_location_t kFirstInvalidRegLocation = 1 << 30;
235 
236   /// A special location reserved for VarLocs of kind SpillLocKind.
237   static constexpr u32_location_t kSpillLocation = kFirstInvalidRegLocation;
238 
239   /// A special location reserved for VarLocs of kind EntryValueBackupKind and
240   /// EntryValueCopyBackupKind.
241   static constexpr u32_location_t kEntryValueBackupLocation =
242       kFirstInvalidRegLocation + 1;
243 
244   LocIndex(u32_location_t Location, u32_index_t Index)
245       : Location(Location), Index(Index) {}
246 
247   uint64_t getAsRawInteger() const {
248     return (static_cast<uint64_t>(Location) << 32) | Index;
249   }
250 
251   template<typename IntT> static LocIndex fromRawInteger(IntT ID) {
252     static_assert(std::is_unsigned<IntT>::value &&
253                       sizeof(ID) == sizeof(uint64_t),
254                   "Cannot convert raw integer to LocIndex");
255     return {static_cast<u32_location_t>(ID >> 32),
256             static_cast<u32_index_t>(ID)};
257   }
258 
259   /// Get the start of the interval reserved for VarLocs of kind RegisterKind
260   /// which reside in \p Reg. The end is at rawIndexForReg(Reg+1)-1.
261   static uint64_t rawIndexForReg(uint32_t Reg) {
262     return LocIndex(Reg, 0).getAsRawInteger();
263   }
264 
265   /// Return a range covering all set indices in the interval reserved for
266   /// \p Location in \p Set.
267   static auto indexRangeForLocation(const VarLocSet &Set,
268                                     u32_location_t Location) {
269     uint64_t Start = LocIndex(Location, 0).getAsRawInteger();
270     uint64_t End = LocIndex(Location + 1, 0).getAsRawInteger();
271     return Set.half_open_range(Start, End);
272   }
273 };
274 
275 class VarLocBasedLDV : public LDVImpl {
276 private:
277   const TargetRegisterInfo *TRI;
278   const TargetInstrInfo *TII;
279   const TargetFrameLowering *TFI;
280   TargetPassConfig *TPC;
281   BitVector CalleeSavedRegs;
282   LexicalScopes LS;
283   VarLocSet::Allocator Alloc;
284 
285   enum struct TransferKind { TransferCopy, TransferSpill, TransferRestore };
286 
287   using FragmentInfo = DIExpression::FragmentInfo;
288   using OptFragmentInfo = Optional<DIExpression::FragmentInfo>;
289 
290   /// A pair of debug variable and value location.
291   struct VarLoc {
292     // The location at which a spilled variable resides. It consists of a
293     // register and an offset.
294     struct SpillLoc {
295       unsigned SpillBase;
296       StackOffset SpillOffset;
297       bool operator==(const SpillLoc &Other) const {
298         return SpillBase == Other.SpillBase && SpillOffset == Other.SpillOffset;
299       }
300       bool operator!=(const SpillLoc &Other) const {
301         return !(*this == Other);
302       }
303     };
304 
305     /// Identity of the variable at this location.
306     const DebugVariable Var;
307 
308     /// The expression applied to this location.
309     const DIExpression *Expr;
310 
311     /// DBG_VALUE to clone var/expr information from if this location
312     /// is moved.
313     const MachineInstr &MI;
314 
315     enum VarLocKind {
316       InvalidKind = 0,
317       RegisterKind,
318       SpillLocKind,
319       ImmediateKind,
320       EntryValueKind,
321       EntryValueBackupKind,
322       EntryValueCopyBackupKind
323     } Kind = InvalidKind;
324 
325     /// The value location. Stored separately to avoid repeatedly
326     /// extracting it from MI.
327     union LocUnion {
328       uint64_t RegNo;
329       SpillLoc SpillLocation;
330       uint64_t Hash;
331       int64_t Immediate;
332       const ConstantFP *FPImm;
333       const ConstantInt *CImm;
334       LocUnion() : Hash(0) {}
335     } Loc;
336 
337     VarLoc(const MachineInstr &MI, LexicalScopes &LS)
338         : Var(MI.getDebugVariable(), MI.getDebugExpression(),
339               MI.getDebugLoc()->getInlinedAt()),
340           Expr(MI.getDebugExpression()), MI(MI) {
341       assert(MI.isDebugValue() && "not a DBG_VALUE");
342       assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
343       if (int RegNo = isDbgValueDescribedByReg(MI)) {
344         Kind = RegisterKind;
345         Loc.RegNo = RegNo;
346       } else if (MI.getDebugOperand(0).isImm()) {
347         Kind = ImmediateKind;
348         Loc.Immediate = MI.getDebugOperand(0).getImm();
349       } else if (MI.getDebugOperand(0).isFPImm()) {
350         Kind = ImmediateKind;
351         Loc.FPImm = MI.getDebugOperand(0).getFPImm();
352       } else if (MI.getDebugOperand(0).isCImm()) {
353         Kind = ImmediateKind;
354         Loc.CImm = MI.getDebugOperand(0).getCImm();
355       }
356 
357       // We create the debug entry values from the factory functions rather than
358       // from this ctor.
359       assert(Kind != EntryValueKind && !isEntryBackupLoc());
360     }
361 
362     /// Take the variable and machine-location in DBG_VALUE MI, and build an
363     /// entry location using the given expression.
364     static VarLoc CreateEntryLoc(const MachineInstr &MI, LexicalScopes &LS,
365                                  const DIExpression *EntryExpr, Register Reg) {
366       VarLoc VL(MI, LS);
367       assert(VL.Kind == RegisterKind);
368       VL.Kind = EntryValueKind;
369       VL.Expr = EntryExpr;
370       VL.Loc.RegNo = Reg;
371       return VL;
372     }
373 
374     /// Take the variable and machine-location from the DBG_VALUE (from the
375     /// function entry), and build an entry value backup location. The backup
376     /// location will turn into the normal location if the backup is valid at
377     /// the time of the primary location clobbering.
378     static VarLoc CreateEntryBackupLoc(const MachineInstr &MI,
379                                        LexicalScopes &LS,
380                                        const DIExpression *EntryExpr) {
381       VarLoc VL(MI, LS);
382       assert(VL.Kind == RegisterKind);
383       VL.Kind = EntryValueBackupKind;
384       VL.Expr = EntryExpr;
385       return VL;
386     }
387 
388     /// Take the variable and machine-location from the DBG_VALUE (from the
389     /// function entry), and build a copy of an entry value backup location by
390     /// setting the register location to NewReg.
391     static VarLoc CreateEntryCopyBackupLoc(const MachineInstr &MI,
392                                            LexicalScopes &LS,
393                                            const DIExpression *EntryExpr,
394                                            Register NewReg) {
395       VarLoc VL(MI, LS);
396       assert(VL.Kind == RegisterKind);
397       VL.Kind = EntryValueCopyBackupKind;
398       VL.Expr = EntryExpr;
399       VL.Loc.RegNo = NewReg;
400       return VL;
401     }
402 
403     /// Copy the register location in DBG_VALUE MI, updating the register to
404     /// be NewReg.
405     static VarLoc CreateCopyLoc(const MachineInstr &MI, LexicalScopes &LS,
406                                 Register NewReg) {
407       VarLoc VL(MI, LS);
408       assert(VL.Kind == RegisterKind);
409       VL.Loc.RegNo = NewReg;
410       return VL;
411     }
412 
413     /// Take the variable described by DBG_VALUE MI, and create a VarLoc
414     /// locating it in the specified spill location.
415     static VarLoc CreateSpillLoc(const MachineInstr &MI, unsigned SpillBase,
416                                  StackOffset SpillOffset, LexicalScopes &LS) {
417       VarLoc VL(MI, LS);
418       assert(VL.Kind == RegisterKind);
419       VL.Kind = SpillLocKind;
420       VL.Loc.SpillLocation = {SpillBase, SpillOffset};
421       return VL;
422     }
423 
424     /// Create a DBG_VALUE representing this VarLoc in the given function.
425     /// Copies variable-specific information such as DILocalVariable and
426     /// inlining information from the original DBG_VALUE instruction, which may
427     /// have been several transfers ago.
428     MachineInstr *BuildDbgValue(MachineFunction &MF) const {
429       const DebugLoc &DbgLoc = MI.getDebugLoc();
430       bool Indirect = MI.isIndirectDebugValue();
431       const auto &IID = MI.getDesc();
432       const DILocalVariable *Var = MI.getDebugVariable();
433       const DIExpression *DIExpr = MI.getDebugExpression();
434       NumInserted++;
435 
436       switch (Kind) {
437       case EntryValueKind:
438         // An entry value is a register location -- but with an updated
439         // expression. The register location of such DBG_VALUE is always the one
440         // from the entry DBG_VALUE, it does not matter if the entry value was
441         // copied in to another register due to some optimizations.
442         return BuildMI(MF, DbgLoc, IID, Indirect,
443                        MI.getDebugOperand(0).getReg(), Var, Expr);
444       case RegisterKind:
445         // Register locations are like the source DBG_VALUE, but with the
446         // register number from this VarLoc.
447         return BuildMI(MF, DbgLoc, IID, Indirect, Loc.RegNo, Var, DIExpr);
448       case SpillLocKind: {
449         // Spills are indirect DBG_VALUEs, with a base register and offset.
450         // Use the original DBG_VALUEs expression to build the spilt location
451         // on top of. FIXME: spill locations created before this pass runs
452         // are not recognized, and not handled here.
453         auto *TRI = MF.getSubtarget().getRegisterInfo();
454         auto *SpillExpr = TRI->prependOffsetExpression(
455             DIExpr, DIExpression::ApplyOffset, Loc.SpillLocation.SpillOffset);
456         unsigned Base = Loc.SpillLocation.SpillBase;
457         return BuildMI(MF, DbgLoc, IID, true, Base, Var, SpillExpr);
458       }
459       case ImmediateKind: {
460         MachineOperand MO = MI.getDebugOperand(0);
461         return BuildMI(MF, DbgLoc, IID, Indirect, MO, Var, DIExpr);
462       }
463       case EntryValueBackupKind:
464       case EntryValueCopyBackupKind:
465       case InvalidKind:
466         llvm_unreachable(
467             "Tried to produce DBG_VALUE for invalid or backup VarLoc");
468       }
469       llvm_unreachable("Unrecognized VarLocBasedLDV.VarLoc.Kind enum");
470     }
471 
472     /// Is the Loc field a constant or constant object?
473     bool isConstant() const { return Kind == ImmediateKind; }
474 
475     /// Check if the Loc field is an entry backup location.
476     bool isEntryBackupLoc() const {
477       return Kind == EntryValueBackupKind || Kind == EntryValueCopyBackupKind;
478     }
479 
480     /// If this variable is described by a register holding the entry value,
481     /// return it, otherwise return 0.
482     unsigned getEntryValueBackupReg() const {
483       if (Kind == EntryValueBackupKind)
484         return Loc.RegNo;
485       return 0;
486     }
487 
488     /// If this variable is described by a register holding the copy of the
489     /// entry value, return it, otherwise return 0.
490     unsigned getEntryValueCopyBackupReg() const {
491       if (Kind == EntryValueCopyBackupKind)
492         return Loc.RegNo;
493       return 0;
494     }
495 
496     /// If this variable is described by a register, return it,
497     /// otherwise return 0.
498     unsigned isDescribedByReg() const {
499       if (Kind == RegisterKind)
500         return Loc.RegNo;
501       return 0;
502     }
503 
504     /// Determine whether the lexical scope of this value's debug location
505     /// dominates MBB.
506     bool dominates(LexicalScopes &LS, MachineBasicBlock &MBB) const {
507       return LS.dominates(MI.getDebugLoc().get(), &MBB);
508     }
509 
510 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
511     // TRI can be null.
512     void dump(const TargetRegisterInfo *TRI, raw_ostream &Out = dbgs()) const {
513       Out << "VarLoc(";
514       switch (Kind) {
515       case RegisterKind:
516       case EntryValueKind:
517       case EntryValueBackupKind:
518       case EntryValueCopyBackupKind:
519         Out << printReg(Loc.RegNo, TRI);
520         break;
521       case SpillLocKind:
522         Out << printReg(Loc.SpillLocation.SpillBase, TRI);
523         Out << "[" << Loc.SpillLocation.SpillOffset.getFixed() << " + "
524             << Loc.SpillLocation.SpillOffset.getScalable() << "x vscale"
525             << "]";
526         break;
527       case ImmediateKind:
528         Out << Loc.Immediate;
529         break;
530       case InvalidKind:
531         llvm_unreachable("Invalid VarLoc in dump method");
532       }
533 
534       Out << ", \"" << Var.getVariable()->getName() << "\", " << *Expr << ", ";
535       if (Var.getInlinedAt())
536         Out << "!" << Var.getInlinedAt()->getMetadataID() << ")\n";
537       else
538         Out << "(null))";
539 
540       if (isEntryBackupLoc())
541         Out << " (backup loc)\n";
542       else
543         Out << "\n";
544     }
545 #endif
546 
547     bool operator==(const VarLoc &Other) const {
548       if (Kind != Other.Kind || !(Var == Other.Var) || Expr != Other.Expr)
549         return false;
550 
551       switch (Kind) {
552       case SpillLocKind:
553         return Loc.SpillLocation == Other.Loc.SpillLocation;
554       case RegisterKind:
555       case ImmediateKind:
556       case EntryValueKind:
557       case EntryValueBackupKind:
558       case EntryValueCopyBackupKind:
559         return Loc.Hash == Other.Loc.Hash;
560       default:
561         llvm_unreachable("Invalid kind");
562       }
563     }
564 
565     /// This operator guarantees that VarLocs are sorted by Variable first.
566     bool operator<(const VarLoc &Other) const {
567       switch (Kind) {
568       case SpillLocKind:
569         return std::make_tuple(Var, Kind, Loc.SpillLocation.SpillBase,
570                                Loc.SpillLocation.SpillOffset.getFixed(),
571                                Loc.SpillLocation.SpillOffset.getScalable(),
572                                Expr) <
573                std::make_tuple(
574                    Other.Var, Other.Kind, Other.Loc.SpillLocation.SpillBase,
575                    Other.Loc.SpillLocation.SpillOffset.getFixed(),
576                    Other.Loc.SpillLocation.SpillOffset.getScalable(),
577                    Other.Expr);
578       case RegisterKind:
579       case ImmediateKind:
580       case EntryValueKind:
581       case EntryValueBackupKind:
582       case EntryValueCopyBackupKind:
583         return std::tie(Var, Kind, Loc.Hash, Expr) <
584                std::tie(Other.Var, Other.Kind, Other.Loc.Hash, Other.Expr);
585       default:
586         llvm_unreachable("Invalid kind");
587       }
588     }
589   };
590 
591   /// VarLocMap is used for two things:
592   /// 1) Assigning a unique LocIndex to a VarLoc. This LocIndex can be used to
593   ///    virtually insert a VarLoc into a VarLocSet.
594   /// 2) Given a LocIndex, look up the unique associated VarLoc.
595   class VarLocMap {
596     /// Map a VarLoc to an index within the vector reserved for its location
597     /// within Loc2Vars.
598     std::map<VarLoc, LocIndex::u32_index_t> Var2Index;
599 
600     /// Map a location to a vector which holds VarLocs which live in that
601     /// location.
602     SmallDenseMap<LocIndex::u32_location_t, std::vector<VarLoc>> Loc2Vars;
603 
604     /// Determine the 32-bit location reserved for \p VL, based on its kind.
605     static LocIndex::u32_location_t getLocationForVar(const VarLoc &VL) {
606       switch (VL.Kind) {
607       case VarLoc::RegisterKind:
608         assert((VL.Loc.RegNo < LocIndex::kFirstInvalidRegLocation) &&
609                "Physreg out of range?");
610         return VL.Loc.RegNo;
611       case VarLoc::SpillLocKind:
612         return LocIndex::kSpillLocation;
613       case VarLoc::EntryValueBackupKind:
614       case VarLoc::EntryValueCopyBackupKind:
615         return LocIndex::kEntryValueBackupLocation;
616       default:
617         return 0;
618       }
619     }
620 
621   public:
622     /// Retrieve a unique LocIndex for \p VL.
623     LocIndex insert(const VarLoc &VL) {
624       LocIndex::u32_location_t Location = getLocationForVar(VL);
625       LocIndex::u32_index_t &Index = Var2Index[VL];
626       if (!Index) {
627         auto &Vars = Loc2Vars[Location];
628         Vars.push_back(VL);
629         Index = Vars.size();
630       }
631       return {Location, Index - 1};
632     }
633 
634     /// Retrieve the unique VarLoc associated with \p ID.
635     const VarLoc &operator[](LocIndex ID) const {
636       auto LocIt = Loc2Vars.find(ID.Location);
637       assert(LocIt != Loc2Vars.end() && "Location not tracked");
638       return LocIt->second[ID.Index];
639     }
640   };
641 
642   using VarLocInMBB =
643       SmallDenseMap<const MachineBasicBlock *, std::unique_ptr<VarLocSet>>;
644   struct TransferDebugPair {
645     MachineInstr *TransferInst; ///< Instruction where this transfer occurs.
646     LocIndex LocationID;        ///< Location number for the transfer dest.
647   };
648   using TransferMap = SmallVector<TransferDebugPair, 4>;
649 
650   // Types for recording sets of variable fragments that overlap. For a given
651   // local variable, we record all other fragments of that variable that could
652   // overlap it, to reduce search time.
653   using FragmentOfVar =
654       std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
655   using OverlapMap =
656       DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
657 
658   // Helper while building OverlapMap, a map of all fragments seen for a given
659   // DILocalVariable.
660   using VarToFragments =
661       DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
662 
663   /// This holds the working set of currently open ranges. For fast
664   /// access, this is done both as a set of VarLocIDs, and a map of
665   /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
666   /// previous open ranges for the same variable. In addition, we keep
667   /// two different maps (Vars/EntryValuesBackupVars), so erase/insert
668   /// methods act differently depending on whether a VarLoc is primary
669   /// location or backup one. In the case the VarLoc is backup location
670   /// we will erase/insert from the EntryValuesBackupVars map, otherwise
671   /// we perform the operation on the Vars.
672   class OpenRangesSet {
673     VarLocSet VarLocs;
674     // Map the DebugVariable to recent primary location ID.
675     SmallDenseMap<DebugVariable, LocIndex, 8> Vars;
676     // Map the DebugVariable to recent backup location ID.
677     SmallDenseMap<DebugVariable, LocIndex, 8> EntryValuesBackupVars;
678     OverlapMap &OverlappingFragments;
679 
680   public:
681     OpenRangesSet(VarLocSet::Allocator &Alloc, OverlapMap &_OLapMap)
682         : VarLocs(Alloc), OverlappingFragments(_OLapMap) {}
683 
684     const VarLocSet &getVarLocs() const { return VarLocs; }
685 
686     /// Terminate all open ranges for VL.Var by removing it from the set.
687     void erase(const VarLoc &VL);
688 
689     /// Terminate all open ranges listed in \c KillSet by removing
690     /// them from the set.
691     void erase(const VarLocSet &KillSet, const VarLocMap &VarLocIDs);
692 
693     /// Insert a new range into the set.
694     void insert(LocIndex VarLocID, const VarLoc &VL);
695 
696     /// Insert a set of ranges.
697     void insertFromLocSet(const VarLocSet &ToLoad, const VarLocMap &Map) {
698       for (uint64_t ID : ToLoad) {
699         LocIndex Idx = LocIndex::fromRawInteger(ID);
700         const VarLoc &VarL = Map[Idx];
701         insert(Idx, VarL);
702       }
703     }
704 
705     llvm::Optional<LocIndex> getEntryValueBackup(DebugVariable Var);
706 
707     /// Empty the set.
708     void clear() {
709       VarLocs.clear();
710       Vars.clear();
711       EntryValuesBackupVars.clear();
712     }
713 
714     /// Return whether the set is empty or not.
715     bool empty() const {
716       assert(Vars.empty() == EntryValuesBackupVars.empty() &&
717              Vars.empty() == VarLocs.empty() &&
718              "open ranges are inconsistent");
719       return VarLocs.empty();
720     }
721 
722     /// Get an empty range of VarLoc IDs.
723     auto getEmptyVarLocRange() const {
724       return iterator_range<VarLocSet::const_iterator>(getVarLocs().end(),
725                                                        getVarLocs().end());
726     }
727 
728     /// Get all set IDs for VarLocs of kind RegisterKind in \p Reg.
729     auto getRegisterVarLocs(Register Reg) const {
730       return LocIndex::indexRangeForLocation(getVarLocs(), Reg);
731     }
732 
733     /// Get all set IDs for VarLocs of kind SpillLocKind.
734     auto getSpillVarLocs() const {
735       return LocIndex::indexRangeForLocation(getVarLocs(),
736                                              LocIndex::kSpillLocation);
737     }
738 
739     /// Get all set IDs for VarLocs of kind EntryValueBackupKind or
740     /// EntryValueCopyBackupKind.
741     auto getEntryValueBackupVarLocs() const {
742       return LocIndex::indexRangeForLocation(
743           getVarLocs(), LocIndex::kEntryValueBackupLocation);
744     }
745   };
746 
747   /// Collect all VarLoc IDs from \p CollectFrom for VarLocs of kind
748   /// RegisterKind which are located in any reg in \p Regs. Insert collected IDs
749   /// into \p Collected.
750   void collectIDsForRegs(VarLocSet &Collected, const DefinedRegsSet &Regs,
751                          const VarLocSet &CollectFrom) const;
752 
753   /// Get the registers which are used by VarLocs of kind RegisterKind tracked
754   /// by \p CollectFrom.
755   void getUsedRegs(const VarLocSet &CollectFrom,
756                    SmallVectorImpl<uint32_t> &UsedRegs) const;
757 
758   VarLocSet &getVarLocsInMBB(const MachineBasicBlock *MBB, VarLocInMBB &Locs) {
759     std::unique_ptr<VarLocSet> &VLS = Locs[MBB];
760     if (!VLS)
761       VLS = std::make_unique<VarLocSet>(Alloc);
762     return *VLS.get();
763   }
764 
765   const VarLocSet &getVarLocsInMBB(const MachineBasicBlock *MBB,
766                                    const VarLocInMBB &Locs) const {
767     auto It = Locs.find(MBB);
768     assert(It != Locs.end() && "MBB not in map");
769     return *It->second.get();
770   }
771 
772   /// Tests whether this instruction is a spill to a stack location.
773   bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF);
774 
775   /// Decide if @MI is a spill instruction and return true if it is. We use 2
776   /// criteria to make this decision:
777   /// - Is this instruction a store to a spill slot?
778   /// - Is there a register operand that is both used and killed?
779   /// TODO: Store optimization can fold spills into other stores (including
780   /// other spills). We do not handle this yet (more than one memory operand).
781   bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF,
782                        Register &Reg);
783 
784   /// Returns true if the given machine instruction is a debug value which we
785   /// can emit entry values for.
786   ///
787   /// Currently, we generate debug entry values only for parameters that are
788   /// unmodified throughout the function and located in a register.
789   bool isEntryValueCandidate(const MachineInstr &MI,
790                              const DefinedRegsSet &Regs) const;
791 
792   /// If a given instruction is identified as a spill, return the spill location
793   /// and set \p Reg to the spilled register.
794   Optional<VarLoc::SpillLoc> isRestoreInstruction(const MachineInstr &MI,
795                                                   MachineFunction *MF,
796                                                   Register &Reg);
797   /// Given a spill instruction, extract the register and offset used to
798   /// address the spill location in a target independent way.
799   VarLoc::SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI);
800   void insertTransferDebugPair(MachineInstr &MI, OpenRangesSet &OpenRanges,
801                                TransferMap &Transfers, VarLocMap &VarLocIDs,
802                                LocIndex OldVarID, TransferKind Kind,
803                                Register NewReg = Register());
804 
805   void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
806                           VarLocMap &VarLocIDs);
807   void transferSpillOrRestoreInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
808                                   VarLocMap &VarLocIDs, TransferMap &Transfers);
809   bool removeEntryValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
810                         VarLocMap &VarLocIDs, const VarLoc &EntryVL);
811   void emitEntryValues(MachineInstr &MI, OpenRangesSet &OpenRanges,
812                        VarLocMap &VarLocIDs, TransferMap &Transfers,
813                        VarLocSet &KillSet);
814   void recordEntryValue(const MachineInstr &MI,
815                         const DefinedRegsSet &DefinedRegs,
816                         OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs);
817   void transferRegisterCopy(MachineInstr &MI, OpenRangesSet &OpenRanges,
818                             VarLocMap &VarLocIDs, TransferMap &Transfers);
819   void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
820                            VarLocMap &VarLocIDs, TransferMap &Transfers);
821   bool transferTerminator(MachineBasicBlock *MBB, OpenRangesSet &OpenRanges,
822                           VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
823 
824   void process(MachineInstr &MI, OpenRangesSet &OpenRanges,
825                VarLocMap &VarLocIDs, TransferMap &Transfers);
826 
827   void accumulateFragmentMap(MachineInstr &MI, VarToFragments &SeenFragments,
828                              OverlapMap &OLapMap);
829 
830   bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
831             const VarLocMap &VarLocIDs,
832             SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
833             SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks);
834 
835   /// Create DBG_VALUE insts for inlocs that have been propagated but
836   /// had their instruction creation deferred.
837   void flushPendingLocs(VarLocInMBB &PendingInLocs, VarLocMap &VarLocIDs);
838 
839   bool ExtendRanges(MachineFunction &MF, TargetPassConfig *TPC) override;
840 
841 public:
842   /// Default construct and initialize the pass.
843   VarLocBasedLDV();
844 
845   ~VarLocBasedLDV();
846 
847   /// Print to ostream with a message.
848   void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
849                         const VarLocMap &VarLocIDs, const char *msg,
850                         raw_ostream &Out) const;
851 };
852 
853 } // end anonymous namespace
854 
855 //===----------------------------------------------------------------------===//
856 //            Implementation
857 //===----------------------------------------------------------------------===//
858 
859 VarLocBasedLDV::VarLocBasedLDV() { }
860 
861 VarLocBasedLDV::~VarLocBasedLDV() { }
862 
863 /// Erase a variable from the set of open ranges, and additionally erase any
864 /// fragments that may overlap it. If the VarLoc is a backup location, erase
865 /// the variable from the EntryValuesBackupVars set, indicating we should stop
866 /// tracking its backup entry location. Otherwise, if the VarLoc is primary
867 /// location, erase the variable from the Vars set.
868 void VarLocBasedLDV::OpenRangesSet::erase(const VarLoc &VL) {
869   // Erasure helper.
870   auto DoErase = [VL, this](DebugVariable VarToErase) {
871     auto *EraseFrom = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
872     auto It = EraseFrom->find(VarToErase);
873     if (It != EraseFrom->end()) {
874       LocIndex ID = It->second;
875       VarLocs.reset(ID.getAsRawInteger());
876       EraseFrom->erase(It);
877     }
878   };
879 
880   DebugVariable Var = VL.Var;
881 
882   // Erase the variable/fragment that ends here.
883   DoErase(Var);
884 
885   // Extract the fragment. Interpret an empty fragment as one that covers all
886   // possible bits.
887   FragmentInfo ThisFragment = Var.getFragmentOrDefault();
888 
889   // There may be fragments that overlap the designated fragment. Look them up
890   // in the pre-computed overlap map, and erase them too.
891   auto MapIt = OverlappingFragments.find({Var.getVariable(), ThisFragment});
892   if (MapIt != OverlappingFragments.end()) {
893     for (auto Fragment : MapIt->second) {
894       VarLocBasedLDV::OptFragmentInfo FragmentHolder;
895       if (!DebugVariable::isDefaultFragment(Fragment))
896         FragmentHolder = VarLocBasedLDV::OptFragmentInfo(Fragment);
897       DoErase({Var.getVariable(), FragmentHolder, Var.getInlinedAt()});
898     }
899   }
900 }
901 
902 void VarLocBasedLDV::OpenRangesSet::erase(const VarLocSet &KillSet,
903                                            const VarLocMap &VarLocIDs) {
904   VarLocs.intersectWithComplement(KillSet);
905   for (uint64_t ID : KillSet) {
906     const VarLoc *VL = &VarLocIDs[LocIndex::fromRawInteger(ID)];
907     auto *EraseFrom = VL->isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
908     EraseFrom->erase(VL->Var);
909   }
910 }
911 
912 void VarLocBasedLDV::OpenRangesSet::insert(LocIndex VarLocID,
913                                             const VarLoc &VL) {
914   auto *InsertInto = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
915   VarLocs.set(VarLocID.getAsRawInteger());
916   InsertInto->insert({VL.Var, VarLocID});
917 }
918 
919 /// Return the Loc ID of an entry value backup location, if it exists for the
920 /// variable.
921 llvm::Optional<LocIndex>
922 VarLocBasedLDV::OpenRangesSet::getEntryValueBackup(DebugVariable Var) {
923   auto It = EntryValuesBackupVars.find(Var);
924   if (It != EntryValuesBackupVars.end())
925     return It->second;
926 
927   return llvm::None;
928 }
929 
930 void VarLocBasedLDV::collectIDsForRegs(VarLocSet &Collected,
931                                         const DefinedRegsSet &Regs,
932                                         const VarLocSet &CollectFrom) const {
933   assert(!Regs.empty() && "Nothing to collect");
934   SmallVector<uint32_t, 32> SortedRegs;
935   append_range(SortedRegs, Regs);
936   array_pod_sort(SortedRegs.begin(), SortedRegs.end());
937   auto It = CollectFrom.find(LocIndex::rawIndexForReg(SortedRegs.front()));
938   auto End = CollectFrom.end();
939   for (uint32_t Reg : SortedRegs) {
940     // The half-open interval [FirstIndexForReg, FirstInvalidIndex) contains all
941     // possible VarLoc IDs for VarLocs of kind RegisterKind which live in Reg.
942     uint64_t FirstIndexForReg = LocIndex::rawIndexForReg(Reg);
943     uint64_t FirstInvalidIndex = LocIndex::rawIndexForReg(Reg + 1);
944     It.advanceToLowerBound(FirstIndexForReg);
945 
946     // Iterate through that half-open interval and collect all the set IDs.
947     for (; It != End && *It < FirstInvalidIndex; ++It)
948       Collected.set(*It);
949 
950     if (It == End)
951       return;
952   }
953 }
954 
955 void VarLocBasedLDV::getUsedRegs(const VarLocSet &CollectFrom,
956                                   SmallVectorImpl<uint32_t> &UsedRegs) const {
957   // All register-based VarLocs are assigned indices greater than or equal to
958   // FirstRegIndex.
959   uint64_t FirstRegIndex = LocIndex::rawIndexForReg(1);
960   uint64_t FirstInvalidIndex =
961       LocIndex::rawIndexForReg(LocIndex::kFirstInvalidRegLocation);
962   for (auto It = CollectFrom.find(FirstRegIndex),
963             End = CollectFrom.find(FirstInvalidIndex);
964        It != End;) {
965     // We found a VarLoc ID for a VarLoc that lives in a register. Figure out
966     // which register and add it to UsedRegs.
967     uint32_t FoundReg = LocIndex::fromRawInteger(*It).Location;
968     assert((UsedRegs.empty() || FoundReg != UsedRegs.back()) &&
969            "Duplicate used reg");
970     UsedRegs.push_back(FoundReg);
971 
972     // Skip to the next /set/ register. Note that this finds a lower bound, so
973     // even if there aren't any VarLocs living in `FoundReg+1`, we're still
974     // guaranteed to move on to the next register (or to end()).
975     uint64_t NextRegIndex = LocIndex::rawIndexForReg(FoundReg + 1);
976     It.advanceToLowerBound(NextRegIndex);
977   }
978 }
979 
980 //===----------------------------------------------------------------------===//
981 //            Debug Range Extension Implementation
982 //===----------------------------------------------------------------------===//
983 
984 #ifndef NDEBUG
985 void VarLocBasedLDV::printVarLocInMBB(const MachineFunction &MF,
986                                        const VarLocInMBB &V,
987                                        const VarLocMap &VarLocIDs,
988                                        const char *msg,
989                                        raw_ostream &Out) const {
990   Out << '\n' << msg << '\n';
991   for (const MachineBasicBlock &BB : MF) {
992     if (!V.count(&BB))
993       continue;
994     const VarLocSet &L = getVarLocsInMBB(&BB, V);
995     if (L.empty())
996       continue;
997     Out << "MBB: " << BB.getNumber() << ":\n";
998     for (uint64_t VLL : L) {
999       const VarLoc &VL = VarLocIDs[LocIndex::fromRawInteger(VLL)];
1000       Out << " Var: " << VL.Var.getVariable()->getName();
1001       Out << " MI: ";
1002       VL.dump(TRI, Out);
1003     }
1004   }
1005   Out << "\n";
1006 }
1007 #endif
1008 
1009 VarLocBasedLDV::VarLoc::SpillLoc
1010 VarLocBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
1011   assert(MI.hasOneMemOperand() &&
1012          "Spill instruction does not have exactly one memory operand?");
1013   auto MMOI = MI.memoperands_begin();
1014   const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
1015   assert(PVal->kind() == PseudoSourceValue::FixedStack &&
1016          "Inconsistent memory operand in spill instruction");
1017   int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
1018   const MachineBasicBlock *MBB = MI.getParent();
1019   Register Reg;
1020   StackOffset Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
1021   return {Reg, Offset};
1022 }
1023 
1024 /// Try to salvage the debug entry value if we encounter a new debug value
1025 /// describing the same parameter, otherwise stop tracking the value. Return
1026 /// true if we should stop tracking the entry value, otherwise return false.
1027 bool VarLocBasedLDV::removeEntryValue(const MachineInstr &MI,
1028                                        OpenRangesSet &OpenRanges,
1029                                        VarLocMap &VarLocIDs,
1030                                        const VarLoc &EntryVL) {
1031   // Skip the DBG_VALUE which is the debug entry value itself.
1032   if (MI.isIdenticalTo(EntryVL.MI))
1033     return false;
1034 
1035   // If the parameter's location is not register location, we can not track
1036   // the entry value any more. In addition, if the debug expression from the
1037   // DBG_VALUE is not empty, we can assume the parameter's value has changed
1038   // indicating that we should stop tracking its entry value as well.
1039   if (!MI.getDebugOperand(0).isReg() ||
1040       MI.getDebugExpression()->getNumElements() != 0)
1041     return true;
1042 
1043   // If the DBG_VALUE comes from a copy instruction that copies the entry value,
1044   // it means the parameter's value has not changed and we should be able to use
1045   // its entry value.
1046   bool TrySalvageEntryValue = false;
1047   Register Reg = MI.getDebugOperand(0).getReg();
1048   auto I = std::next(MI.getReverseIterator());
1049   const MachineOperand *SrcRegOp, *DestRegOp;
1050   if (I != MI.getParent()->rend()) {
1051     // TODO: Try to keep tracking of an entry value if we encounter a propagated
1052     // DBG_VALUE describing the copy of the entry value. (Propagated entry value
1053     // does not indicate the parameter modification.)
1054     auto DestSrc = TII->isCopyInstr(*I);
1055     if (!DestSrc)
1056       return true;
1057 
1058     SrcRegOp = DestSrc->Source;
1059     DestRegOp = DestSrc->Destination;
1060     if (Reg != DestRegOp->getReg())
1061       return true;
1062     TrySalvageEntryValue = true;
1063   }
1064 
1065   if (TrySalvageEntryValue) {
1066     for (uint64_t ID : OpenRanges.getEntryValueBackupVarLocs()) {
1067       const VarLoc &VL = VarLocIDs[LocIndex::fromRawInteger(ID)];
1068       if (VL.getEntryValueCopyBackupReg() == Reg &&
1069           VL.MI.getDebugOperand(0).getReg() == SrcRegOp->getReg())
1070         return false;
1071     }
1072   }
1073 
1074   return true;
1075 }
1076 
1077 /// End all previous ranges related to @MI and start a new range from @MI
1078 /// if it is a DBG_VALUE instr.
1079 void VarLocBasedLDV::transferDebugValue(const MachineInstr &MI,
1080                                          OpenRangesSet &OpenRanges,
1081                                          VarLocMap &VarLocIDs) {
1082   if (!MI.isDebugValue())
1083     return;
1084   const DILocalVariable *Var = MI.getDebugVariable();
1085   const DIExpression *Expr = MI.getDebugExpression();
1086   const DILocation *DebugLoc = MI.getDebugLoc();
1087   const DILocation *InlinedAt = DebugLoc->getInlinedAt();
1088   assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
1089          "Expected inlined-at fields to agree");
1090 
1091   DebugVariable V(Var, Expr, InlinedAt);
1092 
1093   // Check if this DBG_VALUE indicates a parameter's value changing.
1094   // If that is the case, we should stop tracking its entry value.
1095   auto EntryValBackupID = OpenRanges.getEntryValueBackup(V);
1096   if (Var->isParameter() && EntryValBackupID) {
1097     const VarLoc &EntryVL = VarLocIDs[*EntryValBackupID];
1098     if (removeEntryValue(MI, OpenRanges, VarLocIDs, EntryVL)) {
1099       LLVM_DEBUG(dbgs() << "Deleting a DBG entry value because of: ";
1100                  MI.print(dbgs(), /*IsStandalone*/ false,
1101                           /*SkipOpers*/ false, /*SkipDebugLoc*/ false,
1102                           /*AddNewLine*/ true, TII));
1103       OpenRanges.erase(EntryVL);
1104     }
1105   }
1106 
1107   if (isDbgValueDescribedByReg(MI) || MI.getDebugOperand(0).isImm() ||
1108       MI.getDebugOperand(0).isFPImm() || MI.getDebugOperand(0).isCImm()) {
1109     // Use normal VarLoc constructor for registers and immediates.
1110     VarLoc VL(MI, LS);
1111     // End all previous ranges of VL.Var.
1112     OpenRanges.erase(VL);
1113 
1114     LocIndex ID = VarLocIDs.insert(VL);
1115     // Add the VarLoc to OpenRanges from this DBG_VALUE.
1116     OpenRanges.insert(ID, VL);
1117   } else if (MI.hasOneMemOperand()) {
1118     llvm_unreachable("DBG_VALUE with mem operand encountered after regalloc?");
1119   } else {
1120     // This must be an undefined location. If it has an open range, erase it.
1121     assert(MI.getDebugOperand(0).isReg() &&
1122            MI.getDebugOperand(0).getReg() == 0 &&
1123            "Unexpected non-undef DBG_VALUE encountered");
1124     VarLoc VL(MI, LS);
1125     OpenRanges.erase(VL);
1126   }
1127 }
1128 
1129 /// Turn the entry value backup locations into primary locations.
1130 void VarLocBasedLDV::emitEntryValues(MachineInstr &MI,
1131                                       OpenRangesSet &OpenRanges,
1132                                       VarLocMap &VarLocIDs,
1133                                       TransferMap &Transfers,
1134                                       VarLocSet &KillSet) {
1135   // Do not insert entry value locations after a terminator.
1136   if (MI.isTerminator())
1137     return;
1138 
1139   for (uint64_t ID : KillSet) {
1140     LocIndex Idx = LocIndex::fromRawInteger(ID);
1141     const VarLoc &VL = VarLocIDs[Idx];
1142     if (!VL.Var.getVariable()->isParameter())
1143       continue;
1144 
1145     auto DebugVar = VL.Var;
1146     Optional<LocIndex> EntryValBackupID =
1147         OpenRanges.getEntryValueBackup(DebugVar);
1148 
1149     // If the parameter has the entry value backup, it means we should
1150     // be able to use its entry value.
1151     if (!EntryValBackupID)
1152       continue;
1153 
1154     const VarLoc &EntryVL = VarLocIDs[*EntryValBackupID];
1155     VarLoc EntryLoc =
1156         VarLoc::CreateEntryLoc(EntryVL.MI, LS, EntryVL.Expr, EntryVL.Loc.RegNo);
1157     LocIndex EntryValueID = VarLocIDs.insert(EntryLoc);
1158     Transfers.push_back({&MI, EntryValueID});
1159     OpenRanges.insert(EntryValueID, EntryLoc);
1160   }
1161 }
1162 
1163 /// Create new TransferDebugPair and insert it in \p Transfers. The VarLoc
1164 /// with \p OldVarID should be deleted form \p OpenRanges and replaced with
1165 /// new VarLoc. If \p NewReg is different than default zero value then the
1166 /// new location will be register location created by the copy like instruction,
1167 /// otherwise it is variable's location on the stack.
1168 void VarLocBasedLDV::insertTransferDebugPair(
1169     MachineInstr &MI, OpenRangesSet &OpenRanges, TransferMap &Transfers,
1170     VarLocMap &VarLocIDs, LocIndex OldVarID, TransferKind Kind,
1171     Register NewReg) {
1172   const MachineInstr *DebugInstr = &VarLocIDs[OldVarID].MI;
1173 
1174   auto ProcessVarLoc = [&MI, &OpenRanges, &Transfers, &VarLocIDs](VarLoc &VL) {
1175     LocIndex LocId = VarLocIDs.insert(VL);
1176 
1177     // Close this variable's previous location range.
1178     OpenRanges.erase(VL);
1179 
1180     // Record the new location as an open range, and a postponed transfer
1181     // inserting a DBG_VALUE for this location.
1182     OpenRanges.insert(LocId, VL);
1183     assert(!MI.isTerminator() && "Cannot insert DBG_VALUE after terminator");
1184     TransferDebugPair MIP = {&MI, LocId};
1185     Transfers.push_back(MIP);
1186   };
1187 
1188   // End all previous ranges of VL.Var.
1189   OpenRanges.erase(VarLocIDs[OldVarID]);
1190   switch (Kind) {
1191   case TransferKind::TransferCopy: {
1192     assert(NewReg &&
1193            "No register supplied when handling a copy of a debug value");
1194     // Create a DBG_VALUE instruction to describe the Var in its new
1195     // register location.
1196     VarLoc VL = VarLoc::CreateCopyLoc(*DebugInstr, LS, NewReg);
1197     ProcessVarLoc(VL);
1198     LLVM_DEBUG({
1199       dbgs() << "Creating VarLoc for register copy:";
1200       VL.dump(TRI);
1201     });
1202     return;
1203   }
1204   case TransferKind::TransferSpill: {
1205     // Create a DBG_VALUE instruction to describe the Var in its spilled
1206     // location.
1207     VarLoc::SpillLoc SpillLocation = extractSpillBaseRegAndOffset(MI);
1208     VarLoc VL = VarLoc::CreateSpillLoc(*DebugInstr, SpillLocation.SpillBase,
1209                                        SpillLocation.SpillOffset, LS);
1210     ProcessVarLoc(VL);
1211     LLVM_DEBUG({
1212       dbgs() << "Creating VarLoc for spill:";
1213       VL.dump(TRI);
1214     });
1215     return;
1216   }
1217   case TransferKind::TransferRestore: {
1218     assert(NewReg &&
1219            "No register supplied when handling a restore of a debug value");
1220     // DebugInstr refers to the pre-spill location, therefore we can reuse
1221     // its expression.
1222     VarLoc VL = VarLoc::CreateCopyLoc(*DebugInstr, LS, NewReg);
1223     ProcessVarLoc(VL);
1224     LLVM_DEBUG({
1225       dbgs() << "Creating VarLoc for restore:";
1226       VL.dump(TRI);
1227     });
1228     return;
1229   }
1230   }
1231   llvm_unreachable("Invalid transfer kind");
1232 }
1233 
1234 /// A definition of a register may mark the end of a range.
1235 void VarLocBasedLDV::transferRegisterDef(
1236     MachineInstr &MI, OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs,
1237     TransferMap &Transfers) {
1238 
1239   // Meta Instructions do not affect the debug liveness of any register they
1240   // define.
1241   if (MI.isMetaInstruction())
1242     return;
1243 
1244   MachineFunction *MF = MI.getMF();
1245   const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1246   Register SP = TLI->getStackPointerRegisterToSaveRestore();
1247 
1248   // Find the regs killed by MI, and find regmasks of preserved regs.
1249   DefinedRegsSet DeadRegs;
1250   SmallVector<const uint32_t *, 4> RegMasks;
1251   for (const MachineOperand &MO : MI.operands()) {
1252     // Determine whether the operand is a register def.
1253     if (MO.isReg() && MO.isDef() && MO.getReg() &&
1254         Register::isPhysicalRegister(MO.getReg()) &&
1255         !(MI.isCall() && MO.getReg() == SP)) {
1256       // Remove ranges of all aliased registers.
1257       for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1258         // FIXME: Can we break out of this loop early if no insertion occurs?
1259         DeadRegs.insert(*RAI);
1260     } else if (MO.isRegMask()) {
1261       RegMasks.push_back(MO.getRegMask());
1262     }
1263   }
1264 
1265   // Erase VarLocs which reside in one of the dead registers. For performance
1266   // reasons, it's critical to not iterate over the full set of open VarLocs.
1267   // Iterate over the set of dying/used regs instead.
1268   if (!RegMasks.empty()) {
1269     SmallVector<uint32_t, 32> UsedRegs;
1270     getUsedRegs(OpenRanges.getVarLocs(), UsedRegs);
1271     for (uint32_t Reg : UsedRegs) {
1272       // Remove ranges of all clobbered registers. Register masks don't usually
1273       // list SP as preserved. Assume that call instructions never clobber SP,
1274       // because some backends (e.g., AArch64) never list SP in the regmask.
1275       // While the debug info may be off for an instruction or two around
1276       // callee-cleanup calls, transferring the DEBUG_VALUE across the call is
1277       // still a better user experience.
1278       if (Reg == SP)
1279         continue;
1280       bool AnyRegMaskKillsReg =
1281           any_of(RegMasks, [Reg](const uint32_t *RegMask) {
1282             return MachineOperand::clobbersPhysReg(RegMask, Reg);
1283           });
1284       if (AnyRegMaskKillsReg)
1285         DeadRegs.insert(Reg);
1286     }
1287   }
1288 
1289   if (DeadRegs.empty())
1290     return;
1291 
1292   VarLocSet KillSet(Alloc);
1293   collectIDsForRegs(KillSet, DeadRegs, OpenRanges.getVarLocs());
1294   OpenRanges.erase(KillSet, VarLocIDs);
1295 
1296   if (TPC) {
1297     auto &TM = TPC->getTM<TargetMachine>();
1298     if (TM.Options.ShouldEmitDebugEntryValues())
1299       emitEntryValues(MI, OpenRanges, VarLocIDs, Transfers, KillSet);
1300   }
1301 }
1302 
1303 bool VarLocBasedLDV::isSpillInstruction(const MachineInstr &MI,
1304                                          MachineFunction *MF) {
1305   // TODO: Handle multiple stores folded into one.
1306   if (!MI.hasOneMemOperand())
1307     return false;
1308 
1309   if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
1310     return false; // This is not a spill instruction, since no valid size was
1311                   // returned from either function.
1312 
1313   return true;
1314 }
1315 
1316 bool VarLocBasedLDV::isLocationSpill(const MachineInstr &MI,
1317                                       MachineFunction *MF, Register &Reg) {
1318   if (!isSpillInstruction(MI, MF))
1319     return false;
1320 
1321   auto isKilledReg = [&](const MachineOperand MO, Register &Reg) {
1322     if (!MO.isReg() || !MO.isUse()) {
1323       Reg = 0;
1324       return false;
1325     }
1326     Reg = MO.getReg();
1327     return MO.isKill();
1328   };
1329 
1330   for (const MachineOperand &MO : MI.operands()) {
1331     // In a spill instruction generated by the InlineSpiller the spilled
1332     // register has its kill flag set.
1333     if (isKilledReg(MO, Reg))
1334       return true;
1335     if (Reg != 0) {
1336       // Check whether next instruction kills the spilled register.
1337       // FIXME: Current solution does not cover search for killed register in
1338       // bundles and instructions further down the chain.
1339       auto NextI = std::next(MI.getIterator());
1340       // Skip next instruction that points to basic block end iterator.
1341       if (MI.getParent()->end() == NextI)
1342         continue;
1343       Register RegNext;
1344       for (const MachineOperand &MONext : NextI->operands()) {
1345         // Return true if we came across the register from the
1346         // previous spill instruction that is killed in NextI.
1347         if (isKilledReg(MONext, RegNext) && RegNext == Reg)
1348           return true;
1349       }
1350     }
1351   }
1352   // Return false if we didn't find spilled register.
1353   return false;
1354 }
1355 
1356 Optional<VarLocBasedLDV::VarLoc::SpillLoc>
1357 VarLocBasedLDV::isRestoreInstruction(const MachineInstr &MI,
1358                                       MachineFunction *MF, Register &Reg) {
1359   if (!MI.hasOneMemOperand())
1360     return None;
1361 
1362   // FIXME: Handle folded restore instructions with more than one memory
1363   // operand.
1364   if (MI.getRestoreSize(TII)) {
1365     Reg = MI.getOperand(0).getReg();
1366     return extractSpillBaseRegAndOffset(MI);
1367   }
1368   return None;
1369 }
1370 
1371 /// A spilled register may indicate that we have to end the current range of
1372 /// a variable and create a new one for the spill location.
1373 /// A restored register may indicate the reverse situation.
1374 /// We don't want to insert any instructions in process(), so we just create
1375 /// the DBG_VALUE without inserting it and keep track of it in \p Transfers.
1376 /// It will be inserted into the BB when we're done iterating over the
1377 /// instructions.
1378 void VarLocBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI,
1379                                                  OpenRangesSet &OpenRanges,
1380                                                  VarLocMap &VarLocIDs,
1381                                                  TransferMap &Transfers) {
1382   MachineFunction *MF = MI.getMF();
1383   TransferKind TKind;
1384   Register Reg;
1385   Optional<VarLoc::SpillLoc> Loc;
1386 
1387   LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
1388 
1389   // First, if there are any DBG_VALUEs pointing at a spill slot that is
1390   // written to, then close the variable location. The value in memory
1391   // will have changed.
1392   VarLocSet KillSet(Alloc);
1393   if (isSpillInstruction(MI, MF)) {
1394     Loc = extractSpillBaseRegAndOffset(MI);
1395     for (uint64_t ID : OpenRanges.getSpillVarLocs()) {
1396       LocIndex Idx = LocIndex::fromRawInteger(ID);
1397       const VarLoc &VL = VarLocIDs[Idx];
1398       assert(VL.Kind == VarLoc::SpillLocKind && "Broken VarLocSet?");
1399       if (VL.Loc.SpillLocation == *Loc) {
1400         // This location is overwritten by the current instruction -- terminate
1401         // the open range, and insert an explicit DBG_VALUE $noreg.
1402         //
1403         // Doing this at a later stage would require re-interpreting all
1404         // DBG_VALUes and DIExpressions to identify whether they point at
1405         // memory, and then analysing all memory writes to see if they
1406         // overwrite that memory, which is expensive.
1407         //
1408         // At this stage, we already know which DBG_VALUEs are for spills and
1409         // where they are located; it's best to fix handle overwrites now.
1410         KillSet.set(ID);
1411         VarLoc UndefVL = VarLoc::CreateCopyLoc(VL.MI, LS, 0);
1412         LocIndex UndefLocID = VarLocIDs.insert(UndefVL);
1413         Transfers.push_back({&MI, UndefLocID});
1414       }
1415     }
1416     OpenRanges.erase(KillSet, VarLocIDs);
1417   }
1418 
1419   // Try to recognise spill and restore instructions that may create a new
1420   // variable location.
1421   if (isLocationSpill(MI, MF, Reg)) {
1422     TKind = TransferKind::TransferSpill;
1423     LLVM_DEBUG(dbgs() << "Recognized as spill: "; MI.dump(););
1424     LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
1425                       << "\n");
1426   } else {
1427     if (!(Loc = isRestoreInstruction(MI, MF, Reg)))
1428       return;
1429     TKind = TransferKind::TransferRestore;
1430     LLVM_DEBUG(dbgs() << "Recognized as restore: "; MI.dump(););
1431     LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
1432                       << "\n");
1433   }
1434   // Check if the register or spill location is the location of a debug value.
1435   auto TransferCandidates = OpenRanges.getEmptyVarLocRange();
1436   if (TKind == TransferKind::TransferSpill)
1437     TransferCandidates = OpenRanges.getRegisterVarLocs(Reg);
1438   else if (TKind == TransferKind::TransferRestore)
1439     TransferCandidates = OpenRanges.getSpillVarLocs();
1440   for (uint64_t ID : TransferCandidates) {
1441     LocIndex Idx = LocIndex::fromRawInteger(ID);
1442     const VarLoc &VL = VarLocIDs[Idx];
1443     if (TKind == TransferKind::TransferSpill) {
1444       assert(VL.isDescribedByReg() == Reg && "Broken VarLocSet?");
1445       LLVM_DEBUG(dbgs() << "Spilling Register " << printReg(Reg, TRI) << '('
1446                         << VL.Var.getVariable()->getName() << ")\n");
1447     } else {
1448       assert(TKind == TransferKind::TransferRestore &&
1449              VL.Kind == VarLoc::SpillLocKind && "Broken VarLocSet?");
1450       if (VL.Loc.SpillLocation != *Loc)
1451         // The spill location is not the location of a debug value.
1452         continue;
1453       LLVM_DEBUG(dbgs() << "Restoring Register " << printReg(Reg, TRI) << '('
1454                         << VL.Var.getVariable()->getName() << ")\n");
1455     }
1456     insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, Idx, TKind,
1457                             Reg);
1458     // FIXME: A comment should explain why it's correct to return early here,
1459     // if that is in fact correct.
1460     return;
1461   }
1462 }
1463 
1464 /// If \p MI is a register copy instruction, that copies a previously tracked
1465 /// value from one register to another register that is callee saved, we
1466 /// create new DBG_VALUE instruction  described with copy destination register.
1467 void VarLocBasedLDV::transferRegisterCopy(MachineInstr &MI,
1468                                            OpenRangesSet &OpenRanges,
1469                                            VarLocMap &VarLocIDs,
1470                                            TransferMap &Transfers) {
1471   auto DestSrc = TII->isCopyInstr(MI);
1472   if (!DestSrc)
1473     return;
1474 
1475   const MachineOperand *DestRegOp = DestSrc->Destination;
1476   const MachineOperand *SrcRegOp = DestSrc->Source;
1477 
1478   if (!DestRegOp->isDef())
1479     return;
1480 
1481   auto isCalleeSavedReg = [&](Register Reg) {
1482     for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1483       if (CalleeSavedRegs.test(*RAI))
1484         return true;
1485     return false;
1486   };
1487 
1488   Register SrcReg = SrcRegOp->getReg();
1489   Register DestReg = DestRegOp->getReg();
1490 
1491   // We want to recognize instructions where destination register is callee
1492   // saved register. If register that could be clobbered by the call is
1493   // included, there would be a great chance that it is going to be clobbered
1494   // soon. It is more likely that previous register location, which is callee
1495   // saved, is going to stay unclobbered longer, even if it is killed.
1496   if (!isCalleeSavedReg(DestReg))
1497     return;
1498 
1499   // Remember an entry value movement. If we encounter a new debug value of
1500   // a parameter describing only a moving of the value around, rather then
1501   // modifying it, we are still able to use the entry value if needed.
1502   if (isRegOtherThanSPAndFP(*DestRegOp, MI, TRI)) {
1503     for (uint64_t ID : OpenRanges.getEntryValueBackupVarLocs()) {
1504       LocIndex Idx = LocIndex::fromRawInteger(ID);
1505       const VarLoc &VL = VarLocIDs[Idx];
1506       if (VL.getEntryValueBackupReg() == SrcReg) {
1507         LLVM_DEBUG(dbgs() << "Copy of the entry value: "; MI.dump(););
1508         VarLoc EntryValLocCopyBackup =
1509             VarLoc::CreateEntryCopyBackupLoc(VL.MI, LS, VL.Expr, DestReg);
1510 
1511         // Stop tracking the original entry value.
1512         OpenRanges.erase(VL);
1513 
1514         // Start tracking the entry value copy.
1515         LocIndex EntryValCopyLocID = VarLocIDs.insert(EntryValLocCopyBackup);
1516         OpenRanges.insert(EntryValCopyLocID, EntryValLocCopyBackup);
1517         break;
1518       }
1519     }
1520   }
1521 
1522   if (!SrcRegOp->isKill())
1523     return;
1524 
1525   for (uint64_t ID : OpenRanges.getRegisterVarLocs(SrcReg)) {
1526     LocIndex Idx = LocIndex::fromRawInteger(ID);
1527     assert(VarLocIDs[Idx].isDescribedByReg() == SrcReg && "Broken VarLocSet?");
1528     insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, Idx,
1529                             TransferKind::TransferCopy, DestReg);
1530     // FIXME: A comment should explain why it's correct to return early here,
1531     // if that is in fact correct.
1532     return;
1533   }
1534 }
1535 
1536 /// Terminate all open ranges at the end of the current basic block.
1537 bool VarLocBasedLDV::transferTerminator(MachineBasicBlock *CurMBB,
1538                                          OpenRangesSet &OpenRanges,
1539                                          VarLocInMBB &OutLocs,
1540                                          const VarLocMap &VarLocIDs) {
1541   bool Changed = false;
1542 
1543   LLVM_DEBUG(for (uint64_t ID
1544                   : OpenRanges.getVarLocs()) {
1545     // Copy OpenRanges to OutLocs, if not already present.
1546     dbgs() << "Add to OutLocs in MBB #" << CurMBB->getNumber() << ":  ";
1547     VarLocIDs[LocIndex::fromRawInteger(ID)].dump(TRI);
1548   });
1549   VarLocSet &VLS = getVarLocsInMBB(CurMBB, OutLocs);
1550   Changed = VLS != OpenRanges.getVarLocs();
1551   // New OutLocs set may be different due to spill, restore or register
1552   // copy instruction processing.
1553   if (Changed)
1554     VLS = OpenRanges.getVarLocs();
1555   OpenRanges.clear();
1556   return Changed;
1557 }
1558 
1559 /// Accumulate a mapping between each DILocalVariable fragment and other
1560 /// fragments of that DILocalVariable which overlap. This reduces work during
1561 /// the data-flow stage from "Find any overlapping fragments" to "Check if the
1562 /// known-to-overlap fragments are present".
1563 /// \param MI A previously unprocessed DEBUG_VALUE instruction to analyze for
1564 ///           fragment usage.
1565 /// \param SeenFragments Map from DILocalVariable to all fragments of that
1566 ///           Variable which are known to exist.
1567 /// \param OverlappingFragments The overlap map being constructed, from one
1568 ///           Var/Fragment pair to a vector of fragments known to overlap.
1569 void VarLocBasedLDV::accumulateFragmentMap(MachineInstr &MI,
1570                                             VarToFragments &SeenFragments,
1571                                             OverlapMap &OverlappingFragments) {
1572   DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(),
1573                       MI.getDebugLoc()->getInlinedAt());
1574   FragmentInfo ThisFragment = MIVar.getFragmentOrDefault();
1575 
1576   // If this is the first sighting of this variable, then we are guaranteed
1577   // there are currently no overlapping fragments either. Initialize the set
1578   // of seen fragments, record no overlaps for the current one, and return.
1579   auto SeenIt = SeenFragments.find(MIVar.getVariable());
1580   if (SeenIt == SeenFragments.end()) {
1581     SmallSet<FragmentInfo, 4> OneFragment;
1582     OneFragment.insert(ThisFragment);
1583     SeenFragments.insert({MIVar.getVariable(), OneFragment});
1584 
1585     OverlappingFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
1586     return;
1587   }
1588 
1589   // If this particular Variable/Fragment pair already exists in the overlap
1590   // map, it has already been accounted for.
1591   auto IsInOLapMap =
1592       OverlappingFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
1593   if (!IsInOLapMap.second)
1594     return;
1595 
1596   auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
1597   auto &AllSeenFragments = SeenIt->second;
1598 
1599   // Otherwise, examine all other seen fragments for this variable, with "this"
1600   // fragment being a previously unseen fragment. Record any pair of
1601   // overlapping fragments.
1602   for (auto &ASeenFragment : AllSeenFragments) {
1603     // Does this previously seen fragment overlap?
1604     if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
1605       // Yes: Mark the current fragment as being overlapped.
1606       ThisFragmentsOverlaps.push_back(ASeenFragment);
1607       // Mark the previously seen fragment as being overlapped by the current
1608       // one.
1609       auto ASeenFragmentsOverlaps =
1610           OverlappingFragments.find({MIVar.getVariable(), ASeenFragment});
1611       assert(ASeenFragmentsOverlaps != OverlappingFragments.end() &&
1612              "Previously seen var fragment has no vector of overlaps");
1613       ASeenFragmentsOverlaps->second.push_back(ThisFragment);
1614     }
1615   }
1616 
1617   AllSeenFragments.insert(ThisFragment);
1618 }
1619 
1620 /// This routine creates OpenRanges.
1621 void VarLocBasedLDV::process(MachineInstr &MI, OpenRangesSet &OpenRanges,
1622                               VarLocMap &VarLocIDs, TransferMap &Transfers) {
1623   transferDebugValue(MI, OpenRanges, VarLocIDs);
1624   transferRegisterDef(MI, OpenRanges, VarLocIDs, Transfers);
1625   transferRegisterCopy(MI, OpenRanges, VarLocIDs, Transfers);
1626   transferSpillOrRestoreInst(MI, OpenRanges, VarLocIDs, Transfers);
1627 }
1628 
1629 /// This routine joins the analysis results of all incoming edges in @MBB by
1630 /// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
1631 /// source variable in all the predecessors of @MBB reside in the same location.
1632 bool VarLocBasedLDV::join(
1633     MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
1634     const VarLocMap &VarLocIDs,
1635     SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
1636     SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks) {
1637   LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
1638 
1639   VarLocSet InLocsT(Alloc); // Temporary incoming locations.
1640 
1641   // For all predecessors of this MBB, find the set of VarLocs that
1642   // can be joined.
1643   int NumVisited = 0;
1644   for (auto p : MBB.predecessors()) {
1645     // Ignore backedges if we have not visited the predecessor yet. As the
1646     // predecessor hasn't yet had locations propagated into it, most locations
1647     // will not yet be valid, so treat them as all being uninitialized and
1648     // potentially valid. If a location guessed to be correct here is
1649     // invalidated later, we will remove it when we revisit this block.
1650     if (!Visited.count(p)) {
1651       LLVM_DEBUG(dbgs() << "  ignoring unvisited pred MBB: " << p->getNumber()
1652                         << "\n");
1653       continue;
1654     }
1655     auto OL = OutLocs.find(p);
1656     // Join is null in case of empty OutLocs from any of the pred.
1657     if (OL == OutLocs.end())
1658       return false;
1659 
1660     // Just copy over the Out locs to incoming locs for the first visited
1661     // predecessor, and for all other predecessors join the Out locs.
1662     VarLocSet &OutLocVLS = *OL->second.get();
1663     if (!NumVisited)
1664       InLocsT = OutLocVLS;
1665     else
1666       InLocsT &= OutLocVLS;
1667 
1668     LLVM_DEBUG({
1669       if (!InLocsT.empty()) {
1670         for (uint64_t ID : InLocsT)
1671           dbgs() << "  gathered candidate incoming var: "
1672                  << VarLocIDs[LocIndex::fromRawInteger(ID)]
1673                         .Var.getVariable()
1674                         ->getName()
1675                  << "\n";
1676       }
1677     });
1678 
1679     NumVisited++;
1680   }
1681 
1682   // Filter out DBG_VALUES that are out of scope.
1683   VarLocSet KillSet(Alloc);
1684   bool IsArtificial = ArtificialBlocks.count(&MBB);
1685   if (!IsArtificial) {
1686     for (uint64_t ID : InLocsT) {
1687       LocIndex Idx = LocIndex::fromRawInteger(ID);
1688       if (!VarLocIDs[Idx].dominates(LS, MBB)) {
1689         KillSet.set(ID);
1690         LLVM_DEBUG({
1691           auto Name = VarLocIDs[Idx].Var.getVariable()->getName();
1692           dbgs() << "  killing " << Name << ", it doesn't dominate MBB\n";
1693         });
1694       }
1695     }
1696   }
1697   InLocsT.intersectWithComplement(KillSet);
1698 
1699   // As we are processing blocks in reverse post-order we
1700   // should have processed at least one predecessor, unless it
1701   // is the entry block which has no predecessor.
1702   assert((NumVisited || MBB.pred_empty()) &&
1703          "Should have processed at least one predecessor");
1704 
1705   VarLocSet &ILS = getVarLocsInMBB(&MBB, InLocs);
1706   bool Changed = false;
1707   if (ILS != InLocsT) {
1708     ILS = InLocsT;
1709     Changed = true;
1710   }
1711 
1712   return Changed;
1713 }
1714 
1715 void VarLocBasedLDV::flushPendingLocs(VarLocInMBB &PendingInLocs,
1716                                        VarLocMap &VarLocIDs) {
1717   // PendingInLocs records all locations propagated into blocks, which have
1718   // not had DBG_VALUE insts created. Go through and create those insts now.
1719   for (auto &Iter : PendingInLocs) {
1720     // Map is keyed on a constant pointer, unwrap it so we can insert insts.
1721     auto &MBB = const_cast<MachineBasicBlock &>(*Iter.first);
1722     VarLocSet &Pending = *Iter.second.get();
1723 
1724     for (uint64_t ID : Pending) {
1725       // The ID location is live-in to MBB -- work out what kind of machine
1726       // location it is and create a DBG_VALUE.
1727       const VarLoc &DiffIt = VarLocIDs[LocIndex::fromRawInteger(ID)];
1728       if (DiffIt.isEntryBackupLoc())
1729         continue;
1730       MachineInstr *MI = DiffIt.BuildDbgValue(*MBB.getParent());
1731       MBB.insert(MBB.instr_begin(), MI);
1732 
1733       (void)MI;
1734       LLVM_DEBUG(dbgs() << "Inserted: "; MI->dump(););
1735     }
1736   }
1737 }
1738 
1739 bool VarLocBasedLDV::isEntryValueCandidate(
1740     const MachineInstr &MI, const DefinedRegsSet &DefinedRegs) const {
1741   assert(MI.isDebugValue() && "This must be DBG_VALUE.");
1742 
1743   // TODO: Add support for local variables that are expressed in terms of
1744   // parameters entry values.
1745   // TODO: Add support for modified arguments that can be expressed
1746   // by using its entry value.
1747   auto *DIVar = MI.getDebugVariable();
1748   if (!DIVar->isParameter())
1749     return false;
1750 
1751   // Do not consider parameters that belong to an inlined function.
1752   if (MI.getDebugLoc()->getInlinedAt())
1753     return false;
1754 
1755   // Only consider parameters that are described using registers. Parameters
1756   // that are passed on the stack are not yet supported, so ignore debug
1757   // values that are described by the frame or stack pointer.
1758   if (!isRegOtherThanSPAndFP(MI.getDebugOperand(0), MI, TRI))
1759     return false;
1760 
1761   // If a parameter's value has been propagated from the caller, then the
1762   // parameter's DBG_VALUE may be described using a register defined by some
1763   // instruction in the entry block, in which case we shouldn't create an
1764   // entry value.
1765   if (DefinedRegs.count(MI.getDebugOperand(0).getReg()))
1766     return false;
1767 
1768   // TODO: Add support for parameters that have a pre-existing debug expressions
1769   // (e.g. fragments).
1770   if (MI.getDebugExpression()->getNumElements() > 0)
1771     return false;
1772 
1773   return true;
1774 }
1775 
1776 /// Collect all register defines (including aliases) for the given instruction.
1777 static void collectRegDefs(const MachineInstr &MI, DefinedRegsSet &Regs,
1778                            const TargetRegisterInfo *TRI) {
1779   for (const MachineOperand &MO : MI.operands())
1780     if (MO.isReg() && MO.isDef() && MO.getReg())
1781       for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
1782         Regs.insert(*AI);
1783 }
1784 
1785 /// This routine records the entry values of function parameters. The values
1786 /// could be used as backup values. If we loose the track of some unmodified
1787 /// parameters, the backup values will be used as a primary locations.
1788 void VarLocBasedLDV::recordEntryValue(const MachineInstr &MI,
1789                                        const DefinedRegsSet &DefinedRegs,
1790                                        OpenRangesSet &OpenRanges,
1791                                        VarLocMap &VarLocIDs) {
1792   if (TPC) {
1793     auto &TM = TPC->getTM<TargetMachine>();
1794     if (!TM.Options.ShouldEmitDebugEntryValues())
1795       return;
1796   }
1797 
1798   DebugVariable V(MI.getDebugVariable(), MI.getDebugExpression(),
1799                   MI.getDebugLoc()->getInlinedAt());
1800 
1801   if (!isEntryValueCandidate(MI, DefinedRegs) ||
1802       OpenRanges.getEntryValueBackup(V))
1803     return;
1804 
1805   LLVM_DEBUG(dbgs() << "Creating the backup entry location: "; MI.dump(););
1806 
1807   // Create the entry value and use it as a backup location until it is
1808   // valid. It is valid until a parameter is not changed.
1809   DIExpression *NewExpr =
1810       DIExpression::prepend(MI.getDebugExpression(), DIExpression::EntryValue);
1811   VarLoc EntryValLocAsBackup = VarLoc::CreateEntryBackupLoc(MI, LS, NewExpr);
1812   LocIndex EntryValLocID = VarLocIDs.insert(EntryValLocAsBackup);
1813   OpenRanges.insert(EntryValLocID, EntryValLocAsBackup);
1814 }
1815 
1816 /// Calculate the liveness information for the given machine function and
1817 /// extend ranges across basic blocks.
1818 bool VarLocBasedLDV::ExtendRanges(MachineFunction &MF, TargetPassConfig *TPC) {
1819   LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
1820 
1821   if (!MF.getFunction().getSubprogram())
1822     // VarLocBaseLDV will already have removed all DBG_VALUEs.
1823     return false;
1824 
1825   // Skip functions from NoDebug compilation units.
1826   if (MF.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
1827       DICompileUnit::NoDebug)
1828     return false;
1829 
1830   TRI = MF.getSubtarget().getRegisterInfo();
1831   TII = MF.getSubtarget().getInstrInfo();
1832   TFI = MF.getSubtarget().getFrameLowering();
1833   TFI->getCalleeSaves(MF, CalleeSavedRegs);
1834   this->TPC = TPC;
1835   LS.initialize(MF);
1836 
1837   bool Changed = false;
1838   bool OLChanged = false;
1839   bool MBBJoined = false;
1840 
1841   VarLocMap VarLocIDs;         // Map VarLoc<>unique ID for use in bitvectors.
1842   OverlapMap OverlapFragments; // Map of overlapping variable fragments.
1843   OpenRangesSet OpenRanges(Alloc, OverlapFragments);
1844                               // Ranges that are open until end of bb.
1845   VarLocInMBB OutLocs;        // Ranges that exist beyond bb.
1846   VarLocInMBB InLocs;         // Ranges that are incoming after joining.
1847   TransferMap Transfers;      // DBG_VALUEs associated with transfers (such as
1848                               // spills, copies and restores).
1849 
1850   VarToFragments SeenFragments;
1851 
1852   // Blocks which are artificial, i.e. blocks which exclusively contain
1853   // instructions without locations, or with line 0 locations.
1854   SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
1855 
1856   DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
1857   DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
1858   std::priority_queue<unsigned int, std::vector<unsigned int>,
1859                       std::greater<unsigned int>>
1860       Worklist;
1861   std::priority_queue<unsigned int, std::vector<unsigned int>,
1862                       std::greater<unsigned int>>
1863       Pending;
1864 
1865   // Set of register defines that are seen when traversing the entry block
1866   // looking for debug entry value candidates.
1867   DefinedRegsSet DefinedRegs;
1868 
1869   // Only in the case of entry MBB collect DBG_VALUEs representing
1870   // function parameters in order to generate debug entry values for them.
1871   MachineBasicBlock &First_MBB = *(MF.begin());
1872   for (auto &MI : First_MBB) {
1873     collectRegDefs(MI, DefinedRegs, TRI);
1874     if (MI.isDebugValue())
1875       recordEntryValue(MI, DefinedRegs, OpenRanges, VarLocIDs);
1876   }
1877 
1878   // Initialize per-block structures and scan for fragment overlaps.
1879   for (auto &MBB : MF)
1880     for (auto &MI : MBB)
1881       if (MI.isDebugValue())
1882         accumulateFragmentMap(MI, SeenFragments, OverlapFragments);
1883 
1884   auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
1885     if (const DebugLoc &DL = MI.getDebugLoc())
1886       return DL.getLine() != 0;
1887     return false;
1888   };
1889   for (auto &MBB : MF)
1890     if (none_of(MBB.instrs(), hasNonArtificialLocation))
1891       ArtificialBlocks.insert(&MBB);
1892 
1893   LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
1894                               "OutLocs after initialization", dbgs()));
1895 
1896   ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
1897   unsigned int RPONumber = 0;
1898   for (MachineBasicBlock *MBB : RPOT) {
1899     OrderToBB[RPONumber] = MBB;
1900     BBToOrder[MBB] = RPONumber;
1901     Worklist.push(RPONumber);
1902     ++RPONumber;
1903   }
1904 
1905   if (RPONumber > InputBBLimit) {
1906     unsigned NumInputDbgValues = 0;
1907     for (auto &MBB : MF)
1908       for (auto &MI : MBB)
1909         if (MI.isDebugValue())
1910           ++NumInputDbgValues;
1911     if (NumInputDbgValues > InputDbgValueLimit) {
1912       LLVM_DEBUG(dbgs() << "Disabling VarLocBasedLDV: " << MF.getName()
1913                         << " has " << RPONumber << " basic blocks and "
1914                         << NumInputDbgValues
1915                         << " input DBG_VALUEs, exceeding limits.\n");
1916       return false;
1917     }
1918   }
1919 
1920   // This is a standard "union of predecessor outs" dataflow problem.
1921   // To solve it, we perform join() and process() using the two worklist method
1922   // until the ranges converge.
1923   // Ranges have converged when both worklists are empty.
1924   SmallPtrSet<const MachineBasicBlock *, 16> Visited;
1925   while (!Worklist.empty() || !Pending.empty()) {
1926     // We track what is on the pending worklist to avoid inserting the same
1927     // thing twice.  We could avoid this with a custom priority queue, but this
1928     // is probably not worth it.
1929     SmallPtrSet<MachineBasicBlock *, 16> OnPending;
1930     LLVM_DEBUG(dbgs() << "Processing Worklist\n");
1931     while (!Worklist.empty()) {
1932       MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
1933       Worklist.pop();
1934       MBBJoined = join(*MBB, OutLocs, InLocs, VarLocIDs, Visited,
1935                        ArtificialBlocks);
1936       MBBJoined |= Visited.insert(MBB).second;
1937       if (MBBJoined) {
1938         MBBJoined = false;
1939         Changed = true;
1940         // Now that we have started to extend ranges across BBs we need to
1941         // examine spill, copy and restore instructions to see whether they
1942         // operate with registers that correspond to user variables.
1943         // First load any pending inlocs.
1944         OpenRanges.insertFromLocSet(getVarLocsInMBB(MBB, InLocs), VarLocIDs);
1945         for (auto &MI : *MBB)
1946           process(MI, OpenRanges, VarLocIDs, Transfers);
1947         OLChanged |= transferTerminator(MBB, OpenRanges, OutLocs, VarLocIDs);
1948 
1949         LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
1950                                     "OutLocs after propagating", dbgs()));
1951         LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
1952                                     "InLocs after propagating", dbgs()));
1953 
1954         if (OLChanged) {
1955           OLChanged = false;
1956           for (auto s : MBB->successors())
1957             if (OnPending.insert(s).second) {
1958               Pending.push(BBToOrder[s]);
1959             }
1960         }
1961       }
1962     }
1963     Worklist.swap(Pending);
1964     // At this point, pending must be empty, since it was just the empty
1965     // worklist
1966     assert(Pending.empty() && "Pending should be empty");
1967   }
1968 
1969   // Add any DBG_VALUE instructions created by location transfers.
1970   for (auto &TR : Transfers) {
1971     assert(!TR.TransferInst->isTerminator() &&
1972            "Cannot insert DBG_VALUE after terminator");
1973     MachineBasicBlock *MBB = TR.TransferInst->getParent();
1974     const VarLoc &VL = VarLocIDs[TR.LocationID];
1975     MachineInstr *MI = VL.BuildDbgValue(MF);
1976     MBB->insertAfterBundle(TR.TransferInst->getIterator(), MI);
1977   }
1978   Transfers.clear();
1979 
1980   // Deferred inlocs will not have had any DBG_VALUE insts created; do
1981   // that now.
1982   flushPendingLocs(InLocs, VarLocIDs);
1983 
1984   LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
1985   LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
1986   return Changed;
1987 }
1988 
1989 LDVImpl *
1990 llvm::makeVarLocBasedLiveDebugValues()
1991 {
1992   return new VarLocBasedLDV();
1993 }
1994