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