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