1 //===- InstrRefBasedImpl.cpp - Tracking Debug Value MIs -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file InstrRefBasedImpl.cpp
9 ///
10 /// This is a separate implementation of LiveDebugValues, see
11 /// LiveDebugValues.cpp and VarLocBasedImpl.cpp for more information.
12 ///
13 /// This pass propagates variable locations between basic blocks, resolving
14 /// control flow conflicts between them. The problem is SSA construction, where
15 /// each debug instruction assigns the *value* that a variable has, and every
16 /// instruction where the variable is in scope uses that variable. The resulting
17 /// map of instruction-to-value is then translated into a register (or spill)
18 /// location for each variable over each instruction.
19 ///
20 /// The primary difference from normal SSA construction is that we cannot
21 /// _create_ PHI values that contain variable values. CodeGen has already
22 /// completed, and we can't alter it just to make debug-info complete. Thus:
23 /// we can identify function positions where we would like a PHI value for a
24 /// variable, but must search the MachineFunction to see whether such a PHI is
25 /// available. If no such PHI exists, the variable location must be dropped.
26 ///
27 /// To achieve this, we perform two kinds of analysis. First, we identify
28 /// every value defined by every instruction (ignoring those that only move
29 /// another value), then re-compute an SSA-form representation of the
30 /// MachineFunction, using value propagation to eliminate any un-necessary
31 /// PHI values. This gives us a map of every value computed in the function,
32 /// and its location within the register file / stack.
33 ///
34 /// Secondly, for each variable we perform the same analysis, where each debug
35 /// instruction is considered a def, and every instruction where the variable
36 /// is in lexical scope as a use. Value propagation is used again to eliminate
37 /// any un-necessary PHIs. This gives us a map of each variable to the value
38 /// it should have in a block.
39 ///
40 /// Once both are complete, we have two maps for each block:
41 ///  * Variables to the values they should have,
42 ///  * Values to the register / spill slot they are located in.
43 /// After which we can marry-up variable values with a location, and emit
44 /// DBG_VALUE instructions specifying those locations. Variable locations may
45 /// be dropped in this process due to the desired variable value not being
46 /// resident in any machine location, or because there is no PHI value in any
47 /// location that accurately represents the desired value.  The building of
48 /// location lists for each block is left to DbgEntityHistoryCalculator.
49 ///
50 /// This pass is kept efficient because the size of the first SSA problem
51 /// is proportional to the working-set size of the function, which the compiler
52 /// tries to keep small. (It's also proportional to the number of blocks).
53 /// Additionally, we repeatedly perform the second SSA problem analysis with
54 /// only the variables and blocks in a single lexical scope, exploiting their
55 /// locality.
56 ///
57 /// ### Terminology
58 ///
59 /// A machine location is a register or spill slot, a value is something that's
60 /// defined by an instruction or PHI node, while a variable value is the value
61 /// assigned to a variable. A variable location is a machine location, that must
62 /// contain the appropriate variable value. A value that is a PHI node is
63 /// occasionally called an mphi.
64 ///
65 /// The first SSA problem is the "machine value location" problem,
66 /// because we're determining which machine locations contain which values.
67 /// The "locations" are constant: what's unknown is what value they contain.
68 ///
69 /// The second SSA problem (the one for variables) is the "variable value
70 /// problem", because it's determining what values a variable has, rather than
71 /// what location those values are placed in.
72 ///
73 /// TODO:
74 ///   Overlapping fragments
75 ///   Entry values
76 ///   Add back DEBUG statements for debugging this
77 ///   Collect statistics
78 ///
79 //===----------------------------------------------------------------------===//
80 
81 #include "llvm/ADT/DenseMap.h"
82 #include "llvm/ADT/PostOrderIterator.h"
83 #include "llvm/ADT/STLExtras.h"
84 #include "llvm/ADT/SmallPtrSet.h"
85 #include "llvm/ADT/SmallSet.h"
86 #include "llvm/ADT/SmallVector.h"
87 #include "llvm/BinaryFormat/Dwarf.h"
88 #include "llvm/CodeGen/LexicalScopes.h"
89 #include "llvm/CodeGen/MachineBasicBlock.h"
90 #include "llvm/CodeGen/MachineDominators.h"
91 #include "llvm/CodeGen/MachineFrameInfo.h"
92 #include "llvm/CodeGen/MachineFunction.h"
93 #include "llvm/CodeGen/MachineInstr.h"
94 #include "llvm/CodeGen/MachineInstrBuilder.h"
95 #include "llvm/CodeGen/MachineInstrBundle.h"
96 #include "llvm/CodeGen/MachineMemOperand.h"
97 #include "llvm/CodeGen/MachineOperand.h"
98 #include "llvm/CodeGen/PseudoSourceValue.h"
99 #include "llvm/CodeGen/TargetFrameLowering.h"
100 #include "llvm/CodeGen/TargetInstrInfo.h"
101 #include "llvm/CodeGen/TargetLowering.h"
102 #include "llvm/CodeGen/TargetPassConfig.h"
103 #include "llvm/CodeGen/TargetRegisterInfo.h"
104 #include "llvm/CodeGen/TargetSubtargetInfo.h"
105 #include "llvm/Config/llvm-config.h"
106 #include "llvm/IR/DebugInfoMetadata.h"
107 #include "llvm/IR/DebugLoc.h"
108 #include "llvm/IR/Function.h"
109 #include "llvm/MC/MCRegisterInfo.h"
110 #include "llvm/Support/Casting.h"
111 #include "llvm/Support/Compiler.h"
112 #include "llvm/Support/Debug.h"
113 #include "llvm/Support/GenericIteratedDominanceFrontier.h"
114 #include "llvm/Support/TypeSize.h"
115 #include "llvm/Support/raw_ostream.h"
116 #include "llvm/Target/TargetMachine.h"
117 #include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
118 #include <algorithm>
119 #include <cassert>
120 #include <climits>
121 #include <cstdint>
122 #include <functional>
123 #include <queue>
124 #include <tuple>
125 #include <utility>
126 #include <vector>
127 
128 #include "InstrRefBasedImpl.h"
129 #include "LiveDebugValues.h"
130 
131 using namespace llvm;
132 using namespace LiveDebugValues;
133 
134 // SSAUpdaterImple sets DEBUG_TYPE, change it.
135 #undef DEBUG_TYPE
136 #define DEBUG_TYPE "livedebugvalues"
137 
138 // Act more like the VarLoc implementation, by propagating some locations too
139 // far and ignoring some transfers.
140 static cl::opt<bool> EmulateOldLDV("emulate-old-livedebugvalues", cl::Hidden,
141                                    cl::desc("Act like old LiveDebugValues did"),
142                                    cl::init(false));
143 
144 // Limit for the maximum number of stack slots we should track, past which we
145 // will ignore any spills. InstrRefBasedLDV gathers detailed information on all
146 // stack slots which leads to high memory consumption, and in some scenarios
147 // (such as asan with very many locals) the working set of the function can be
148 // very large, causing many spills. In these scenarios, it is very unlikely that
149 // the developer has hundreds of variables live at the same time that they're
150 // carefully thinking about -- instead, they probably autogenerated the code.
151 // When this happens, gracefully stop tracking excess spill slots, rather than
152 // consuming all the developer's memory.
153 static cl::opt<unsigned>
154     StackWorkingSetLimit("livedebugvalues-max-stack-slots", cl::Hidden,
155                          cl::desc("livedebugvalues-stack-ws-limit"),
156                          cl::init(250));
157 
158 /// Tracker for converting machine value locations and variable values into
159 /// variable locations (the output of LiveDebugValues), recorded as DBG_VALUEs
160 /// specifying block live-in locations and transfers within blocks.
161 ///
162 /// Operating on a per-block basis, this class takes a (pre-loaded) MLocTracker
163 /// and must be initialized with the set of variable values that are live-in to
164 /// the block. The caller then repeatedly calls process(). TransferTracker picks
165 /// out variable locations for the live-in variable values (if there _is_ a
166 /// location) and creates the corresponding DBG_VALUEs. Then, as the block is
167 /// stepped through, transfers of values between machine locations are
168 /// identified and if profitable, a DBG_VALUE created.
169 ///
170 /// This is where debug use-before-defs would be resolved: a variable with an
171 /// unavailable value could materialize in the middle of a block, when the
172 /// value becomes available. Or, we could detect clobbers and re-specify the
173 /// variable in a backup location. (XXX these are unimplemented).
174 class TransferTracker {
175 public:
176   const TargetInstrInfo *TII;
177   const TargetLowering *TLI;
178   /// This machine location tracker is assumed to always contain the up-to-date
179   /// value mapping for all machine locations. TransferTracker only reads
180   /// information from it. (XXX make it const?)
181   MLocTracker *MTracker;
182   MachineFunction &MF;
183   bool ShouldEmitDebugEntryValues;
184 
185   /// Record of all changes in variable locations at a block position. Awkwardly
186   /// we allow inserting either before or after the point: MBB != nullptr
187   /// indicates it's before, otherwise after.
188   struct Transfer {
189     MachineBasicBlock::instr_iterator Pos; /// Position to insert DBG_VALUes
190     MachineBasicBlock *MBB; /// non-null if we should insert after.
191     SmallVector<MachineInstr *, 4> Insts; /// Vector of DBG_VALUEs to insert.
192   };
193 
194   struct LocAndProperties {
195     LocIdx Loc;
196     DbgValueProperties Properties;
197   };
198 
199   /// Collection of transfers (DBG_VALUEs) to be inserted.
200   SmallVector<Transfer, 32> Transfers;
201 
202   /// Local cache of what-value-is-in-what-LocIdx. Used to identify differences
203   /// between TransferTrackers view of variable locations and MLocTrackers. For
204   /// example, MLocTracker observes all clobbers, but TransferTracker lazily
205   /// does not.
206   SmallVector<ValueIDNum, 32> VarLocs;
207 
208   /// Map from LocIdxes to which DebugVariables are based that location.
209   /// Mantained while stepping through the block. Not accurate if
210   /// VarLocs[Idx] != MTracker->LocIdxToIDNum[Idx].
211   DenseMap<LocIdx, SmallSet<DebugVariable, 4>> ActiveMLocs;
212 
213   /// Map from DebugVariable to it's current location and qualifying meta
214   /// information. To be used in conjunction with ActiveMLocs to construct
215   /// enough information for the DBG_VALUEs for a particular LocIdx.
216   DenseMap<DebugVariable, LocAndProperties> ActiveVLocs;
217 
218   /// Temporary cache of DBG_VALUEs to be entered into the Transfers collection.
219   SmallVector<MachineInstr *, 4> PendingDbgValues;
220 
221   /// Record of a use-before-def: created when a value that's live-in to the
222   /// current block isn't available in any machine location, but it will be
223   /// defined in this block.
224   struct UseBeforeDef {
225     /// Value of this variable, def'd in block.
226     ValueIDNum ID;
227     /// Identity of this variable.
228     DebugVariable Var;
229     /// Additional variable properties.
230     DbgValueProperties Properties;
231   };
232 
233   /// Map from instruction index (within the block) to the set of UseBeforeDefs
234   /// that become defined at that instruction.
235   DenseMap<unsigned, SmallVector<UseBeforeDef, 1>> UseBeforeDefs;
236 
237   /// The set of variables that are in UseBeforeDefs and can become a location
238   /// once the relevant value is defined. An element being erased from this
239   /// collection prevents the use-before-def materializing.
240   DenseSet<DebugVariable> UseBeforeDefVariables;
241 
242   const TargetRegisterInfo &TRI;
243   const BitVector &CalleeSavedRegs;
244 
245   TransferTracker(const TargetInstrInfo *TII, MLocTracker *MTracker,
246                   MachineFunction &MF, const TargetRegisterInfo &TRI,
247                   const BitVector &CalleeSavedRegs, const TargetPassConfig &TPC)
248       : TII(TII), MTracker(MTracker), MF(MF), TRI(TRI),
249         CalleeSavedRegs(CalleeSavedRegs) {
250     TLI = MF.getSubtarget().getTargetLowering();
251     auto &TM = TPC.getTM<TargetMachine>();
252     ShouldEmitDebugEntryValues = TM.Options.ShouldEmitDebugEntryValues();
253   }
254 
255   /// Load object with live-in variable values. \p mlocs contains the live-in
256   /// values in each machine location, while \p vlocs the live-in variable
257   /// values. This method picks variable locations for the live-in variables,
258   /// creates DBG_VALUEs and puts them in #Transfers, then prepares the other
259   /// object fields to track variable locations as we step through the block.
260   /// FIXME: could just examine mloctracker instead of passing in \p mlocs?
261   void
262   loadInlocs(MachineBasicBlock &MBB, ValueTable &MLocs,
263              const SmallVectorImpl<std::pair<DebugVariable, DbgValue>> &VLocs,
264              unsigned NumLocs) {
265     ActiveMLocs.clear();
266     ActiveVLocs.clear();
267     VarLocs.clear();
268     VarLocs.reserve(NumLocs);
269     UseBeforeDefs.clear();
270     UseBeforeDefVariables.clear();
271 
272     auto isCalleeSaved = [&](LocIdx L) {
273       unsigned Reg = MTracker->LocIdxToLocID[L];
274       if (Reg >= MTracker->NumRegs)
275         return false;
276       for (MCRegAliasIterator RAI(Reg, &TRI, true); RAI.isValid(); ++RAI)
277         if (CalleeSavedRegs.test(*RAI))
278           return true;
279       return false;
280     };
281 
282     // Map of the preferred location for each value.
283     DenseMap<ValueIDNum, LocIdx> ValueToLoc;
284 
285     // Initialized the preferred-location map with illegal locations, to be
286     // filled in later.
287     for (auto &VLoc : VLocs)
288       if (VLoc.second.Kind == DbgValue::Def)
289         ValueToLoc.insert({VLoc.second.ID, LocIdx::MakeIllegalLoc()});
290 
291     ActiveMLocs.reserve(VLocs.size());
292     ActiveVLocs.reserve(VLocs.size());
293 
294     // Produce a map of value numbers to the current machine locs they live
295     // in. When emulating VarLocBasedImpl, there should only be one
296     // location; when not, we get to pick.
297     for (auto Location : MTracker->locations()) {
298       LocIdx Idx = Location.Idx;
299       ValueIDNum &VNum = MLocs[Idx.asU64()];
300       VarLocs.push_back(VNum);
301 
302       // Is there a variable that wants a location for this value? If not, skip.
303       auto VIt = ValueToLoc.find(VNum);
304       if (VIt == ValueToLoc.end())
305         continue;
306 
307       LocIdx CurLoc = VIt->second;
308       // In order of preference, pick:
309       //  * Callee saved registers,
310       //  * Other registers,
311       //  * Spill slots.
312       if (CurLoc.isIllegal() || MTracker->isSpill(CurLoc) ||
313           (!isCalleeSaved(CurLoc) && isCalleeSaved(Idx.asU64()))) {
314         // Insert, or overwrite if insertion failed.
315         VIt->second = Idx;
316       }
317     }
318 
319     // Now map variables to their picked LocIdxes.
320     for (const auto &Var : VLocs) {
321       if (Var.second.Kind == DbgValue::Const) {
322         PendingDbgValues.push_back(
323             emitMOLoc(*Var.second.MO, Var.first, Var.second.Properties));
324         continue;
325       }
326 
327       // If the value has no location, we can't make a variable location.
328       const ValueIDNum &Num = Var.second.ID;
329       auto ValuesPreferredLoc = ValueToLoc.find(Num);
330       if (ValuesPreferredLoc->second.isIllegal()) {
331         // If it's a def that occurs in this block, register it as a
332         // use-before-def to be resolved as we step through the block.
333         if (Num.getBlock() == (unsigned)MBB.getNumber() && !Num.isPHI())
334           addUseBeforeDef(Var.first, Var.second.Properties, Num);
335         else
336           recoverAsEntryValue(Var.first, Var.second.Properties, Num);
337         continue;
338       }
339 
340       LocIdx M = ValuesPreferredLoc->second;
341       auto NewValue = LocAndProperties{M, Var.second.Properties};
342       auto Result = ActiveVLocs.insert(std::make_pair(Var.first, NewValue));
343       if (!Result.second)
344         Result.first->second = NewValue;
345       ActiveMLocs[M].insert(Var.first);
346       PendingDbgValues.push_back(
347           MTracker->emitLoc(M, Var.first, Var.second.Properties));
348     }
349     flushDbgValues(MBB.begin(), &MBB);
350   }
351 
352   /// Record that \p Var has value \p ID, a value that becomes available
353   /// later in the function.
354   void addUseBeforeDef(const DebugVariable &Var,
355                        const DbgValueProperties &Properties, ValueIDNum ID) {
356     UseBeforeDef UBD = {ID, Var, Properties};
357     UseBeforeDefs[ID.getInst()].push_back(UBD);
358     UseBeforeDefVariables.insert(Var);
359   }
360 
361   /// After the instruction at index \p Inst and position \p pos has been
362   /// processed, check whether it defines a variable value in a use-before-def.
363   /// If so, and the variable value hasn't changed since the start of the
364   /// block, create a DBG_VALUE.
365   void checkInstForNewValues(unsigned Inst, MachineBasicBlock::iterator pos) {
366     auto MIt = UseBeforeDefs.find(Inst);
367     if (MIt == UseBeforeDefs.end())
368       return;
369 
370     for (auto &Use : MIt->second) {
371       LocIdx L = Use.ID.getLoc();
372 
373       // If something goes very wrong, we might end up labelling a COPY
374       // instruction or similar with an instruction number, where it doesn't
375       // actually define a new value, instead it moves a value. In case this
376       // happens, discard.
377       if (MTracker->readMLoc(L) != Use.ID)
378         continue;
379 
380       // If a different debug instruction defined the variable value / location
381       // since the start of the block, don't materialize this use-before-def.
382       if (!UseBeforeDefVariables.count(Use.Var))
383         continue;
384 
385       PendingDbgValues.push_back(MTracker->emitLoc(L, Use.Var, Use.Properties));
386     }
387     flushDbgValues(pos, nullptr);
388   }
389 
390   /// Helper to move created DBG_VALUEs into Transfers collection.
391   void flushDbgValues(MachineBasicBlock::iterator Pos, MachineBasicBlock *MBB) {
392     if (PendingDbgValues.size() == 0)
393       return;
394 
395     // Pick out the instruction start position.
396     MachineBasicBlock::instr_iterator BundleStart;
397     if (MBB && Pos == MBB->begin())
398       BundleStart = MBB->instr_begin();
399     else
400       BundleStart = getBundleStart(Pos->getIterator());
401 
402     Transfers.push_back({BundleStart, MBB, PendingDbgValues});
403     PendingDbgValues.clear();
404   }
405 
406   bool isEntryValueVariable(const DebugVariable &Var,
407                             const DIExpression *Expr) const {
408     if (!Var.getVariable()->isParameter())
409       return false;
410 
411     if (Var.getInlinedAt())
412       return false;
413 
414     if (Expr->getNumElements() > 0)
415       return false;
416 
417     return true;
418   }
419 
420   bool isEntryValueValue(const ValueIDNum &Val) const {
421     // Must be in entry block (block number zero), and be a PHI / live-in value.
422     if (Val.getBlock() || !Val.isPHI())
423       return false;
424 
425     // Entry values must enter in a register.
426     if (MTracker->isSpill(Val.getLoc()))
427       return false;
428 
429     Register SP = TLI->getStackPointerRegisterToSaveRestore();
430     Register FP = TRI.getFrameRegister(MF);
431     Register Reg = MTracker->LocIdxToLocID[Val.getLoc()];
432     return Reg != SP && Reg != FP;
433   }
434 
435   bool recoverAsEntryValue(const DebugVariable &Var,
436                            const DbgValueProperties &Prop,
437                            const ValueIDNum &Num) {
438     // Is this variable location a candidate to be an entry value. First,
439     // should we be trying this at all?
440     if (!ShouldEmitDebugEntryValues)
441       return false;
442 
443     // Is the variable appropriate for entry values (i.e., is a parameter).
444     if (!isEntryValueVariable(Var, Prop.DIExpr))
445       return false;
446 
447     // Is the value assigned to this variable still the entry value?
448     if (!isEntryValueValue(Num))
449       return false;
450 
451     // Emit a variable location using an entry value expression.
452     DIExpression *NewExpr =
453         DIExpression::prepend(Prop.DIExpr, DIExpression::EntryValue);
454     Register Reg = MTracker->LocIdxToLocID[Num.getLoc()];
455     MachineOperand MO = MachineOperand::CreateReg(Reg, false);
456 
457     PendingDbgValues.push_back(emitMOLoc(MO, Var, {NewExpr, Prop.Indirect}));
458     return true;
459   }
460 
461   /// Change a variable value after encountering a DBG_VALUE inside a block.
462   void redefVar(const MachineInstr &MI) {
463     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
464                       MI.getDebugLoc()->getInlinedAt());
465     DbgValueProperties Properties(MI);
466 
467     const MachineOperand &MO = MI.getOperand(0);
468 
469     // Ignore non-register locations, we don't transfer those.
470     if (!MO.isReg() || MO.getReg() == 0) {
471       auto It = ActiveVLocs.find(Var);
472       if (It != ActiveVLocs.end()) {
473         ActiveMLocs[It->second.Loc].erase(Var);
474         ActiveVLocs.erase(It);
475      }
476       // Any use-before-defs no longer apply.
477       UseBeforeDefVariables.erase(Var);
478       return;
479     }
480 
481     Register Reg = MO.getReg();
482     LocIdx NewLoc = MTracker->getRegMLoc(Reg);
483     redefVar(MI, Properties, NewLoc);
484   }
485 
486   /// Handle a change in variable location within a block. Terminate the
487   /// variables current location, and record the value it now refers to, so
488   /// that we can detect location transfers later on.
489   void redefVar(const MachineInstr &MI, const DbgValueProperties &Properties,
490                 Optional<LocIdx> OptNewLoc) {
491     DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
492                       MI.getDebugLoc()->getInlinedAt());
493     // Any use-before-defs no longer apply.
494     UseBeforeDefVariables.erase(Var);
495 
496     // Erase any previous location,
497     auto It = ActiveVLocs.find(Var);
498     if (It != ActiveVLocs.end())
499       ActiveMLocs[It->second.Loc].erase(Var);
500 
501     // If there _is_ no new location, all we had to do was erase.
502     if (!OptNewLoc)
503       return;
504     LocIdx NewLoc = *OptNewLoc;
505 
506     // Check whether our local copy of values-by-location in #VarLocs is out of
507     // date. Wipe old tracking data for the location if it's been clobbered in
508     // the meantime.
509     if (MTracker->readMLoc(NewLoc) != VarLocs[NewLoc.asU64()]) {
510       for (auto &P : ActiveMLocs[NewLoc]) {
511         ActiveVLocs.erase(P);
512       }
513       ActiveMLocs[NewLoc.asU64()].clear();
514       VarLocs[NewLoc.asU64()] = MTracker->readMLoc(NewLoc);
515     }
516 
517     ActiveMLocs[NewLoc].insert(Var);
518     if (It == ActiveVLocs.end()) {
519       ActiveVLocs.insert(
520           std::make_pair(Var, LocAndProperties{NewLoc, Properties}));
521     } else {
522       It->second.Loc = NewLoc;
523       It->second.Properties = Properties;
524     }
525   }
526 
527   /// Account for a location \p mloc being clobbered. Examine the variable
528   /// locations that will be terminated: and try to recover them by using
529   /// another location. Optionally, given \p MakeUndef, emit a DBG_VALUE to
530   /// explicitly terminate a location if it can't be recovered.
531   void clobberMloc(LocIdx MLoc, MachineBasicBlock::iterator Pos,
532                    bool MakeUndef = true) {
533     auto ActiveMLocIt = ActiveMLocs.find(MLoc);
534     if (ActiveMLocIt == ActiveMLocs.end())
535       return;
536 
537     // What was the old variable value?
538     ValueIDNum OldValue = VarLocs[MLoc.asU64()];
539     VarLocs[MLoc.asU64()] = ValueIDNum::EmptyValue;
540 
541     // Examine the remaining variable locations: if we can find the same value
542     // again, we can recover the location.
543     Optional<LocIdx> NewLoc = None;
544     for (auto Loc : MTracker->locations())
545       if (Loc.Value == OldValue)
546         NewLoc = Loc.Idx;
547 
548     // If there is no location, and we weren't asked to make the variable
549     // explicitly undef, then stop here.
550     if (!NewLoc && !MakeUndef) {
551       // Try and recover a few more locations with entry values.
552       for (auto &Var : ActiveMLocIt->second) {
553         auto &Prop = ActiveVLocs.find(Var)->second.Properties;
554         recoverAsEntryValue(Var, Prop, OldValue);
555       }
556       flushDbgValues(Pos, nullptr);
557       return;
558     }
559 
560     // Examine all the variables based on this location.
561     DenseSet<DebugVariable> NewMLocs;
562     for (auto &Var : ActiveMLocIt->second) {
563       auto ActiveVLocIt = ActiveVLocs.find(Var);
564       // Re-state the variable location: if there's no replacement then NewLoc
565       // is None and a $noreg DBG_VALUE will be created. Otherwise, a DBG_VALUE
566       // identifying the alternative location will be emitted.
567       const DbgValueProperties &Properties = ActiveVLocIt->second.Properties;
568       PendingDbgValues.push_back(MTracker->emitLoc(NewLoc, Var, Properties));
569 
570       // Update machine locations <=> variable locations maps. Defer updating
571       // ActiveMLocs to avoid invalidaing the ActiveMLocIt iterator.
572       if (!NewLoc) {
573         ActiveVLocs.erase(ActiveVLocIt);
574       } else {
575         ActiveVLocIt->second.Loc = *NewLoc;
576         NewMLocs.insert(Var);
577       }
578     }
579 
580     // Commit any deferred ActiveMLoc changes.
581     if (!NewMLocs.empty())
582       for (auto &Var : NewMLocs)
583         ActiveMLocs[*NewLoc].insert(Var);
584 
585     // We lazily track what locations have which values; if we've found a new
586     // location for the clobbered value, remember it.
587     if (NewLoc)
588       VarLocs[NewLoc->asU64()] = OldValue;
589 
590     flushDbgValues(Pos, nullptr);
591 
592     // Re-find ActiveMLocIt, iterator could have been invalidated.
593     ActiveMLocIt = ActiveMLocs.find(MLoc);
594     ActiveMLocIt->second.clear();
595   }
596 
597   /// Transfer variables based on \p Src to be based on \p Dst. This handles
598   /// both register copies as well as spills and restores. Creates DBG_VALUEs
599   /// describing the movement.
600   void transferMlocs(LocIdx Src, LocIdx Dst, MachineBasicBlock::iterator Pos) {
601     // Does Src still contain the value num we expect? If not, it's been
602     // clobbered in the meantime, and our variable locations are stale.
603     if (VarLocs[Src.asU64()] != MTracker->readMLoc(Src))
604       return;
605 
606     // assert(ActiveMLocs[Dst].size() == 0);
607     //^^^ Legitimate scenario on account of un-clobbered slot being assigned to?
608 
609     // Move set of active variables from one location to another.
610     auto MovingVars = ActiveMLocs[Src];
611     ActiveMLocs[Dst] = MovingVars;
612     VarLocs[Dst.asU64()] = VarLocs[Src.asU64()];
613 
614     // For each variable based on Src; create a location at Dst.
615     for (auto &Var : MovingVars) {
616       auto ActiveVLocIt = ActiveVLocs.find(Var);
617       assert(ActiveVLocIt != ActiveVLocs.end());
618       ActiveVLocIt->second.Loc = Dst;
619 
620       MachineInstr *MI =
621           MTracker->emitLoc(Dst, Var, ActiveVLocIt->second.Properties);
622       PendingDbgValues.push_back(MI);
623     }
624     ActiveMLocs[Src].clear();
625     flushDbgValues(Pos, nullptr);
626 
627     // XXX XXX XXX "pretend to be old LDV" means dropping all tracking data
628     // about the old location.
629     if (EmulateOldLDV)
630       VarLocs[Src.asU64()] = ValueIDNum::EmptyValue;
631   }
632 
633   MachineInstrBuilder emitMOLoc(const MachineOperand &MO,
634                                 const DebugVariable &Var,
635                                 const DbgValueProperties &Properties) {
636     DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0,
637                                   Var.getVariable()->getScope(),
638                                   const_cast<DILocation *>(Var.getInlinedAt()));
639     auto MIB = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE));
640     MIB.add(MO);
641     if (Properties.Indirect)
642       MIB.addImm(0);
643     else
644       MIB.addReg(0);
645     MIB.addMetadata(Var.getVariable());
646     MIB.addMetadata(Properties.DIExpr);
647     return MIB;
648   }
649 };
650 
651 //===----------------------------------------------------------------------===//
652 //            Implementation
653 //===----------------------------------------------------------------------===//
654 
655 ValueIDNum ValueIDNum::EmptyValue = {UINT_MAX, UINT_MAX, UINT_MAX};
656 ValueIDNum ValueIDNum::TombstoneValue = {UINT_MAX, UINT_MAX, UINT_MAX - 1};
657 
658 #ifndef NDEBUG
659 void DbgValue::dump(const MLocTracker *MTrack) const {
660   if (Kind == Const) {
661     MO->dump();
662   } else if (Kind == NoVal) {
663     dbgs() << "NoVal(" << BlockNo << ")";
664   } else if (Kind == VPHI) {
665     dbgs() << "VPHI(" << BlockNo << "," << MTrack->IDAsString(ID) << ")";
666   } else {
667     assert(Kind == Def);
668     dbgs() << MTrack->IDAsString(ID);
669   }
670   if (Properties.Indirect)
671     dbgs() << " indir";
672   if (Properties.DIExpr)
673     dbgs() << " " << *Properties.DIExpr;
674 }
675 #endif
676 
677 MLocTracker::MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII,
678                          const TargetRegisterInfo &TRI,
679                          const TargetLowering &TLI)
680     : MF(MF), TII(TII), TRI(TRI), TLI(TLI),
681       LocIdxToIDNum(ValueIDNum::EmptyValue), LocIdxToLocID(0) {
682   NumRegs = TRI.getNumRegs();
683   reset();
684   LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc());
685   assert(NumRegs < (1u << NUM_LOC_BITS)); // Detect bit packing failure
686 
687   // Always track SP. This avoids the implicit clobbering caused by regmasks
688   // from affectings its values. (LiveDebugValues disbelieves calls and
689   // regmasks that claim to clobber SP).
690   Register SP = TLI.getStackPointerRegisterToSaveRestore();
691   if (SP) {
692     unsigned ID = getLocID(SP);
693     (void)lookupOrTrackRegister(ID);
694 
695     for (MCRegAliasIterator RAI(SP, &TRI, true); RAI.isValid(); ++RAI)
696       SPAliases.insert(*RAI);
697   }
698 
699   // Build some common stack positions -- full registers being spilt to the
700   // stack.
701   StackSlotIdxes.insert({{8, 0}, 0});
702   StackSlotIdxes.insert({{16, 0}, 1});
703   StackSlotIdxes.insert({{32, 0}, 2});
704   StackSlotIdxes.insert({{64, 0}, 3});
705   StackSlotIdxes.insert({{128, 0}, 4});
706   StackSlotIdxes.insert({{256, 0}, 5});
707   StackSlotIdxes.insert({{512, 0}, 6});
708 
709   // Traverse all the subregister idxes, and ensure there's an index for them.
710   // Duplicates are no problem: we're interested in their position in the
711   // stack slot, we don't want to type the slot.
712   for (unsigned int I = 1; I < TRI.getNumSubRegIndices(); ++I) {
713     unsigned Size = TRI.getSubRegIdxSize(I);
714     unsigned Offs = TRI.getSubRegIdxOffset(I);
715     unsigned Idx = StackSlotIdxes.size();
716 
717     // Some subregs have -1, -2 and so forth fed into their fields, to mean
718     // special backend things. Ignore those.
719     if (Size > 60000 || Offs > 60000)
720       continue;
721 
722     StackSlotIdxes.insert({{Size, Offs}, Idx});
723   }
724 
725   for (auto &Idx : StackSlotIdxes)
726     StackIdxesToPos[Idx.second] = Idx.first;
727 
728   NumSlotIdxes = StackSlotIdxes.size();
729 }
730 
731 LocIdx MLocTracker::trackRegister(unsigned ID) {
732   assert(ID != 0);
733   LocIdx NewIdx = LocIdx(LocIdxToIDNum.size());
734   LocIdxToIDNum.grow(NewIdx);
735   LocIdxToLocID.grow(NewIdx);
736 
737   // Default: it's an mphi.
738   ValueIDNum ValNum = {CurBB, 0, NewIdx};
739   // Was this reg ever touched by a regmask?
740   for (const auto &MaskPair : reverse(Masks)) {
741     if (MaskPair.first->clobbersPhysReg(ID)) {
742       // There was an earlier def we skipped.
743       ValNum = {CurBB, MaskPair.second, NewIdx};
744       break;
745     }
746   }
747 
748   LocIdxToIDNum[NewIdx] = ValNum;
749   LocIdxToLocID[NewIdx] = ID;
750   return NewIdx;
751 }
752 
753 void MLocTracker::writeRegMask(const MachineOperand *MO, unsigned CurBB,
754                                unsigned InstID) {
755   // Def any register we track have that isn't preserved. The regmask
756   // terminates the liveness of a register, meaning its value can't be
757   // relied upon -- we represent this by giving it a new value.
758   for (auto Location : locations()) {
759     unsigned ID = LocIdxToLocID[Location.Idx];
760     // Don't clobber SP, even if the mask says it's clobbered.
761     if (ID < NumRegs && !SPAliases.count(ID) && MO->clobbersPhysReg(ID))
762       defReg(ID, CurBB, InstID);
763   }
764   Masks.push_back(std::make_pair(MO, InstID));
765 }
766 
767 Optional<SpillLocationNo> MLocTracker::getOrTrackSpillLoc(SpillLoc L) {
768   SpillLocationNo SpillID(SpillLocs.idFor(L));
769 
770   if (SpillID.id() == 0) {
771     // If there is no location, and we have reached the limit of how many stack
772     // slots to track, then don't track this one.
773     if (SpillLocs.size() >= StackWorkingSetLimit)
774       return None;
775 
776     // Spill location is untracked: create record for this one, and all
777     // subregister slots too.
778     SpillID = SpillLocationNo(SpillLocs.insert(L));
779     for (unsigned StackIdx = 0; StackIdx < NumSlotIdxes; ++StackIdx) {
780       unsigned L = getSpillIDWithIdx(SpillID, StackIdx);
781       LocIdx Idx = LocIdx(LocIdxToIDNum.size()); // New idx
782       LocIdxToIDNum.grow(Idx);
783       LocIdxToLocID.grow(Idx);
784       LocIDToLocIdx.push_back(Idx);
785       LocIdxToLocID[Idx] = L;
786       // Initialize to PHI value; corresponds to the location's live-in value
787       // during transfer function construction.
788       LocIdxToIDNum[Idx] = ValueIDNum(CurBB, 0, Idx);
789     }
790   }
791   return SpillID;
792 }
793 
794 std::string MLocTracker::LocIdxToName(LocIdx Idx) const {
795   unsigned ID = LocIdxToLocID[Idx];
796   if (ID >= NumRegs) {
797     StackSlotPos Pos = locIDToSpillIdx(ID);
798     ID -= NumRegs;
799     unsigned Slot = ID / NumSlotIdxes;
800     return Twine("slot ")
801         .concat(Twine(Slot).concat(Twine(" sz ").concat(Twine(Pos.first)
802         .concat(Twine(" offs ").concat(Twine(Pos.second))))))
803         .str();
804   } else {
805     return TRI.getRegAsmName(ID).str();
806   }
807 }
808 
809 std::string MLocTracker::IDAsString(const ValueIDNum &Num) const {
810   std::string DefName = LocIdxToName(Num.getLoc());
811   return Num.asString(DefName);
812 }
813 
814 #ifndef NDEBUG
815 LLVM_DUMP_METHOD void MLocTracker::dump() {
816   for (auto Location : locations()) {
817     std::string MLocName = LocIdxToName(Location.Value.getLoc());
818     std::string DefName = Location.Value.asString(MLocName);
819     dbgs() << LocIdxToName(Location.Idx) << " --> " << DefName << "\n";
820   }
821 }
822 
823 LLVM_DUMP_METHOD void MLocTracker::dump_mloc_map() {
824   for (auto Location : locations()) {
825     std::string foo = LocIdxToName(Location.Idx);
826     dbgs() << "Idx " << Location.Idx.asU64() << " " << foo << "\n";
827   }
828 }
829 #endif
830 
831 MachineInstrBuilder MLocTracker::emitLoc(Optional<LocIdx> MLoc,
832                                          const DebugVariable &Var,
833                                          const DbgValueProperties &Properties) {
834   DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0,
835                                 Var.getVariable()->getScope(),
836                                 const_cast<DILocation *>(Var.getInlinedAt()));
837   auto MIB = BuildMI(MF, DL, TII.get(TargetOpcode::DBG_VALUE));
838 
839   const DIExpression *Expr = Properties.DIExpr;
840   if (!MLoc) {
841     // No location -> DBG_VALUE $noreg
842     MIB.addReg(0);
843     MIB.addReg(0);
844   } else if (LocIdxToLocID[*MLoc] >= NumRegs) {
845     unsigned LocID = LocIdxToLocID[*MLoc];
846     SpillLocationNo SpillID = locIDToSpill(LocID);
847     StackSlotPos StackIdx = locIDToSpillIdx(LocID);
848     unsigned short Offset = StackIdx.second;
849 
850     // TODO: support variables that are located in spill slots, with non-zero
851     // offsets from the start of the spill slot. It would require some more
852     // complex DIExpression calculations. This doesn't seem to be produced by
853     // LLVM right now, so don't try and support it.
854     // Accept no-subregister slots and subregisters where the offset is zero.
855     // The consumer should already have type information to work out how large
856     // the variable is.
857     if (Offset == 0) {
858       const SpillLoc &Spill = SpillLocs[SpillID.id()];
859       Expr = TRI.prependOffsetExpression(Expr, DIExpression::ApplyOffset,
860                                          Spill.SpillOffset);
861       unsigned Base = Spill.SpillBase;
862       MIB.addReg(Base);
863       MIB.addImm(0);
864 
865       // Being on the stack makes this location indirect; if it was _already_
866       // indirect though, we need to add extra indirection. See this test for
867       // a scenario where this happens:
868       //     llvm/test/DebugInfo/X86/spill-nontrivial-param.ll
869       if (Properties.Indirect) {
870         std::vector<uint64_t> Elts = {dwarf::DW_OP_deref};
871         Expr = DIExpression::append(Expr, Elts);
872       }
873     } else {
874       // This is a stack location with a weird subregister offset: emit an undef
875       // DBG_VALUE instead.
876       MIB.addReg(0);
877       MIB.addReg(0);
878     }
879   } else {
880     // Non-empty, non-stack slot, must be a plain register.
881     unsigned LocID = LocIdxToLocID[*MLoc];
882     MIB.addReg(LocID);
883     if (Properties.Indirect)
884       MIB.addImm(0);
885     else
886       MIB.addReg(0);
887   }
888 
889   MIB.addMetadata(Var.getVariable());
890   MIB.addMetadata(Expr);
891   return MIB;
892 }
893 
894 /// Default construct and initialize the pass.
895 InstrRefBasedLDV::InstrRefBasedLDV() = default;
896 
897 bool InstrRefBasedLDV::isCalleeSaved(LocIdx L) const {
898   unsigned Reg = MTracker->LocIdxToLocID[L];
899   for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
900     if (CalleeSavedRegs.test(*RAI))
901       return true;
902   return false;
903 }
904 
905 //===----------------------------------------------------------------------===//
906 //            Debug Range Extension Implementation
907 //===----------------------------------------------------------------------===//
908 
909 #ifndef NDEBUG
910 // Something to restore in the future.
911 // void InstrRefBasedLDV::printVarLocInMBB(..)
912 #endif
913 
914 Optional<SpillLocationNo>
915 InstrRefBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
916   assert(MI.hasOneMemOperand() &&
917          "Spill instruction does not have exactly one memory operand?");
918   auto MMOI = MI.memoperands_begin();
919   const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
920   assert(PVal->kind() == PseudoSourceValue::FixedStack &&
921          "Inconsistent memory operand in spill instruction");
922   int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
923   const MachineBasicBlock *MBB = MI.getParent();
924   Register Reg;
925   StackOffset Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
926   return MTracker->getOrTrackSpillLoc({Reg, Offset});
927 }
928 
929 Optional<LocIdx>
930 InstrRefBasedLDV::findLocationForMemOperand(const MachineInstr &MI) {
931   Optional<SpillLocationNo> SpillLoc = extractSpillBaseRegAndOffset(MI);
932   if (!SpillLoc)
933     return None;
934 
935   // Where in the stack slot is this value defined -- i.e., what size of value
936   // is this? An important question, because it could be loaded into a register
937   // from the stack at some point. Happily the memory operand will tell us
938   // the size written to the stack.
939   auto *MemOperand = *MI.memoperands_begin();
940   unsigned SizeInBits = MemOperand->getSizeInBits();
941 
942   // Find that position in the stack indexes we're tracking.
943   auto IdxIt = MTracker->StackSlotIdxes.find({SizeInBits, 0});
944   if (IdxIt == MTracker->StackSlotIdxes.end())
945     // That index is not tracked. This is suprising, and unlikely to ever
946     // occur, but the safe action is to indicate the variable is optimised out.
947     return None;
948 
949   unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillLoc, IdxIt->second);
950   return MTracker->getSpillMLoc(SpillID);
951 }
952 
953 /// End all previous ranges related to @MI and start a new range from @MI
954 /// if it is a DBG_VALUE instr.
955 bool InstrRefBasedLDV::transferDebugValue(const MachineInstr &MI) {
956   if (!MI.isDebugValue())
957     return false;
958 
959   const DILocalVariable *Var = MI.getDebugVariable();
960   const DIExpression *Expr = MI.getDebugExpression();
961   const DILocation *DebugLoc = MI.getDebugLoc();
962   const DILocation *InlinedAt = DebugLoc->getInlinedAt();
963   assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
964          "Expected inlined-at fields to agree");
965 
966   DebugVariable V(Var, Expr, InlinedAt);
967   DbgValueProperties Properties(MI);
968 
969   // If there are no instructions in this lexical scope, do no location tracking
970   // at all, this variable shouldn't get a legitimate location range.
971   auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
972   if (Scope == nullptr)
973     return true; // handled it; by doing nothing
974 
975   // For now, ignore DBG_VALUE_LISTs when extending ranges. Allow it to
976   // contribute to locations in this block, but don't propagate further.
977   // Interpret it like a DBG_VALUE $noreg.
978   if (MI.isDebugValueList()) {
979     if (VTracker)
980       VTracker->defVar(MI, Properties, None);
981     if (TTracker)
982       TTracker->redefVar(MI, Properties, None);
983     return true;
984   }
985 
986   const MachineOperand &MO = MI.getOperand(0);
987 
988   // MLocTracker needs to know that this register is read, even if it's only
989   // read by a debug inst.
990   if (MO.isReg() && MO.getReg() != 0)
991     (void)MTracker->readReg(MO.getReg());
992 
993   // If we're preparing for the second analysis (variables), the machine value
994   // locations are already solved, and we report this DBG_VALUE and the value
995   // it refers to to VLocTracker.
996   if (VTracker) {
997     if (MO.isReg()) {
998       // Feed defVar the new variable location, or if this is a
999       // DBG_VALUE $noreg, feed defVar None.
1000       if (MO.getReg())
1001         VTracker->defVar(MI, Properties, MTracker->readReg(MO.getReg()));
1002       else
1003         VTracker->defVar(MI, Properties, None);
1004     } else if (MI.getOperand(0).isImm() || MI.getOperand(0).isFPImm() ||
1005                MI.getOperand(0).isCImm()) {
1006       VTracker->defVar(MI, MI.getOperand(0));
1007     }
1008   }
1009 
1010   // If performing final tracking of transfers, report this variable definition
1011   // to the TransferTracker too.
1012   if (TTracker)
1013     TTracker->redefVar(MI);
1014   return true;
1015 }
1016 
1017 bool InstrRefBasedLDV::transferDebugInstrRef(MachineInstr &MI,
1018                                              const ValueTable *MLiveOuts,
1019                                              const ValueTable *MLiveIns) {
1020   if (!MI.isDebugRef())
1021     return false;
1022 
1023   // Only handle this instruction when we are building the variable value
1024   // transfer function.
1025   if (!VTracker && !TTracker)
1026     return false;
1027 
1028   unsigned InstNo = MI.getOperand(0).getImm();
1029   unsigned OpNo = MI.getOperand(1).getImm();
1030 
1031   const DILocalVariable *Var = MI.getDebugVariable();
1032   const DIExpression *Expr = MI.getDebugExpression();
1033   const DILocation *DebugLoc = MI.getDebugLoc();
1034   const DILocation *InlinedAt = DebugLoc->getInlinedAt();
1035   assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
1036          "Expected inlined-at fields to agree");
1037 
1038   DebugVariable V(Var, Expr, InlinedAt);
1039 
1040   auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get());
1041   if (Scope == nullptr)
1042     return true; // Handled by doing nothing. This variable is never in scope.
1043 
1044   const MachineFunction &MF = *MI.getParent()->getParent();
1045 
1046   // Various optimizations may have happened to the value during codegen,
1047   // recorded in the value substitution table. Apply any substitutions to
1048   // the instruction / operand number in this DBG_INSTR_REF, and collect
1049   // any subregister extractions performed during optimization.
1050 
1051   // Create dummy substitution with Src set, for lookup.
1052   auto SoughtSub =
1053       MachineFunction::DebugSubstitution({InstNo, OpNo}, {0, 0}, 0);
1054 
1055   SmallVector<unsigned, 4> SeenSubregs;
1056   auto LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub);
1057   while (LowerBoundIt != MF.DebugValueSubstitutions.end() &&
1058          LowerBoundIt->Src == SoughtSub.Src) {
1059     std::tie(InstNo, OpNo) = LowerBoundIt->Dest;
1060     SoughtSub.Src = LowerBoundIt->Dest;
1061     if (unsigned Subreg = LowerBoundIt->Subreg)
1062       SeenSubregs.push_back(Subreg);
1063     LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub);
1064   }
1065 
1066   // Default machine value number is <None> -- if no instruction defines
1067   // the corresponding value, it must have been optimized out.
1068   Optional<ValueIDNum> NewID = None;
1069 
1070   // Try to lookup the instruction number, and find the machine value number
1071   // that it defines. It could be an instruction, or a PHI.
1072   auto InstrIt = DebugInstrNumToInstr.find(InstNo);
1073   auto PHIIt = std::lower_bound(DebugPHINumToValue.begin(),
1074                                 DebugPHINumToValue.end(), InstNo);
1075   if (InstrIt != DebugInstrNumToInstr.end()) {
1076     const MachineInstr &TargetInstr = *InstrIt->second.first;
1077     uint64_t BlockNo = TargetInstr.getParent()->getNumber();
1078 
1079     // Pick out the designated operand. It might be a memory reference, if
1080     // a register def was folded into a stack store.
1081     if (OpNo == MachineFunction::DebugOperandMemNumber &&
1082         TargetInstr.hasOneMemOperand()) {
1083       Optional<LocIdx> L = findLocationForMemOperand(TargetInstr);
1084       if (L)
1085         NewID = ValueIDNum(BlockNo, InstrIt->second.second, *L);
1086     } else if (OpNo != MachineFunction::DebugOperandMemNumber) {
1087       // Permit the debug-info to be completely wrong: identifying a nonexistant
1088       // operand, or one that is not a register definition, means something
1089       // unexpected happened during optimisation. Broken debug-info, however,
1090       // shouldn't crash the compiler -- instead leave the variable value as
1091       // None, which will make it appear "optimised out".
1092       if (OpNo < TargetInstr.getNumOperands()) {
1093         const MachineOperand &MO = TargetInstr.getOperand(OpNo);
1094 
1095         if (MO.isReg() && MO.isDef() && MO.getReg()) {
1096           unsigned LocID = MTracker->getLocID(MO.getReg());
1097           LocIdx L = MTracker->LocIDToLocIdx[LocID];
1098           NewID = ValueIDNum(BlockNo, InstrIt->second.second, L);
1099         }
1100       }
1101 
1102       if (!NewID) {
1103         LLVM_DEBUG(
1104             { dbgs() << "Seen instruction reference to illegal operand\n"; });
1105       }
1106     }
1107     // else: NewID is left as None.
1108   } else if (PHIIt != DebugPHINumToValue.end() && PHIIt->InstrNum == InstNo) {
1109     // It's actually a PHI value. Which value it is might not be obvious, use
1110     // the resolver helper to find out.
1111     NewID = resolveDbgPHIs(*MI.getParent()->getParent(), MLiveOuts, MLiveIns,
1112                            MI, InstNo);
1113   }
1114 
1115   // Apply any subregister extractions, in reverse. We might have seen code
1116   // like this:
1117   //    CALL64 @foo, implicit-def $rax
1118   //    %0:gr64 = COPY $rax
1119   //    %1:gr32 = COPY %0.sub_32bit
1120   //    %2:gr16 = COPY %1.sub_16bit
1121   //    %3:gr8  = COPY %2.sub_8bit
1122   // In which case each copy would have been recorded as a substitution with
1123   // a subregister qualifier. Apply those qualifiers now.
1124   if (NewID && !SeenSubregs.empty()) {
1125     unsigned Offset = 0;
1126     unsigned Size = 0;
1127 
1128     // Look at each subregister that we passed through, and progressively
1129     // narrow in, accumulating any offsets that occur. Substitutions should
1130     // only ever be the same or narrower width than what they read from;
1131     // iterate in reverse order so that we go from wide to small.
1132     for (unsigned Subreg : reverse(SeenSubregs)) {
1133       unsigned ThisSize = TRI->getSubRegIdxSize(Subreg);
1134       unsigned ThisOffset = TRI->getSubRegIdxOffset(Subreg);
1135       Offset += ThisOffset;
1136       Size = (Size == 0) ? ThisSize : std::min(Size, ThisSize);
1137     }
1138 
1139     // If that worked, look for an appropriate subregister with the register
1140     // where the define happens. Don't look at values that were defined during
1141     // a stack write: we can't currently express register locations within
1142     // spills.
1143     LocIdx L = NewID->getLoc();
1144     if (NewID && !MTracker->isSpill(L)) {
1145       // Find the register class for the register where this def happened.
1146       // FIXME: no index for this?
1147       Register Reg = MTracker->LocIdxToLocID[L];
1148       const TargetRegisterClass *TRC = nullptr;
1149       for (auto *TRCI : TRI->regclasses())
1150         if (TRCI->contains(Reg))
1151           TRC = TRCI;
1152       assert(TRC && "Couldn't find target register class?");
1153 
1154       // If the register we have isn't the right size or in the right place,
1155       // Try to find a subregister inside it.
1156       unsigned MainRegSize = TRI->getRegSizeInBits(*TRC);
1157       if (Size != MainRegSize || Offset) {
1158         // Enumerate all subregisters, searching.
1159         Register NewReg = 0;
1160         for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) {
1161           unsigned Subreg = TRI->getSubRegIndex(Reg, *SRI);
1162           unsigned SubregSize = TRI->getSubRegIdxSize(Subreg);
1163           unsigned SubregOffset = TRI->getSubRegIdxOffset(Subreg);
1164           if (SubregSize == Size && SubregOffset == Offset) {
1165             NewReg = *SRI;
1166             break;
1167           }
1168         }
1169 
1170         // If we didn't find anything: there's no way to express our value.
1171         if (!NewReg) {
1172           NewID = None;
1173         } else {
1174           // Re-state the value as being defined within the subregister
1175           // that we found.
1176           LocIdx NewLoc = MTracker->lookupOrTrackRegister(NewReg);
1177           NewID = ValueIDNum(NewID->getBlock(), NewID->getInst(), NewLoc);
1178         }
1179       }
1180     } else {
1181       // If we can't handle subregisters, unset the new value.
1182       NewID = None;
1183     }
1184   }
1185 
1186   // We, we have a value number or None. Tell the variable value tracker about
1187   // it. The rest of this LiveDebugValues implementation acts exactly the same
1188   // for DBG_INSTR_REFs as DBG_VALUEs (just, the former can refer to values that
1189   // aren't immediately available).
1190   DbgValueProperties Properties(Expr, false);
1191   if (VTracker)
1192     VTracker->defVar(MI, Properties, NewID);
1193 
1194   // If we're on the final pass through the function, decompose this INSTR_REF
1195   // into a plain DBG_VALUE.
1196   if (!TTracker)
1197     return true;
1198 
1199   // Pick a location for the machine value number, if such a location exists.
1200   // (This information could be stored in TransferTracker to make it faster).
1201   Optional<LocIdx> FoundLoc = None;
1202   for (auto Location : MTracker->locations()) {
1203     LocIdx CurL = Location.Idx;
1204     ValueIDNum ID = MTracker->readMLoc(CurL);
1205     if (NewID && ID == NewID) {
1206       // If this is the first location with that value, pick it. Otherwise,
1207       // consider whether it's a "longer term" location.
1208       if (!FoundLoc) {
1209         FoundLoc = CurL;
1210         continue;
1211       }
1212 
1213       if (MTracker->isSpill(CurL))
1214         FoundLoc = CurL; // Spills are a longer term location.
1215       else if (!MTracker->isSpill(*FoundLoc) &&
1216                !MTracker->isSpill(CurL) &&
1217                !isCalleeSaved(*FoundLoc) &&
1218                isCalleeSaved(CurL))
1219         FoundLoc = CurL; // Callee saved regs are longer term than normal.
1220     }
1221   }
1222 
1223   // Tell transfer tracker that the variable value has changed.
1224   TTracker->redefVar(MI, Properties, FoundLoc);
1225 
1226   // If there was a value with no location; but the value is defined in a
1227   // later instruction in this block, this is a block-local use-before-def.
1228   if (!FoundLoc && NewID && NewID->getBlock() == CurBB &&
1229       NewID->getInst() > CurInst)
1230     TTracker->addUseBeforeDef(V, {MI.getDebugExpression(), false}, *NewID);
1231 
1232   // Produce a DBG_VALUE representing what this DBG_INSTR_REF meant.
1233   // This DBG_VALUE is potentially a $noreg / undefined location, if
1234   // FoundLoc is None.
1235   // (XXX -- could morph the DBG_INSTR_REF in the future).
1236   MachineInstr *DbgMI = MTracker->emitLoc(FoundLoc, V, Properties);
1237   TTracker->PendingDbgValues.push_back(DbgMI);
1238   TTracker->flushDbgValues(MI.getIterator(), nullptr);
1239   return true;
1240 }
1241 
1242 bool InstrRefBasedLDV::transferDebugPHI(MachineInstr &MI) {
1243   if (!MI.isDebugPHI())
1244     return false;
1245 
1246   // Analyse these only when solving the machine value location problem.
1247   if (VTracker || TTracker)
1248     return true;
1249 
1250   // First operand is the value location, either a stack slot or register.
1251   // Second is the debug instruction number of the original PHI.
1252   const MachineOperand &MO = MI.getOperand(0);
1253   unsigned InstrNum = MI.getOperand(1).getImm();
1254 
1255   auto EmitBadPHI = [this, &MI, InstrNum](void) -> bool {
1256     // Helper lambda to do any accounting when we fail to find a location for
1257     // a DBG_PHI. This can happen if DBG_PHIs are malformed, or refer to a
1258     // dead stack slot, for example.
1259     // Record a DebugPHIRecord with an empty value + location.
1260     DebugPHINumToValue.push_back({InstrNum, MI.getParent(), None, None});
1261     return true;
1262   };
1263 
1264   if (MO.isReg() && MO.getReg()) {
1265     // The value is whatever's currently in the register. Read and record it,
1266     // to be analysed later.
1267     Register Reg = MO.getReg();
1268     ValueIDNum Num = MTracker->readReg(Reg);
1269     auto PHIRec = DebugPHIRecord(
1270         {InstrNum, MI.getParent(), Num, MTracker->lookupOrTrackRegister(Reg)});
1271     DebugPHINumToValue.push_back(PHIRec);
1272 
1273     // Ensure this register is tracked.
1274     for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1275       MTracker->lookupOrTrackRegister(*RAI);
1276   } else if (MO.isFI()) {
1277     // The value is whatever's in this stack slot.
1278     unsigned FI = MO.getIndex();
1279 
1280     // If the stack slot is dead, then this was optimized away.
1281     // FIXME: stack slot colouring should account for slots that get merged.
1282     if (MFI->isDeadObjectIndex(FI))
1283       return EmitBadPHI();
1284 
1285     // Identify this spill slot, ensure it's tracked.
1286     Register Base;
1287     StackOffset Offs = TFI->getFrameIndexReference(*MI.getMF(), FI, Base);
1288     SpillLoc SL = {Base, Offs};
1289     Optional<SpillLocationNo> SpillNo = MTracker->getOrTrackSpillLoc(SL);
1290 
1291     // We might be able to find a value, but have chosen not to, to avoid
1292     // tracking too much stack information.
1293     if (!SpillNo)
1294       return EmitBadPHI();
1295 
1296     // Problem: what value should we extract from the stack? LLVM does not
1297     // record what size the last store to the slot was, and it would become
1298     // sketchy after stack slot colouring anyway. Take a look at what values
1299     // are stored on the stack, and pick the largest one that wasn't def'd
1300     // by a spill (i.e., the value most likely to have been def'd in a register
1301     // and then spilt.
1302     std::array<unsigned, 4> CandidateSizes = {64, 32, 16, 8};
1303     Optional<ValueIDNum> Result = None;
1304     Optional<LocIdx> SpillLoc = None;
1305     for (unsigned CS : CandidateSizes) {
1306       unsigned SpillID = MTracker->getLocID(*SpillNo, {CS, 0});
1307       SpillLoc = MTracker->getSpillMLoc(SpillID);
1308       ValueIDNum Val = MTracker->readMLoc(*SpillLoc);
1309       // If this value was defined in it's own position, then it was probably
1310       // an aliasing index of a small value that was spilt.
1311       if (Val.getLoc() != SpillLoc->asU64()) {
1312         Result = Val;
1313         break;
1314       }
1315     }
1316 
1317     // If we didn't find anything, we're probably looking at a PHI, or a memory
1318     // store folded into an instruction. FIXME: Take a guess that's it's 64
1319     // bits. This isn't ideal, but tracking the size that the spill is
1320     // "supposed" to be is more complex, and benefits a small number of
1321     // locations.
1322     if (!Result) {
1323       unsigned SpillID = MTracker->getLocID(*SpillNo, {64, 0});
1324       SpillLoc = MTracker->getSpillMLoc(SpillID);
1325       Result = MTracker->readMLoc(*SpillLoc);
1326     }
1327 
1328     // Record this DBG_PHI for later analysis.
1329     auto DbgPHI =
1330         DebugPHIRecord({InstrNum, MI.getParent(), *Result, *SpillLoc});
1331     DebugPHINumToValue.push_back(DbgPHI);
1332   } else {
1333     // Else: if the operand is neither a legal register or a stack slot, then
1334     // we're being fed illegal debug-info. Record an empty PHI, so that any
1335     // debug users trying to read this number will be put off trying to
1336     // interpret the value.
1337     LLVM_DEBUG(
1338         { dbgs() << "Seen DBG_PHI with unrecognised operand format\n"; });
1339     return EmitBadPHI();
1340   }
1341 
1342   return true;
1343 }
1344 
1345 void InstrRefBasedLDV::transferRegisterDef(MachineInstr &MI) {
1346   // Meta Instructions do not affect the debug liveness of any register they
1347   // define.
1348   if (MI.isImplicitDef()) {
1349     // Except when there's an implicit def, and the location it's defining has
1350     // no value number. The whole point of an implicit def is to announce that
1351     // the register is live, without be specific about it's value. So define
1352     // a value if there isn't one already.
1353     ValueIDNum Num = MTracker->readReg(MI.getOperand(0).getReg());
1354     // Has a legitimate value -> ignore the implicit def.
1355     if (Num.getLoc() != 0)
1356       return;
1357     // Otherwise, def it here.
1358   } else if (MI.isMetaInstruction())
1359     return;
1360 
1361   // We always ignore SP defines on call instructions, they don't actually
1362   // change the value of the stack pointer... except for win32's _chkstk. This
1363   // is rare: filter quickly for the common case (no stack adjustments, not a
1364   // call, etc). If it is a call that modifies SP, recognise the SP register
1365   // defs.
1366   bool CallChangesSP = false;
1367   if (AdjustsStackInCalls && MI.isCall() && MI.getOperand(0).isSymbol() &&
1368       !strcmp(MI.getOperand(0).getSymbolName(), StackProbeSymbolName.data()))
1369     CallChangesSP = true;
1370 
1371   // Test whether we should ignore a def of this register due to it being part
1372   // of the stack pointer.
1373   auto IgnoreSPAlias = [this, &MI, CallChangesSP](Register R) -> bool {
1374     if (CallChangesSP)
1375       return false;
1376     return MI.isCall() && MTracker->SPAliases.count(R);
1377   };
1378 
1379   // Find the regs killed by MI, and find regmasks of preserved regs.
1380   // Max out the number of statically allocated elements in `DeadRegs`, as this
1381   // prevents fallback to std::set::count() operations.
1382   SmallSet<uint32_t, 32> DeadRegs;
1383   SmallVector<const uint32_t *, 4> RegMasks;
1384   SmallVector<const MachineOperand *, 4> RegMaskPtrs;
1385   for (const MachineOperand &MO : MI.operands()) {
1386     // Determine whether the operand is a register def.
1387     if (MO.isReg() && MO.isDef() && MO.getReg() &&
1388         Register::isPhysicalRegister(MO.getReg()) &&
1389         !IgnoreSPAlias(MO.getReg())) {
1390       // Remove ranges of all aliased registers.
1391       for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1392         // FIXME: Can we break out of this loop early if no insertion occurs?
1393         DeadRegs.insert(*RAI);
1394     } else if (MO.isRegMask()) {
1395       RegMasks.push_back(MO.getRegMask());
1396       RegMaskPtrs.push_back(&MO);
1397     }
1398   }
1399 
1400   // Tell MLocTracker about all definitions, of regmasks and otherwise.
1401   for (uint32_t DeadReg : DeadRegs)
1402     MTracker->defReg(DeadReg, CurBB, CurInst);
1403 
1404   for (auto *MO : RegMaskPtrs)
1405     MTracker->writeRegMask(MO, CurBB, CurInst);
1406 
1407   // If this instruction writes to a spill slot, def that slot.
1408   if (hasFoldedStackStore(MI)) {
1409     if (Optional<SpillLocationNo> SpillNo = extractSpillBaseRegAndOffset(MI)) {
1410       for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) {
1411         unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillNo, I);
1412         LocIdx L = MTracker->getSpillMLoc(SpillID);
1413         MTracker->setMLoc(L, ValueIDNum(CurBB, CurInst, L));
1414       }
1415     }
1416   }
1417 
1418   if (!TTracker)
1419     return;
1420 
1421   // When committing variable values to locations: tell transfer tracker that
1422   // we've clobbered things. It may be able to recover the variable from a
1423   // different location.
1424 
1425   // Inform TTracker about any direct clobbers.
1426   for (uint32_t DeadReg : DeadRegs) {
1427     LocIdx Loc = MTracker->lookupOrTrackRegister(DeadReg);
1428     TTracker->clobberMloc(Loc, MI.getIterator(), false);
1429   }
1430 
1431   // Look for any clobbers performed by a register mask. Only test locations
1432   // that are actually being tracked.
1433   if (!RegMaskPtrs.empty()) {
1434     for (auto L : MTracker->locations()) {
1435       // Stack locations can't be clobbered by regmasks.
1436       if (MTracker->isSpill(L.Idx))
1437         continue;
1438 
1439       Register Reg = MTracker->LocIdxToLocID[L.Idx];
1440       if (IgnoreSPAlias(Reg))
1441         continue;
1442 
1443       for (auto *MO : RegMaskPtrs)
1444         if (MO->clobbersPhysReg(Reg))
1445           TTracker->clobberMloc(L.Idx, MI.getIterator(), false);
1446     }
1447   }
1448 
1449   // Tell TTracker about any folded stack store.
1450   if (hasFoldedStackStore(MI)) {
1451     if (Optional<SpillLocationNo> SpillNo = extractSpillBaseRegAndOffset(MI)) {
1452       for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) {
1453         unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillNo, I);
1454         LocIdx L = MTracker->getSpillMLoc(SpillID);
1455         TTracker->clobberMloc(L, MI.getIterator(), true);
1456       }
1457     }
1458   }
1459 }
1460 
1461 void InstrRefBasedLDV::performCopy(Register SrcRegNum, Register DstRegNum) {
1462   // In all circumstances, re-def all aliases. It's definitely a new value now.
1463   for (MCRegAliasIterator RAI(DstRegNum, TRI, true); RAI.isValid(); ++RAI)
1464     MTracker->defReg(*RAI, CurBB, CurInst);
1465 
1466   ValueIDNum SrcValue = MTracker->readReg(SrcRegNum);
1467   MTracker->setReg(DstRegNum, SrcValue);
1468 
1469   // Copy subregisters from one location to another.
1470   for (MCSubRegIndexIterator SRI(SrcRegNum, TRI); SRI.isValid(); ++SRI) {
1471     unsigned SrcSubReg = SRI.getSubReg();
1472     unsigned SubRegIdx = SRI.getSubRegIndex();
1473     unsigned DstSubReg = TRI->getSubReg(DstRegNum, SubRegIdx);
1474     if (!DstSubReg)
1475       continue;
1476 
1477     // Do copy. There are two matching subregisters, the source value should
1478     // have been def'd when the super-reg was, the latter might not be tracked
1479     // yet.
1480     // This will force SrcSubReg to be tracked, if it isn't yet. Will read
1481     // mphi values if it wasn't tracked.
1482     LocIdx SrcL = MTracker->lookupOrTrackRegister(SrcSubReg);
1483     LocIdx DstL = MTracker->lookupOrTrackRegister(DstSubReg);
1484     (void)SrcL;
1485     (void)DstL;
1486     ValueIDNum CpyValue = MTracker->readReg(SrcSubReg);
1487 
1488     MTracker->setReg(DstSubReg, CpyValue);
1489   }
1490 }
1491 
1492 Optional<SpillLocationNo>
1493 InstrRefBasedLDV::isSpillInstruction(const MachineInstr &MI,
1494                                      MachineFunction *MF) {
1495   // TODO: Handle multiple stores folded into one.
1496   if (!MI.hasOneMemOperand())
1497     return None;
1498 
1499   // Reject any memory operand that's aliased -- we can't guarantee its value.
1500   auto MMOI = MI.memoperands_begin();
1501   const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
1502   if (PVal->isAliased(MFI))
1503     return None;
1504 
1505   if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
1506     return None; // This is not a spill instruction, since no valid size was
1507                  // returned from either function.
1508 
1509   return extractSpillBaseRegAndOffset(MI);
1510 }
1511 
1512 bool InstrRefBasedLDV::isLocationSpill(const MachineInstr &MI,
1513                                        MachineFunction *MF, unsigned &Reg) {
1514   if (!isSpillInstruction(MI, MF))
1515     return false;
1516 
1517   int FI;
1518   Reg = TII->isStoreToStackSlotPostFE(MI, FI);
1519   return Reg != 0;
1520 }
1521 
1522 Optional<SpillLocationNo>
1523 InstrRefBasedLDV::isRestoreInstruction(const MachineInstr &MI,
1524                                        MachineFunction *MF, unsigned &Reg) {
1525   if (!MI.hasOneMemOperand())
1526     return None;
1527 
1528   // FIXME: Handle folded restore instructions with more than one memory
1529   // operand.
1530   if (MI.getRestoreSize(TII)) {
1531     Reg = MI.getOperand(0).getReg();
1532     return extractSpillBaseRegAndOffset(MI);
1533   }
1534   return None;
1535 }
1536 
1537 bool InstrRefBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI) {
1538   // XXX -- it's too difficult to implement VarLocBasedImpl's  stack location
1539   // limitations under the new model. Therefore, when comparing them, compare
1540   // versions that don't attempt spills or restores at all.
1541   if (EmulateOldLDV)
1542     return false;
1543 
1544   // Strictly limit ourselves to plain loads and stores, not all instructions
1545   // that can access the stack.
1546   int DummyFI = -1;
1547   if (!TII->isStoreToStackSlotPostFE(MI, DummyFI) &&
1548       !TII->isLoadFromStackSlotPostFE(MI, DummyFI))
1549     return false;
1550 
1551   MachineFunction *MF = MI.getMF();
1552   unsigned Reg;
1553 
1554   LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
1555 
1556   // Strictly limit ourselves to plain loads and stores, not all instructions
1557   // that can access the stack.
1558   int FIDummy;
1559   if (!TII->isStoreToStackSlotPostFE(MI, FIDummy) &&
1560       !TII->isLoadFromStackSlotPostFE(MI, FIDummy))
1561     return false;
1562 
1563   // First, if there are any DBG_VALUEs pointing at a spill slot that is
1564   // written to, terminate that variable location. The value in memory
1565   // will have changed. DbgEntityHistoryCalculator doesn't try to detect this.
1566   if (Optional<SpillLocationNo> Loc = isSpillInstruction(MI, MF)) {
1567     // Un-set this location and clobber, so that earlier locations don't
1568     // continue past this store.
1569     for (unsigned SlotIdx = 0; SlotIdx < MTracker->NumSlotIdxes; ++SlotIdx) {
1570       unsigned SpillID = MTracker->getSpillIDWithIdx(*Loc, SlotIdx);
1571       Optional<LocIdx> MLoc = MTracker->getSpillMLoc(SpillID);
1572       if (!MLoc)
1573         continue;
1574 
1575       // We need to over-write the stack slot with something (here, a def at
1576       // this instruction) to ensure no values are preserved in this stack slot
1577       // after the spill. It also prevents TTracker from trying to recover the
1578       // location and re-installing it in the same place.
1579       ValueIDNum Def(CurBB, CurInst, *MLoc);
1580       MTracker->setMLoc(*MLoc, Def);
1581       if (TTracker)
1582         TTracker->clobberMloc(*MLoc, MI.getIterator());
1583     }
1584   }
1585 
1586   // Try to recognise spill and restore instructions that may transfer a value.
1587   if (isLocationSpill(MI, MF, Reg)) {
1588     // isLocationSpill returning true should guarantee we can extract a
1589     // location.
1590     SpillLocationNo Loc = *extractSpillBaseRegAndOffset(MI);
1591 
1592     auto DoTransfer = [&](Register SrcReg, unsigned SpillID) {
1593       auto ReadValue = MTracker->readReg(SrcReg);
1594       LocIdx DstLoc = MTracker->getSpillMLoc(SpillID);
1595       MTracker->setMLoc(DstLoc, ReadValue);
1596 
1597       if (TTracker) {
1598         LocIdx SrcLoc = MTracker->getRegMLoc(SrcReg);
1599         TTracker->transferMlocs(SrcLoc, DstLoc, MI.getIterator());
1600       }
1601     };
1602 
1603     // Then, transfer subreg bits.
1604     for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) {
1605       // Ensure this reg is tracked,
1606       (void)MTracker->lookupOrTrackRegister(*SRI);
1607       unsigned SubregIdx = TRI->getSubRegIndex(Reg, *SRI);
1608       unsigned SpillID = MTracker->getLocID(Loc, SubregIdx);
1609       DoTransfer(*SRI, SpillID);
1610     }
1611 
1612     // Directly lookup size of main source reg, and transfer.
1613     unsigned Size = TRI->getRegSizeInBits(Reg, *MRI);
1614     unsigned SpillID = MTracker->getLocID(Loc, {Size, 0});
1615     DoTransfer(Reg, SpillID);
1616   } else {
1617     Optional<SpillLocationNo> Loc = isRestoreInstruction(MI, MF, Reg);
1618     if (!Loc)
1619       return false;
1620 
1621     // Assumption: we're reading from the base of the stack slot, not some
1622     // offset into it. It seems very unlikely LLVM would ever generate
1623     // restores where this wasn't true. This then becomes a question of what
1624     // subregisters in the destination register line up with positions in the
1625     // stack slot.
1626 
1627     // Def all registers that alias the destination.
1628     for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1629       MTracker->defReg(*RAI, CurBB, CurInst);
1630 
1631     // Now find subregisters within the destination register, and load values
1632     // from stack slot positions.
1633     auto DoTransfer = [&](Register DestReg, unsigned SpillID) {
1634       LocIdx SrcIdx = MTracker->getSpillMLoc(SpillID);
1635       auto ReadValue = MTracker->readMLoc(SrcIdx);
1636       MTracker->setReg(DestReg, ReadValue);
1637     };
1638 
1639     for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) {
1640       unsigned Subreg = TRI->getSubRegIndex(Reg, *SRI);
1641       unsigned SpillID = MTracker->getLocID(*Loc, Subreg);
1642       DoTransfer(*SRI, SpillID);
1643     }
1644 
1645     // Directly look up this registers slot idx by size, and transfer.
1646     unsigned Size = TRI->getRegSizeInBits(Reg, *MRI);
1647     unsigned SpillID = MTracker->getLocID(*Loc, {Size, 0});
1648     DoTransfer(Reg, SpillID);
1649   }
1650   return true;
1651 }
1652 
1653 bool InstrRefBasedLDV::transferRegisterCopy(MachineInstr &MI) {
1654   auto DestSrc = TII->isCopyInstr(MI);
1655   if (!DestSrc)
1656     return false;
1657 
1658   const MachineOperand *DestRegOp = DestSrc->Destination;
1659   const MachineOperand *SrcRegOp = DestSrc->Source;
1660 
1661   auto isCalleeSavedReg = [&](unsigned Reg) {
1662     for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1663       if (CalleeSavedRegs.test(*RAI))
1664         return true;
1665     return false;
1666   };
1667 
1668   Register SrcReg = SrcRegOp->getReg();
1669   Register DestReg = DestRegOp->getReg();
1670 
1671   // Ignore identity copies. Yep, these make it as far as LiveDebugValues.
1672   if (SrcReg == DestReg)
1673     return true;
1674 
1675   // For emulating VarLocBasedImpl:
1676   // We want to recognize instructions where destination register is callee
1677   // saved register. If register that could be clobbered by the call is
1678   // included, there would be a great chance that it is going to be clobbered
1679   // soon. It is more likely that previous register, which is callee saved, is
1680   // going to stay unclobbered longer, even if it is killed.
1681   //
1682   // For InstrRefBasedImpl, we can track multiple locations per value, so
1683   // ignore this condition.
1684   if (EmulateOldLDV && !isCalleeSavedReg(DestReg))
1685     return false;
1686 
1687   // InstrRefBasedImpl only followed killing copies.
1688   if (EmulateOldLDV && !SrcRegOp->isKill())
1689     return false;
1690 
1691   // Copy MTracker info, including subregs if available.
1692   InstrRefBasedLDV::performCopy(SrcReg, DestReg);
1693 
1694   // Only produce a transfer of DBG_VALUE within a block where old LDV
1695   // would have. We might make use of the additional value tracking in some
1696   // other way, later.
1697   if (TTracker && isCalleeSavedReg(DestReg) && SrcRegOp->isKill())
1698     TTracker->transferMlocs(MTracker->getRegMLoc(SrcReg),
1699                             MTracker->getRegMLoc(DestReg), MI.getIterator());
1700 
1701   // VarLocBasedImpl would quit tracking the old location after copying.
1702   if (EmulateOldLDV && SrcReg != DestReg)
1703     MTracker->defReg(SrcReg, CurBB, CurInst);
1704 
1705   // Finally, the copy might have clobbered variables based on the destination
1706   // register. Tell TTracker about it, in case a backup location exists.
1707   if (TTracker) {
1708     for (MCRegAliasIterator RAI(DestReg, TRI, true); RAI.isValid(); ++RAI) {
1709       LocIdx ClobberedLoc = MTracker->getRegMLoc(*RAI);
1710       TTracker->clobberMloc(ClobberedLoc, MI.getIterator(), false);
1711     }
1712   }
1713 
1714   return true;
1715 }
1716 
1717 /// Accumulate a mapping between each DILocalVariable fragment and other
1718 /// fragments of that DILocalVariable which overlap. This reduces work during
1719 /// the data-flow stage from "Find any overlapping fragments" to "Check if the
1720 /// known-to-overlap fragments are present".
1721 /// \param MI A previously unprocessed debug instruction to analyze for
1722 ///           fragment usage.
1723 void InstrRefBasedLDV::accumulateFragmentMap(MachineInstr &MI) {
1724   assert(MI.isDebugValue() || MI.isDebugRef());
1725   DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(),
1726                       MI.getDebugLoc()->getInlinedAt());
1727   FragmentInfo ThisFragment = MIVar.getFragmentOrDefault();
1728 
1729   // If this is the first sighting of this variable, then we are guaranteed
1730   // there are currently no overlapping fragments either. Initialize the set
1731   // of seen fragments, record no overlaps for the current one, and return.
1732   auto SeenIt = SeenFragments.find(MIVar.getVariable());
1733   if (SeenIt == SeenFragments.end()) {
1734     SmallSet<FragmentInfo, 4> OneFragment;
1735     OneFragment.insert(ThisFragment);
1736     SeenFragments.insert({MIVar.getVariable(), OneFragment});
1737 
1738     OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
1739     return;
1740   }
1741 
1742   // If this particular Variable/Fragment pair already exists in the overlap
1743   // map, it has already been accounted for.
1744   auto IsInOLapMap =
1745       OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
1746   if (!IsInOLapMap.second)
1747     return;
1748 
1749   auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
1750   auto &AllSeenFragments = SeenIt->second;
1751 
1752   // Otherwise, examine all other seen fragments for this variable, with "this"
1753   // fragment being a previously unseen fragment. Record any pair of
1754   // overlapping fragments.
1755   for (auto &ASeenFragment : AllSeenFragments) {
1756     // Does this previously seen fragment overlap?
1757     if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
1758       // Yes: Mark the current fragment as being overlapped.
1759       ThisFragmentsOverlaps.push_back(ASeenFragment);
1760       // Mark the previously seen fragment as being overlapped by the current
1761       // one.
1762       auto ASeenFragmentsOverlaps =
1763           OverlapFragments.find({MIVar.getVariable(), ASeenFragment});
1764       assert(ASeenFragmentsOverlaps != OverlapFragments.end() &&
1765              "Previously seen var fragment has no vector of overlaps");
1766       ASeenFragmentsOverlaps->second.push_back(ThisFragment);
1767     }
1768   }
1769 
1770   AllSeenFragments.insert(ThisFragment);
1771 }
1772 
1773 void InstrRefBasedLDV::process(MachineInstr &MI, const ValueTable *MLiveOuts,
1774                                const ValueTable *MLiveIns) {
1775   // Try to interpret an MI as a debug or transfer instruction. Only if it's
1776   // none of these should we interpret it's register defs as new value
1777   // definitions.
1778   if (transferDebugValue(MI))
1779     return;
1780   if (transferDebugInstrRef(MI, MLiveOuts, MLiveIns))
1781     return;
1782   if (transferDebugPHI(MI))
1783     return;
1784   if (transferRegisterCopy(MI))
1785     return;
1786   if (transferSpillOrRestoreInst(MI))
1787     return;
1788   transferRegisterDef(MI);
1789 }
1790 
1791 void InstrRefBasedLDV::produceMLocTransferFunction(
1792     MachineFunction &MF, SmallVectorImpl<MLocTransferMap> &MLocTransfer,
1793     unsigned MaxNumBlocks) {
1794   // Because we try to optimize around register mask operands by ignoring regs
1795   // that aren't currently tracked, we set up something ugly for later: RegMask
1796   // operands that are seen earlier than the first use of a register, still need
1797   // to clobber that register in the transfer function. But this information
1798   // isn't actively recorded. Instead, we track each RegMask used in each block,
1799   // and accumulated the clobbered but untracked registers in each block into
1800   // the following bitvector. Later, if new values are tracked, we can add
1801   // appropriate clobbers.
1802   SmallVector<BitVector, 32> BlockMasks;
1803   BlockMasks.resize(MaxNumBlocks);
1804 
1805   // Reserve one bit per register for the masks described above.
1806   unsigned BVWords = MachineOperand::getRegMaskSize(TRI->getNumRegs());
1807   for (auto &BV : BlockMasks)
1808     BV.resize(TRI->getNumRegs(), true);
1809 
1810   // Step through all instructions and inhale the transfer function.
1811   for (auto &MBB : MF) {
1812     // Object fields that are read by trackers to know where we are in the
1813     // function.
1814     CurBB = MBB.getNumber();
1815     CurInst = 1;
1816 
1817     // Set all machine locations to a PHI value. For transfer function
1818     // production only, this signifies the live-in value to the block.
1819     MTracker->reset();
1820     MTracker->setMPhis(CurBB);
1821 
1822     // Step through each instruction in this block.
1823     for (auto &MI : MBB) {
1824       // Pass in an empty unique_ptr for the value tables when accumulating the
1825       // machine transfer function.
1826       process(MI, nullptr, nullptr);
1827 
1828       // Also accumulate fragment map.
1829       if (MI.isDebugValue() || MI.isDebugRef())
1830         accumulateFragmentMap(MI);
1831 
1832       // Create a map from the instruction number (if present) to the
1833       // MachineInstr and its position.
1834       if (uint64_t InstrNo = MI.peekDebugInstrNum()) {
1835         auto InstrAndPos = std::make_pair(&MI, CurInst);
1836         auto InsertResult =
1837             DebugInstrNumToInstr.insert(std::make_pair(InstrNo, InstrAndPos));
1838 
1839         // There should never be duplicate instruction numbers.
1840         assert(InsertResult.second);
1841         (void)InsertResult;
1842       }
1843 
1844       ++CurInst;
1845     }
1846 
1847     // Produce the transfer function, a map of machine location to new value. If
1848     // any machine location has the live-in phi value from the start of the
1849     // block, it's live-through and doesn't need recording in the transfer
1850     // function.
1851     for (auto Location : MTracker->locations()) {
1852       LocIdx Idx = Location.Idx;
1853       ValueIDNum &P = Location.Value;
1854       if (P.isPHI() && P.getLoc() == Idx.asU64())
1855         continue;
1856 
1857       // Insert-or-update.
1858       auto &TransferMap = MLocTransfer[CurBB];
1859       auto Result = TransferMap.insert(std::make_pair(Idx.asU64(), P));
1860       if (!Result.second)
1861         Result.first->second = P;
1862     }
1863 
1864     // Accumulate any bitmask operands into the clobberred reg mask for this
1865     // block.
1866     for (auto &P : MTracker->Masks) {
1867       BlockMasks[CurBB].clearBitsNotInMask(P.first->getRegMask(), BVWords);
1868     }
1869   }
1870 
1871   // Compute a bitvector of all the registers that are tracked in this block.
1872   BitVector UsedRegs(TRI->getNumRegs());
1873   for (auto Location : MTracker->locations()) {
1874     unsigned ID = MTracker->LocIdxToLocID[Location.Idx];
1875     // Ignore stack slots, and aliases of the stack pointer.
1876     if (ID >= TRI->getNumRegs() || MTracker->SPAliases.count(ID))
1877       continue;
1878     UsedRegs.set(ID);
1879   }
1880 
1881   // Check that any regmask-clobber of a register that gets tracked, is not
1882   // live-through in the transfer function. It needs to be clobbered at the
1883   // very least.
1884   for (unsigned int I = 0; I < MaxNumBlocks; ++I) {
1885     BitVector &BV = BlockMasks[I];
1886     BV.flip();
1887     BV &= UsedRegs;
1888     // This produces all the bits that we clobber, but also use. Check that
1889     // they're all clobbered or at least set in the designated transfer
1890     // elem.
1891     for (unsigned Bit : BV.set_bits()) {
1892       unsigned ID = MTracker->getLocID(Bit);
1893       LocIdx Idx = MTracker->LocIDToLocIdx[ID];
1894       auto &TransferMap = MLocTransfer[I];
1895 
1896       // Install a value representing the fact that this location is effectively
1897       // written to in this block. As there's no reserved value, instead use
1898       // a value number that is never generated. Pick the value number for the
1899       // first instruction in the block, def'ing this location, which we know
1900       // this block never used anyway.
1901       ValueIDNum NotGeneratedNum = ValueIDNum(I, 1, Idx);
1902       auto Result =
1903         TransferMap.insert(std::make_pair(Idx.asU64(), NotGeneratedNum));
1904       if (!Result.second) {
1905         ValueIDNum &ValueID = Result.first->second;
1906         if (ValueID.getBlock() == I && ValueID.isPHI())
1907           // It was left as live-through. Set it to clobbered.
1908           ValueID = NotGeneratedNum;
1909       }
1910     }
1911   }
1912 }
1913 
1914 bool InstrRefBasedLDV::mlocJoin(
1915     MachineBasicBlock &MBB, SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
1916     FuncValueTable &OutLocs, ValueTable &InLocs) {
1917   LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
1918   bool Changed = false;
1919 
1920   // Handle value-propagation when control flow merges on entry to a block. For
1921   // any location without a PHI already placed, the location has the same value
1922   // as its predecessors. If a PHI is placed, test to see whether it's now a
1923   // redundant PHI that we can eliminate.
1924 
1925   SmallVector<const MachineBasicBlock *, 8> BlockOrders;
1926   for (auto Pred : MBB.predecessors())
1927     BlockOrders.push_back(Pred);
1928 
1929   // Visit predecessors in RPOT order.
1930   auto Cmp = [&](const MachineBasicBlock *A, const MachineBasicBlock *B) {
1931     return BBToOrder.find(A)->second < BBToOrder.find(B)->second;
1932   };
1933   llvm::sort(BlockOrders, Cmp);
1934 
1935   // Skip entry block.
1936   if (BlockOrders.size() == 0)
1937     return false;
1938 
1939   // Step through all machine locations, look at each predecessor and test
1940   // whether we can eliminate redundant PHIs.
1941   for (auto Location : MTracker->locations()) {
1942     LocIdx Idx = Location.Idx;
1943 
1944     // Pick out the first predecessors live-out value for this location. It's
1945     // guaranteed to not be a backedge, as we order by RPO.
1946     ValueIDNum FirstVal = OutLocs[BlockOrders[0]->getNumber()][Idx.asU64()];
1947 
1948     // If we've already eliminated a PHI here, do no further checking, just
1949     // propagate the first live-in value into this block.
1950     if (InLocs[Idx.asU64()] != ValueIDNum(MBB.getNumber(), 0, Idx)) {
1951       if (InLocs[Idx.asU64()] != FirstVal) {
1952         InLocs[Idx.asU64()] = FirstVal;
1953         Changed |= true;
1954       }
1955       continue;
1956     }
1957 
1958     // We're now examining a PHI to see whether it's un-necessary. Loop around
1959     // the other live-in values and test whether they're all the same.
1960     bool Disagree = false;
1961     for (unsigned int I = 1; I < BlockOrders.size(); ++I) {
1962       const MachineBasicBlock *PredMBB = BlockOrders[I];
1963       const ValueIDNum &PredLiveOut =
1964           OutLocs[PredMBB->getNumber()][Idx.asU64()];
1965 
1966       // Incoming values agree, continue trying to eliminate this PHI.
1967       if (FirstVal == PredLiveOut)
1968         continue;
1969 
1970       // We can also accept a PHI value that feeds back into itself.
1971       if (PredLiveOut == ValueIDNum(MBB.getNumber(), 0, Idx))
1972         continue;
1973 
1974       // Live-out of a predecessor disagrees with the first predecessor.
1975       Disagree = true;
1976     }
1977 
1978     // No disagreement? No PHI. Otherwise, leave the PHI in live-ins.
1979     if (!Disagree) {
1980       InLocs[Idx.asU64()] = FirstVal;
1981       Changed |= true;
1982     }
1983   }
1984 
1985   // TODO: Reimplement NumInserted and NumRemoved.
1986   return Changed;
1987 }
1988 
1989 void InstrRefBasedLDV::findStackIndexInterference(
1990     SmallVectorImpl<unsigned> &Slots) {
1991   // We could spend a bit of time finding the exact, minimal, set of stack
1992   // indexes that interfere with each other, much like reg units. Or, we can
1993   // rely on the fact that:
1994   //  * The smallest / lowest index will interfere with everything at zero
1995   //    offset, which will be the largest set of registers,
1996   //  * Most indexes with non-zero offset will end up being interference units
1997   //    anyway.
1998   // So just pick those out and return them.
1999 
2000   // We can rely on a single-byte stack index existing already, because we
2001   // initialize them in MLocTracker.
2002   auto It = MTracker->StackSlotIdxes.find({8, 0});
2003   assert(It != MTracker->StackSlotIdxes.end());
2004   Slots.push_back(It->second);
2005 
2006   // Find anything that has a non-zero offset and add that too.
2007   for (auto &Pair : MTracker->StackSlotIdxes) {
2008     // Is offset zero? If so, ignore.
2009     if (!Pair.first.second)
2010       continue;
2011     Slots.push_back(Pair.second);
2012   }
2013 }
2014 
2015 void InstrRefBasedLDV::placeMLocPHIs(
2016     MachineFunction &MF, SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
2017     FuncValueTable &MInLocs, SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
2018   SmallVector<unsigned, 4> StackUnits;
2019   findStackIndexInterference(StackUnits);
2020 
2021   // To avoid repeatedly running the PHI placement algorithm, leverage the
2022   // fact that a def of register MUST also def its register units. Find the
2023   // units for registers, place PHIs for them, and then replicate them for
2024   // aliasing registers. Some inputs that are never def'd (DBG_PHIs of
2025   // arguments) don't lead to register units being tracked, just place PHIs for
2026   // those registers directly. Stack slots have their own form of "unit",
2027   // store them to one side.
2028   SmallSet<Register, 32> RegUnitsToPHIUp;
2029   SmallSet<LocIdx, 32> NormalLocsToPHI;
2030   SmallSet<SpillLocationNo, 32> StackSlots;
2031   for (auto Location : MTracker->locations()) {
2032     LocIdx L = Location.Idx;
2033     if (MTracker->isSpill(L)) {
2034       StackSlots.insert(MTracker->locIDToSpill(MTracker->LocIdxToLocID[L]));
2035       continue;
2036     }
2037 
2038     Register R = MTracker->LocIdxToLocID[L];
2039     SmallSet<Register, 8> FoundRegUnits;
2040     bool AnyIllegal = false;
2041     for (MCRegUnitIterator RUI(R.asMCReg(), TRI); RUI.isValid(); ++RUI) {
2042       for (MCRegUnitRootIterator URoot(*RUI, TRI); URoot.isValid(); ++URoot){
2043         if (!MTracker->isRegisterTracked(*URoot)) {
2044           // Not all roots were loaded into the tracking map: this register
2045           // isn't actually def'd anywhere, we only read from it. Generate PHIs
2046           // for this reg, but don't iterate units.
2047           AnyIllegal = true;
2048         } else {
2049           FoundRegUnits.insert(*URoot);
2050         }
2051       }
2052     }
2053 
2054     if (AnyIllegal) {
2055       NormalLocsToPHI.insert(L);
2056       continue;
2057     }
2058 
2059     RegUnitsToPHIUp.insert(FoundRegUnits.begin(), FoundRegUnits.end());
2060   }
2061 
2062   // Lambda to fetch PHIs for a given location, and write into the PHIBlocks
2063   // collection.
2064   SmallVector<MachineBasicBlock *, 32> PHIBlocks;
2065   auto CollectPHIsForLoc = [&](LocIdx L) {
2066     // Collect the set of defs.
2067     SmallPtrSet<MachineBasicBlock *, 32> DefBlocks;
2068     for (unsigned int I = 0; I < OrderToBB.size(); ++I) {
2069       MachineBasicBlock *MBB = OrderToBB[I];
2070       const auto &TransferFunc = MLocTransfer[MBB->getNumber()];
2071       if (TransferFunc.find(L) != TransferFunc.end())
2072         DefBlocks.insert(MBB);
2073     }
2074 
2075     // The entry block defs the location too: it's the live-in / argument value.
2076     // Only insert if there are other defs though; everything is trivially live
2077     // through otherwise.
2078     if (!DefBlocks.empty())
2079       DefBlocks.insert(&*MF.begin());
2080 
2081     // Ask the SSA construction algorithm where we should put PHIs. Clear
2082     // anything that might have been hanging around from earlier.
2083     PHIBlocks.clear();
2084     BlockPHIPlacement(AllBlocks, DefBlocks, PHIBlocks);
2085   };
2086 
2087   auto InstallPHIsAtLoc = [&PHIBlocks, &MInLocs](LocIdx L) {
2088     for (const MachineBasicBlock *MBB : PHIBlocks)
2089       MInLocs[MBB->getNumber()][L.asU64()] = ValueIDNum(MBB->getNumber(), 0, L);
2090   };
2091 
2092   // For locations with no reg units, just place PHIs.
2093   for (LocIdx L : NormalLocsToPHI) {
2094     CollectPHIsForLoc(L);
2095     // Install those PHI values into the live-in value array.
2096     InstallPHIsAtLoc(L);
2097   }
2098 
2099   // For stack slots, calculate PHIs for the equivalent of the units, then
2100   // install for each index.
2101   for (SpillLocationNo Slot : StackSlots) {
2102     for (unsigned Idx : StackUnits) {
2103       unsigned SpillID = MTracker->getSpillIDWithIdx(Slot, Idx);
2104       LocIdx L = MTracker->getSpillMLoc(SpillID);
2105       CollectPHIsForLoc(L);
2106       InstallPHIsAtLoc(L);
2107 
2108       // Find anything that aliases this stack index, install PHIs for it too.
2109       unsigned Size, Offset;
2110       std::tie(Size, Offset) = MTracker->StackIdxesToPos[Idx];
2111       for (auto &Pair : MTracker->StackSlotIdxes) {
2112         unsigned ThisSize, ThisOffset;
2113         std::tie(ThisSize, ThisOffset) = Pair.first;
2114         if (ThisSize + ThisOffset <= Offset || Size + Offset <= ThisOffset)
2115           continue;
2116 
2117         unsigned ThisID = MTracker->getSpillIDWithIdx(Slot, Pair.second);
2118         LocIdx ThisL = MTracker->getSpillMLoc(ThisID);
2119         InstallPHIsAtLoc(ThisL);
2120       }
2121     }
2122   }
2123 
2124   // For reg units, place PHIs, and then place them for any aliasing registers.
2125   for (Register R : RegUnitsToPHIUp) {
2126     LocIdx L = MTracker->lookupOrTrackRegister(R);
2127     CollectPHIsForLoc(L);
2128 
2129     // Install those PHI values into the live-in value array.
2130     InstallPHIsAtLoc(L);
2131 
2132     // Now find aliases and install PHIs for those.
2133     for (MCRegAliasIterator RAI(R, TRI, true); RAI.isValid(); ++RAI) {
2134       // Super-registers that are "above" the largest register read/written by
2135       // the function will alias, but will not be tracked.
2136       if (!MTracker->isRegisterTracked(*RAI))
2137         continue;
2138 
2139       LocIdx AliasLoc = MTracker->lookupOrTrackRegister(*RAI);
2140       InstallPHIsAtLoc(AliasLoc);
2141     }
2142   }
2143 }
2144 
2145 void InstrRefBasedLDV::buildMLocValueMap(
2146     MachineFunction &MF, FuncValueTable &MInLocs, FuncValueTable &MOutLocs,
2147     SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
2148   std::priority_queue<unsigned int, std::vector<unsigned int>,
2149                       std::greater<unsigned int>>
2150       Worklist, Pending;
2151 
2152   // We track what is on the current and pending worklist to avoid inserting
2153   // the same thing twice. We could avoid this with a custom priority queue,
2154   // but this is probably not worth it.
2155   SmallPtrSet<MachineBasicBlock *, 16> OnPending, OnWorklist;
2156 
2157   // Initialize worklist with every block to be visited. Also produce list of
2158   // all blocks.
2159   SmallPtrSet<MachineBasicBlock *, 32> AllBlocks;
2160   for (unsigned int I = 0; I < BBToOrder.size(); ++I) {
2161     Worklist.push(I);
2162     OnWorklist.insert(OrderToBB[I]);
2163     AllBlocks.insert(OrderToBB[I]);
2164   }
2165 
2166   // Initialize entry block to PHIs. These represent arguments.
2167   for (auto Location : MTracker->locations())
2168     MInLocs[0][Location.Idx.asU64()] = ValueIDNum(0, 0, Location.Idx);
2169 
2170   MTracker->reset();
2171 
2172   // Start by placing PHIs, using the usual SSA constructor algorithm. Consider
2173   // any machine-location that isn't live-through a block to be def'd in that
2174   // block.
2175   placeMLocPHIs(MF, AllBlocks, MInLocs, MLocTransfer);
2176 
2177   // Propagate values to eliminate redundant PHIs. At the same time, this
2178   // produces the table of Block x Location => Value for the entry to each
2179   // block.
2180   // The kind of PHIs we can eliminate are, for example, where one path in a
2181   // conditional spills and restores a register, and the register still has
2182   // the same value once control flow joins, unbeknowns to the PHI placement
2183   // code. Propagating values allows us to identify such un-necessary PHIs and
2184   // remove them.
2185   SmallPtrSet<const MachineBasicBlock *, 16> Visited;
2186   while (!Worklist.empty() || !Pending.empty()) {
2187     // Vector for storing the evaluated block transfer function.
2188     SmallVector<std::pair<LocIdx, ValueIDNum>, 32> ToRemap;
2189 
2190     while (!Worklist.empty()) {
2191       MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
2192       CurBB = MBB->getNumber();
2193       Worklist.pop();
2194 
2195       // Join the values in all predecessor blocks.
2196       bool InLocsChanged;
2197       InLocsChanged = mlocJoin(*MBB, Visited, MOutLocs, MInLocs[CurBB]);
2198       InLocsChanged |= Visited.insert(MBB).second;
2199 
2200       // Don't examine transfer function if we've visited this loc at least
2201       // once, and inlocs haven't changed.
2202       if (!InLocsChanged)
2203         continue;
2204 
2205       // Load the current set of live-ins into MLocTracker.
2206       MTracker->loadFromArray(MInLocs[CurBB], CurBB);
2207 
2208       // Each element of the transfer function can be a new def, or a read of
2209       // a live-in value. Evaluate each element, and store to "ToRemap".
2210       ToRemap.clear();
2211       for (auto &P : MLocTransfer[CurBB]) {
2212         if (P.second.getBlock() == CurBB && P.second.isPHI()) {
2213           // This is a movement of whatever was live in. Read it.
2214           ValueIDNum NewID = MTracker->readMLoc(P.second.getLoc());
2215           ToRemap.push_back(std::make_pair(P.first, NewID));
2216         } else {
2217           // It's a def. Just set it.
2218           assert(P.second.getBlock() == CurBB);
2219           ToRemap.push_back(std::make_pair(P.first, P.second));
2220         }
2221       }
2222 
2223       // Commit the transfer function changes into mloc tracker, which
2224       // transforms the contents of the MLocTracker into the live-outs.
2225       for (auto &P : ToRemap)
2226         MTracker->setMLoc(P.first, P.second);
2227 
2228       // Now copy out-locs from mloc tracker into out-loc vector, checking
2229       // whether changes have occurred. These changes can have come from both
2230       // the transfer function, and mlocJoin.
2231       bool OLChanged = false;
2232       for (auto Location : MTracker->locations()) {
2233         OLChanged |= MOutLocs[CurBB][Location.Idx.asU64()] != Location.Value;
2234         MOutLocs[CurBB][Location.Idx.asU64()] = Location.Value;
2235       }
2236 
2237       MTracker->reset();
2238 
2239       // No need to examine successors again if out-locs didn't change.
2240       if (!OLChanged)
2241         continue;
2242 
2243       // All successors should be visited: put any back-edges on the pending
2244       // list for the next pass-through, and any other successors to be
2245       // visited this pass, if they're not going to be already.
2246       for (auto s : MBB->successors()) {
2247         // Does branching to this successor represent a back-edge?
2248         if (BBToOrder[s] > BBToOrder[MBB]) {
2249           // No: visit it during this dataflow iteration.
2250           if (OnWorklist.insert(s).second)
2251             Worklist.push(BBToOrder[s]);
2252         } else {
2253           // Yes: visit it on the next iteration.
2254           if (OnPending.insert(s).second)
2255             Pending.push(BBToOrder[s]);
2256         }
2257       }
2258     }
2259 
2260     Worklist.swap(Pending);
2261     std::swap(OnPending, OnWorklist);
2262     OnPending.clear();
2263     // At this point, pending must be empty, since it was just the empty
2264     // worklist
2265     assert(Pending.empty() && "Pending should be empty");
2266   }
2267 
2268   // Once all the live-ins don't change on mlocJoin(), we've eliminated all
2269   // redundant PHIs.
2270 }
2271 
2272 void InstrRefBasedLDV::BlockPHIPlacement(
2273     const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
2274     const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks,
2275     SmallVectorImpl<MachineBasicBlock *> &PHIBlocks) {
2276   // Apply IDF calculator to the designated set of location defs, storing
2277   // required PHIs into PHIBlocks. Uses the dominator tree stored in the
2278   // InstrRefBasedLDV object.
2279   IDFCalculatorBase<MachineBasicBlock, false> IDF(DomTree->getBase());
2280 
2281   IDF.setLiveInBlocks(AllBlocks);
2282   IDF.setDefiningBlocks(DefBlocks);
2283   IDF.calculate(PHIBlocks);
2284 }
2285 
2286 Optional<ValueIDNum> InstrRefBasedLDV::pickVPHILoc(
2287     const MachineBasicBlock &MBB, const DebugVariable &Var,
2288     const LiveIdxT &LiveOuts, FuncValueTable &MOutLocs,
2289     const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) {
2290   // Collect a set of locations from predecessor where its live-out value can
2291   // be found.
2292   SmallVector<SmallVector<LocIdx, 4>, 8> Locs;
2293   SmallVector<const DbgValueProperties *, 4> Properties;
2294   unsigned NumLocs = MTracker->getNumLocs();
2295 
2296   // No predecessors means no PHIs.
2297   if (BlockOrders.empty())
2298     return None;
2299 
2300   for (auto p : BlockOrders) {
2301     unsigned ThisBBNum = p->getNumber();
2302     auto OutValIt = LiveOuts.find(p);
2303     if (OutValIt == LiveOuts.end())
2304       // If we have a predecessor not in scope, we'll never find a PHI position.
2305       return None;
2306     const DbgValue &OutVal = *OutValIt->second;
2307 
2308     if (OutVal.Kind == DbgValue::Const || OutVal.Kind == DbgValue::NoVal)
2309       // Consts and no-values cannot have locations we can join on.
2310       return None;
2311 
2312     Properties.push_back(&OutVal.Properties);
2313 
2314     // Create new empty vector of locations.
2315     Locs.resize(Locs.size() + 1);
2316 
2317     // If the live-in value is a def, find the locations where that value is
2318     // present. Do the same for VPHIs where we know the VPHI value.
2319     if (OutVal.Kind == DbgValue::Def ||
2320         (OutVal.Kind == DbgValue::VPHI && OutVal.BlockNo != MBB.getNumber() &&
2321          OutVal.ID != ValueIDNum::EmptyValue)) {
2322       ValueIDNum ValToLookFor = OutVal.ID;
2323       // Search the live-outs of the predecessor for the specified value.
2324       for (unsigned int I = 0; I < NumLocs; ++I) {
2325         if (MOutLocs[ThisBBNum][I] == ValToLookFor)
2326           Locs.back().push_back(LocIdx(I));
2327       }
2328     } else {
2329       assert(OutVal.Kind == DbgValue::VPHI);
2330       // For VPHIs where we don't know the location, we definitely can't find
2331       // a join loc.
2332       if (OutVal.BlockNo != MBB.getNumber())
2333         return None;
2334 
2335       // Otherwise: this is a VPHI on a backedge feeding back into itself, i.e.
2336       // a value that's live-through the whole loop. (It has to be a backedge,
2337       // because a block can't dominate itself). We can accept as a PHI location
2338       // any location where the other predecessors agree, _and_ the machine
2339       // locations feed back into themselves. Therefore, add all self-looping
2340       // machine-value PHI locations.
2341       for (unsigned int I = 0; I < NumLocs; ++I) {
2342         ValueIDNum MPHI(MBB.getNumber(), 0, LocIdx(I));
2343         if (MOutLocs[ThisBBNum][I] == MPHI)
2344           Locs.back().push_back(LocIdx(I));
2345       }
2346     }
2347   }
2348 
2349   // We should have found locations for all predecessors, or returned.
2350   assert(Locs.size() == BlockOrders.size());
2351 
2352   // Check that all properties are the same. We can't pick a location if they're
2353   // not.
2354   const DbgValueProperties *Properties0 = Properties[0];
2355   for (auto *Prop : Properties)
2356     if (*Prop != *Properties0)
2357       return None;
2358 
2359   // Starting with the first set of locations, take the intersection with
2360   // subsequent sets.
2361   SmallVector<LocIdx, 4> CandidateLocs = Locs[0];
2362   for (unsigned int I = 1; I < Locs.size(); ++I) {
2363     auto &LocVec = Locs[I];
2364     SmallVector<LocIdx, 4> NewCandidates;
2365     std::set_intersection(CandidateLocs.begin(), CandidateLocs.end(),
2366                           LocVec.begin(), LocVec.end(), std::inserter(NewCandidates, NewCandidates.begin()));
2367     CandidateLocs = NewCandidates;
2368   }
2369   if (CandidateLocs.empty())
2370     return None;
2371 
2372   // We now have a set of LocIdxes that contain the right output value in
2373   // each of the predecessors. Pick the lowest; if there's a register loc,
2374   // that'll be it.
2375   LocIdx L = *CandidateLocs.begin();
2376 
2377   // Return a PHI-value-number for the found location.
2378   ValueIDNum PHIVal = {(unsigned)MBB.getNumber(), 0, L};
2379   return PHIVal;
2380 }
2381 
2382 bool InstrRefBasedLDV::vlocJoin(
2383     MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs,
2384     SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
2385     DbgValue &LiveIn) {
2386   LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
2387   bool Changed = false;
2388 
2389   // Order predecessors by RPOT order, for exploring them in that order.
2390   SmallVector<MachineBasicBlock *, 8> BlockOrders(MBB.predecessors());
2391 
2392   auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
2393     return BBToOrder[A] < BBToOrder[B];
2394   };
2395 
2396   llvm::sort(BlockOrders, Cmp);
2397 
2398   unsigned CurBlockRPONum = BBToOrder[&MBB];
2399 
2400   // Collect all the incoming DbgValues for this variable, from predecessor
2401   // live-out values.
2402   SmallVector<InValueT, 8> Values;
2403   bool Bail = false;
2404   int BackEdgesStart = 0;
2405   for (auto p : BlockOrders) {
2406     // If the predecessor isn't in scope / to be explored, we'll never be
2407     // able to join any locations.
2408     if (!BlocksToExplore.contains(p)) {
2409       Bail = true;
2410       break;
2411     }
2412 
2413     // All Live-outs will have been initialized.
2414     DbgValue &OutLoc = *VLOCOutLocs.find(p)->second;
2415 
2416     // Keep track of where back-edges begin in the Values vector. Relies on
2417     // BlockOrders being sorted by RPO.
2418     unsigned ThisBBRPONum = BBToOrder[p];
2419     if (ThisBBRPONum < CurBlockRPONum)
2420       ++BackEdgesStart;
2421 
2422     Values.push_back(std::make_pair(p, &OutLoc));
2423   }
2424 
2425   // If there were no values, or one of the predecessors couldn't have a
2426   // value, then give up immediately. It's not safe to produce a live-in
2427   // value. Leave as whatever it was before.
2428   if (Bail || Values.size() == 0)
2429     return false;
2430 
2431   // All (non-entry) blocks have at least one non-backedge predecessor.
2432   // Pick the variable value from the first of these, to compare against
2433   // all others.
2434   const DbgValue &FirstVal = *Values[0].second;
2435 
2436   // If the old live-in value is not a PHI then either a) no PHI is needed
2437   // here, or b) we eliminated the PHI that was here. If so, we can just
2438   // propagate in the first parent's incoming value.
2439   if (LiveIn.Kind != DbgValue::VPHI || LiveIn.BlockNo != MBB.getNumber()) {
2440     Changed = LiveIn != FirstVal;
2441     if (Changed)
2442       LiveIn = FirstVal;
2443     return Changed;
2444   }
2445 
2446   // Scan for variable values that can never be resolved: if they have
2447   // different DIExpressions, different indirectness, or are mixed constants /
2448   // non-constants.
2449   for (auto &V : Values) {
2450     if (V.second->Properties != FirstVal.Properties)
2451       return false;
2452     if (V.second->Kind == DbgValue::NoVal)
2453       return false;
2454     if (V.second->Kind == DbgValue::Const && FirstVal.Kind != DbgValue::Const)
2455       return false;
2456   }
2457 
2458   // Try to eliminate this PHI. Do the incoming values all agree?
2459   bool Disagree = false;
2460   for (auto &V : Values) {
2461     if (*V.second == FirstVal)
2462       continue; // No disagreement.
2463 
2464     // Eliminate if a backedge feeds a VPHI back into itself.
2465     if (V.second->Kind == DbgValue::VPHI &&
2466         V.second->BlockNo == MBB.getNumber() &&
2467         // Is this a backedge?
2468         std::distance(Values.begin(), &V) >= BackEdgesStart)
2469       continue;
2470 
2471     Disagree = true;
2472   }
2473 
2474   // No disagreement -> live-through value.
2475   if (!Disagree) {
2476     Changed = LiveIn != FirstVal;
2477     if (Changed)
2478       LiveIn = FirstVal;
2479     return Changed;
2480   } else {
2481     // Otherwise use a VPHI.
2482     DbgValue VPHI(MBB.getNumber(), FirstVal.Properties, DbgValue::VPHI);
2483     Changed = LiveIn != VPHI;
2484     if (Changed)
2485       LiveIn = VPHI;
2486     return Changed;
2487   }
2488 }
2489 
2490 void InstrRefBasedLDV::getBlocksForScope(
2491     const DILocation *DILoc,
2492     SmallPtrSetImpl<const MachineBasicBlock *> &BlocksToExplore,
2493     const SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks) {
2494   // Get the set of "normal" in-lexical-scope blocks.
2495   LS.getMachineBasicBlocks(DILoc, BlocksToExplore);
2496 
2497   // VarLoc LiveDebugValues tracks variable locations that are defined in
2498   // blocks not in scope. This is something we could legitimately ignore, but
2499   // lets allow it for now for the sake of coverage.
2500   BlocksToExplore.insert(AssignBlocks.begin(), AssignBlocks.end());
2501 
2502   // Storage for artificial blocks we intend to add to BlocksToExplore.
2503   DenseSet<const MachineBasicBlock *> ToAdd;
2504 
2505   // To avoid needlessly dropping large volumes of variable locations, propagate
2506   // variables through aritifical blocks, i.e. those that don't have any
2507   // instructions in scope at all. To accurately replicate VarLoc
2508   // LiveDebugValues, this means exploring all artificial successors too.
2509   // Perform a depth-first-search to enumerate those blocks.
2510   for (auto *MBB : BlocksToExplore) {
2511     // Depth-first-search state: each node is a block and which successor
2512     // we're currently exploring.
2513     SmallVector<std::pair<const MachineBasicBlock *,
2514                           MachineBasicBlock::const_succ_iterator>,
2515                 8>
2516         DFS;
2517 
2518     // Find any artificial successors not already tracked.
2519     for (auto *succ : MBB->successors()) {
2520       if (BlocksToExplore.count(succ))
2521         continue;
2522       if (!ArtificialBlocks.count(succ))
2523         continue;
2524       ToAdd.insert(succ);
2525       DFS.push_back({succ, succ->succ_begin()});
2526     }
2527 
2528     // Search all those blocks, depth first.
2529     while (!DFS.empty()) {
2530       const MachineBasicBlock *CurBB = DFS.back().first;
2531       MachineBasicBlock::const_succ_iterator &CurSucc = DFS.back().second;
2532       // Walk back if we've explored this blocks successors to the end.
2533       if (CurSucc == CurBB->succ_end()) {
2534         DFS.pop_back();
2535         continue;
2536       }
2537 
2538       // If the current successor is artificial and unexplored, descend into
2539       // it.
2540       if (!ToAdd.count(*CurSucc) && ArtificialBlocks.count(*CurSucc)) {
2541         ToAdd.insert(*CurSucc);
2542         DFS.push_back({*CurSucc, (*CurSucc)->succ_begin()});
2543         continue;
2544       }
2545 
2546       ++CurSucc;
2547     }
2548   };
2549 
2550   BlocksToExplore.insert(ToAdd.begin(), ToAdd.end());
2551 }
2552 
2553 void InstrRefBasedLDV::buildVLocValueMap(
2554     const DILocation *DILoc, const SmallSet<DebugVariable, 4> &VarsWeCareAbout,
2555     SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, LiveInsT &Output,
2556     FuncValueTable &MOutLocs, FuncValueTable &MInLocs,
2557     SmallVectorImpl<VLocTracker> &AllTheVLocs) {
2558   // This method is much like buildMLocValueMap: but focuses on a single
2559   // LexicalScope at a time. Pick out a set of blocks and variables that are
2560   // to have their value assignments solved, then run our dataflow algorithm
2561   // until a fixedpoint is reached.
2562   std::priority_queue<unsigned int, std::vector<unsigned int>,
2563                       std::greater<unsigned int>>
2564       Worklist, Pending;
2565   SmallPtrSet<MachineBasicBlock *, 16> OnWorklist, OnPending;
2566 
2567   // The set of blocks we'll be examining.
2568   SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
2569 
2570   // The order in which to examine them (RPO).
2571   SmallVector<MachineBasicBlock *, 8> BlockOrders;
2572 
2573   // RPO ordering function.
2574   auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
2575     return BBToOrder[A] < BBToOrder[B];
2576   };
2577 
2578   getBlocksForScope(DILoc, BlocksToExplore, AssignBlocks);
2579 
2580   // Single block scope: not interesting! No propagation at all. Note that
2581   // this could probably go above ArtificialBlocks without damage, but
2582   // that then produces output differences from original-live-debug-values,
2583   // which propagates from a single block into many artificial ones.
2584   if (BlocksToExplore.size() == 1)
2585     return;
2586 
2587   // Convert a const set to a non-const set. LexicalScopes
2588   // getMachineBasicBlocks returns const MBB pointers, IDF wants mutable ones.
2589   // (Neither of them mutate anything).
2590   SmallPtrSet<MachineBasicBlock *, 8> MutBlocksToExplore;
2591   for (const auto *MBB : BlocksToExplore)
2592     MutBlocksToExplore.insert(const_cast<MachineBasicBlock *>(MBB));
2593 
2594   // Picks out relevants blocks RPO order and sort them.
2595   for (auto *MBB : BlocksToExplore)
2596     BlockOrders.push_back(const_cast<MachineBasicBlock *>(MBB));
2597 
2598   llvm::sort(BlockOrders, Cmp);
2599   unsigned NumBlocks = BlockOrders.size();
2600 
2601   // Allocate some vectors for storing the live ins and live outs. Large.
2602   SmallVector<DbgValue, 32> LiveIns, LiveOuts;
2603   LiveIns.reserve(NumBlocks);
2604   LiveOuts.reserve(NumBlocks);
2605 
2606   // Initialize all values to start as NoVals. This signifies "it's live
2607   // through, but we don't know what it is".
2608   DbgValueProperties EmptyProperties(EmptyExpr, false);
2609   for (unsigned int I = 0; I < NumBlocks; ++I) {
2610     DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal);
2611     LiveIns.push_back(EmptyDbgValue);
2612     LiveOuts.push_back(EmptyDbgValue);
2613   }
2614 
2615   // Produce by-MBB indexes of live-in/live-outs, to ease lookup within
2616   // vlocJoin.
2617   LiveIdxT LiveOutIdx, LiveInIdx;
2618   LiveOutIdx.reserve(NumBlocks);
2619   LiveInIdx.reserve(NumBlocks);
2620   for (unsigned I = 0; I < NumBlocks; ++I) {
2621     LiveOutIdx[BlockOrders[I]] = &LiveOuts[I];
2622     LiveInIdx[BlockOrders[I]] = &LiveIns[I];
2623   }
2624 
2625   // Loop over each variable and place PHIs for it, then propagate values
2626   // between blocks. This keeps the locality of working on one lexical scope at
2627   // at time, but avoids re-processing variable values because some other
2628   // variable has been assigned.
2629   for (auto &Var : VarsWeCareAbout) {
2630     // Re-initialize live-ins and live-outs, to clear the remains of previous
2631     // variables live-ins / live-outs.
2632     for (unsigned int I = 0; I < NumBlocks; ++I) {
2633       DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal);
2634       LiveIns[I] = EmptyDbgValue;
2635       LiveOuts[I] = EmptyDbgValue;
2636     }
2637 
2638     // Place PHIs for variable values, using the LLVM IDF calculator.
2639     // Collect the set of blocks where variables are def'd.
2640     SmallPtrSet<MachineBasicBlock *, 32> DefBlocks;
2641     for (const MachineBasicBlock *ExpMBB : BlocksToExplore) {
2642       auto &TransferFunc = AllTheVLocs[ExpMBB->getNumber()].Vars;
2643       if (TransferFunc.find(Var) != TransferFunc.end())
2644         DefBlocks.insert(const_cast<MachineBasicBlock *>(ExpMBB));
2645     }
2646 
2647     SmallVector<MachineBasicBlock *, 32> PHIBlocks;
2648 
2649     // Request the set of PHIs we should insert for this variable. If there's
2650     // only one value definition, things are very simple.
2651     if (DefBlocks.size() == 1) {
2652       placePHIsForSingleVarDefinition(MutBlocksToExplore, *DefBlocks.begin(),
2653                                       AllTheVLocs, Var, Output);
2654       continue;
2655     }
2656 
2657     // Otherwise: we need to place PHIs through SSA and propagate values.
2658     BlockPHIPlacement(MutBlocksToExplore, DefBlocks, PHIBlocks);
2659 
2660     // Insert PHIs into the per-block live-in tables for this variable.
2661     for (MachineBasicBlock *PHIMBB : PHIBlocks) {
2662       unsigned BlockNo = PHIMBB->getNumber();
2663       DbgValue *LiveIn = LiveInIdx[PHIMBB];
2664       *LiveIn = DbgValue(BlockNo, EmptyProperties, DbgValue::VPHI);
2665     }
2666 
2667     for (auto *MBB : BlockOrders) {
2668       Worklist.push(BBToOrder[MBB]);
2669       OnWorklist.insert(MBB);
2670     }
2671 
2672     // Iterate over all the blocks we selected, propagating the variables value.
2673     // This loop does two things:
2674     //  * Eliminates un-necessary VPHIs in vlocJoin,
2675     //  * Evaluates the blocks transfer function (i.e. variable assignments) and
2676     //    stores the result to the blocks live-outs.
2677     // Always evaluate the transfer function on the first iteration, and when
2678     // the live-ins change thereafter.
2679     bool FirstTrip = true;
2680     while (!Worklist.empty() || !Pending.empty()) {
2681       while (!Worklist.empty()) {
2682         auto *MBB = OrderToBB[Worklist.top()];
2683         CurBB = MBB->getNumber();
2684         Worklist.pop();
2685 
2686         auto LiveInsIt = LiveInIdx.find(MBB);
2687         assert(LiveInsIt != LiveInIdx.end());
2688         DbgValue *LiveIn = LiveInsIt->second;
2689 
2690         // Join values from predecessors. Updates LiveInIdx, and writes output
2691         // into JoinedInLocs.
2692         bool InLocsChanged =
2693             vlocJoin(*MBB, LiveOutIdx, BlocksToExplore, *LiveIn);
2694 
2695         SmallVector<const MachineBasicBlock *, 8> Preds;
2696         for (const auto *Pred : MBB->predecessors())
2697           Preds.push_back(Pred);
2698 
2699         // If this block's live-in value is a VPHI, try to pick a machine-value
2700         // for it. This makes the machine-value available and propagated
2701         // through all blocks by the time value propagation finishes. We can't
2702         // do this any earlier as it needs to read the block live-outs.
2703         if (LiveIn->Kind == DbgValue::VPHI && LiveIn->BlockNo == (int)CurBB) {
2704           // There's a small possibility that on a preceeding path, a VPHI is
2705           // eliminated and transitions from VPHI-with-location to
2706           // live-through-value. As a result, the selected location of any VPHI
2707           // might change, so we need to re-compute it on each iteration.
2708           Optional<ValueIDNum> ValueNum =
2709               pickVPHILoc(*MBB, Var, LiveOutIdx, MOutLocs, Preds);
2710 
2711           if (ValueNum) {
2712             InLocsChanged |= LiveIn->ID != *ValueNum;
2713             LiveIn->ID = *ValueNum;
2714           }
2715         }
2716 
2717         if (!InLocsChanged && !FirstTrip)
2718           continue;
2719 
2720         DbgValue *LiveOut = LiveOutIdx[MBB];
2721         bool OLChanged = false;
2722 
2723         // Do transfer function.
2724         auto &VTracker = AllTheVLocs[MBB->getNumber()];
2725         auto TransferIt = VTracker.Vars.find(Var);
2726         if (TransferIt != VTracker.Vars.end()) {
2727           // Erase on empty transfer (DBG_VALUE $noreg).
2728           if (TransferIt->second.Kind == DbgValue::Undef) {
2729             DbgValue NewVal(MBB->getNumber(), EmptyProperties, DbgValue::NoVal);
2730             if (*LiveOut != NewVal) {
2731               *LiveOut = NewVal;
2732               OLChanged = true;
2733             }
2734           } else {
2735             // Insert new variable value; or overwrite.
2736             if (*LiveOut != TransferIt->second) {
2737               *LiveOut = TransferIt->second;
2738               OLChanged = true;
2739             }
2740           }
2741         } else {
2742           // Just copy live-ins to live-outs, for anything not transferred.
2743           if (*LiveOut != *LiveIn) {
2744             *LiveOut = *LiveIn;
2745             OLChanged = true;
2746           }
2747         }
2748 
2749         // If no live-out value changed, there's no need to explore further.
2750         if (!OLChanged)
2751           continue;
2752 
2753         // We should visit all successors. Ensure we'll visit any non-backedge
2754         // successors during this dataflow iteration; book backedge successors
2755         // to be visited next time around.
2756         for (auto s : MBB->successors()) {
2757           // Ignore out of scope / not-to-be-explored successors.
2758           if (LiveInIdx.find(s) == LiveInIdx.end())
2759             continue;
2760 
2761           if (BBToOrder[s] > BBToOrder[MBB]) {
2762             if (OnWorklist.insert(s).second)
2763               Worklist.push(BBToOrder[s]);
2764           } else if (OnPending.insert(s).second && (FirstTrip || OLChanged)) {
2765             Pending.push(BBToOrder[s]);
2766           }
2767         }
2768       }
2769       Worklist.swap(Pending);
2770       std::swap(OnWorklist, OnPending);
2771       OnPending.clear();
2772       assert(Pending.empty());
2773       FirstTrip = false;
2774     }
2775 
2776     // Save live-ins to output vector. Ignore any that are still marked as being
2777     // VPHIs with no location -- those are variables that we know the value of,
2778     // but are not actually available in the register file.
2779     for (auto *MBB : BlockOrders) {
2780       DbgValue *BlockLiveIn = LiveInIdx[MBB];
2781       if (BlockLiveIn->Kind == DbgValue::NoVal)
2782         continue;
2783       if (BlockLiveIn->Kind == DbgValue::VPHI &&
2784           BlockLiveIn->ID == ValueIDNum::EmptyValue)
2785         continue;
2786       if (BlockLiveIn->Kind == DbgValue::VPHI)
2787         BlockLiveIn->Kind = DbgValue::Def;
2788       assert(BlockLiveIn->Properties.DIExpr->getFragmentInfo() ==
2789              Var.getFragment() && "Fragment info missing during value prop");
2790       Output[MBB->getNumber()].push_back(std::make_pair(Var, *BlockLiveIn));
2791     }
2792   } // Per-variable loop.
2793 
2794   BlockOrders.clear();
2795   BlocksToExplore.clear();
2796 }
2797 
2798 void InstrRefBasedLDV::placePHIsForSingleVarDefinition(
2799     const SmallPtrSetImpl<MachineBasicBlock *> &InScopeBlocks,
2800     MachineBasicBlock *AssignMBB, SmallVectorImpl<VLocTracker> &AllTheVLocs,
2801     const DebugVariable &Var, LiveInsT &Output) {
2802   // If there is a single definition of the variable, then working out it's
2803   // value everywhere is very simple: it's every block dominated by the
2804   // definition. At the dominance frontier, the usual algorithm would:
2805   //  * Place PHIs,
2806   //  * Propagate values into them,
2807   //  * Find there's no incoming variable value from the other incoming branches
2808   //    of the dominance frontier,
2809   //  * Specify there's no variable value in blocks past the frontier.
2810   // This is a common case, hence it's worth special-casing it.
2811 
2812   // Pick out the variables value from the block transfer function.
2813   VLocTracker &VLocs = AllTheVLocs[AssignMBB->getNumber()];
2814   auto ValueIt = VLocs.Vars.find(Var);
2815   const DbgValue &Value = ValueIt->second;
2816 
2817   // If it's an explicit assignment of "undef", that means there is no location
2818   // anyway, anywhere.
2819   if (Value.Kind == DbgValue::Undef)
2820     return;
2821 
2822   // Assign the variable value to entry to each dominated block that's in scope.
2823   // Skip the definition block -- it's assigned the variable value in the middle
2824   // of the block somewhere.
2825   for (auto *ScopeBlock : InScopeBlocks) {
2826     if (!DomTree->properlyDominates(AssignMBB, ScopeBlock))
2827       continue;
2828 
2829     Output[ScopeBlock->getNumber()].push_back({Var, Value});
2830   }
2831 
2832   // All blocks that aren't dominated have no live-in value, thus no variable
2833   // value will be given to them.
2834 }
2835 
2836 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2837 void InstrRefBasedLDV::dump_mloc_transfer(
2838     const MLocTransferMap &mloc_transfer) const {
2839   for (auto &P : mloc_transfer) {
2840     std::string foo = MTracker->LocIdxToName(P.first);
2841     std::string bar = MTracker->IDAsString(P.second);
2842     dbgs() << "Loc " << foo << " --> " << bar << "\n";
2843   }
2844 }
2845 #endif
2846 
2847 void InstrRefBasedLDV::initialSetup(MachineFunction &MF) {
2848   // Build some useful data structures.
2849 
2850   LLVMContext &Context = MF.getFunction().getContext();
2851   EmptyExpr = DIExpression::get(Context, {});
2852 
2853   auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
2854     if (const DebugLoc &DL = MI.getDebugLoc())
2855       return DL.getLine() != 0;
2856     return false;
2857   };
2858   // Collect a set of all the artificial blocks.
2859   for (auto &MBB : MF)
2860     if (none_of(MBB.instrs(), hasNonArtificialLocation))
2861       ArtificialBlocks.insert(&MBB);
2862 
2863   // Compute mappings of block <=> RPO order.
2864   ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
2865   unsigned int RPONumber = 0;
2866   for (MachineBasicBlock *MBB : RPOT) {
2867     OrderToBB[RPONumber] = MBB;
2868     BBToOrder[MBB] = RPONumber;
2869     BBNumToRPO[MBB->getNumber()] = RPONumber;
2870     ++RPONumber;
2871   }
2872 
2873   // Order value substitutions by their "source" operand pair, for quick lookup.
2874   llvm::sort(MF.DebugValueSubstitutions);
2875 
2876 #ifdef EXPENSIVE_CHECKS
2877   // As an expensive check, test whether there are any duplicate substitution
2878   // sources in the collection.
2879   if (MF.DebugValueSubstitutions.size() > 2) {
2880     for (auto It = MF.DebugValueSubstitutions.begin();
2881          It != std::prev(MF.DebugValueSubstitutions.end()); ++It) {
2882       assert(It->Src != std::next(It)->Src && "Duplicate variable location "
2883                                               "substitution seen");
2884     }
2885   }
2886 #endif
2887 }
2888 
2889 // Produce an "ejection map" for blocks, i.e., what's the highest-numbered
2890 // lexical scope it's used in. When exploring in DFS order and we pass that
2891 // scope, the block can be processed and any tracking information freed.
2892 void InstrRefBasedLDV::makeDepthFirstEjectionMap(
2893     SmallVectorImpl<unsigned> &EjectionMap,
2894     const ScopeToDILocT &ScopeToDILocation,
2895     ScopeToAssignBlocksT &ScopeToAssignBlocks) {
2896   SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
2897   SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack;
2898   auto *TopScope = LS.getCurrentFunctionScope();
2899 
2900   // Unlike lexical scope explorers, we explore in reverse order, to find the
2901   // "last" lexical scope used for each block early.
2902   WorkStack.push_back({TopScope, TopScope->getChildren().size() - 1});
2903 
2904   while (!WorkStack.empty()) {
2905     auto &ScopePosition = WorkStack.back();
2906     LexicalScope *WS = ScopePosition.first;
2907     ssize_t ChildNum = ScopePosition.second--;
2908 
2909     const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();
2910     if (ChildNum >= 0) {
2911       // If ChildNum is positive, there are remaining children to explore.
2912       // Push the child and its children-count onto the stack.
2913       auto &ChildScope = Children[ChildNum];
2914       WorkStack.push_back(
2915           std::make_pair(ChildScope, ChildScope->getChildren().size() - 1));
2916     } else {
2917       WorkStack.pop_back();
2918 
2919       // We've explored all children and any later blocks: examine all blocks
2920       // in our scope. If they haven't yet had an ejection number set, then
2921       // this scope will be the last to use that block.
2922       auto DILocationIt = ScopeToDILocation.find(WS);
2923       if (DILocationIt != ScopeToDILocation.end()) {
2924         getBlocksForScope(DILocationIt->second, BlocksToExplore,
2925                           ScopeToAssignBlocks.find(WS)->second);
2926         for (auto *MBB : BlocksToExplore) {
2927           unsigned BBNum = MBB->getNumber();
2928           if (EjectionMap[BBNum] == 0)
2929             EjectionMap[BBNum] = WS->getDFSOut();
2930         }
2931 
2932         BlocksToExplore.clear();
2933       }
2934     }
2935   }
2936 }
2937 
2938 bool InstrRefBasedLDV::depthFirstVLocAndEmit(
2939     unsigned MaxNumBlocks, const ScopeToDILocT &ScopeToDILocation,
2940     const ScopeToVarsT &ScopeToVars, ScopeToAssignBlocksT &ScopeToAssignBlocks,
2941     LiveInsT &Output, FuncValueTable &MOutLocs, FuncValueTable &MInLocs,
2942     SmallVectorImpl<VLocTracker> &AllTheVLocs, MachineFunction &MF,
2943     DenseMap<DebugVariable, unsigned> &AllVarsNumbering,
2944     const TargetPassConfig &TPC) {
2945   TTracker = new TransferTracker(TII, MTracker, MF, *TRI, CalleeSavedRegs, TPC);
2946   unsigned NumLocs = MTracker->getNumLocs();
2947   VTracker = nullptr;
2948 
2949   // No scopes? No variable locations.
2950   if (!LS.getCurrentFunctionScope())
2951     return false;
2952 
2953   // Build map from block number to the last scope that uses the block.
2954   SmallVector<unsigned, 16> EjectionMap;
2955   EjectionMap.resize(MaxNumBlocks, 0);
2956   makeDepthFirstEjectionMap(EjectionMap, ScopeToDILocation,
2957                             ScopeToAssignBlocks);
2958 
2959   // Helper lambda for ejecting a block -- if nothing is going to use the block,
2960   // we can translate the variable location information into DBG_VALUEs and then
2961   // free all of InstrRefBasedLDV's data structures.
2962   auto EjectBlock = [&](MachineBasicBlock &MBB) -> void {
2963     unsigned BBNum = MBB.getNumber();
2964     AllTheVLocs[BBNum].clear();
2965 
2966     // Prime the transfer-tracker, and then step through all the block
2967     // instructions, installing transfers.
2968     MTracker->reset();
2969     MTracker->loadFromArray(MInLocs[BBNum], BBNum);
2970     TTracker->loadInlocs(MBB, MInLocs[BBNum], Output[BBNum], NumLocs);
2971 
2972     CurBB = BBNum;
2973     CurInst = 1;
2974     for (auto &MI : MBB) {
2975       process(MI, MOutLocs.get(), MInLocs.get());
2976       TTracker->checkInstForNewValues(CurInst, MI.getIterator());
2977       ++CurInst;
2978     }
2979 
2980     // Free machine-location tables for this block.
2981     MInLocs[BBNum].reset();
2982     MOutLocs[BBNum].reset();
2983     // We don't need live-in variable values for this block either.
2984     Output[BBNum].clear();
2985     AllTheVLocs[BBNum].clear();
2986   };
2987 
2988   SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
2989   SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack;
2990   WorkStack.push_back({LS.getCurrentFunctionScope(), 0});
2991   unsigned HighestDFSIn = 0;
2992 
2993   // Proceed to explore in depth first order.
2994   while (!WorkStack.empty()) {
2995     auto &ScopePosition = WorkStack.back();
2996     LexicalScope *WS = ScopePosition.first;
2997     ssize_t ChildNum = ScopePosition.second++;
2998 
2999     // We obesrve scopes with children twice here, once descending in, once
3000     // ascending out of the scope nest. Use HighestDFSIn as a ratchet to ensure
3001     // we don't process a scope twice. Additionally, ignore scopes that don't
3002     // have a DILocation -- by proxy, this means we never tracked any variable
3003     // assignments in that scope.
3004     auto DILocIt = ScopeToDILocation.find(WS);
3005     if (HighestDFSIn <= WS->getDFSIn() && DILocIt != ScopeToDILocation.end()) {
3006       const DILocation *DILoc = DILocIt->second;
3007       auto &VarsWeCareAbout = ScopeToVars.find(WS)->second;
3008       auto &BlocksInScope = ScopeToAssignBlocks.find(WS)->second;
3009 
3010       buildVLocValueMap(DILoc, VarsWeCareAbout, BlocksInScope, Output, MOutLocs,
3011                         MInLocs, AllTheVLocs);
3012     }
3013 
3014     HighestDFSIn = std::max(HighestDFSIn, WS->getDFSIn());
3015 
3016     // Descend into any scope nests.
3017     const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();
3018     if (ChildNum < (ssize_t)Children.size()) {
3019       // There are children to explore -- push onto stack and continue.
3020       auto &ChildScope = Children[ChildNum];
3021       WorkStack.push_back(std::make_pair(ChildScope, 0));
3022     } else {
3023       WorkStack.pop_back();
3024 
3025       // We've explored a leaf, or have explored all the children of a scope.
3026       // Try to eject any blocks where this is the last scope it's relevant to.
3027       auto DILocationIt = ScopeToDILocation.find(WS);
3028       if (DILocationIt == ScopeToDILocation.end())
3029         continue;
3030 
3031       getBlocksForScope(DILocationIt->second, BlocksToExplore,
3032                         ScopeToAssignBlocks.find(WS)->second);
3033       for (auto *MBB : BlocksToExplore)
3034         if (WS->getDFSOut() == EjectionMap[MBB->getNumber()])
3035           EjectBlock(const_cast<MachineBasicBlock &>(*MBB));
3036 
3037       BlocksToExplore.clear();
3038     }
3039   }
3040 
3041   // Some artificial blocks may not have been ejected, meaning they're not
3042   // connected to an actual legitimate scope. This can technically happen
3043   // with things like the entry block. In theory, we shouldn't need to do
3044   // anything for such out-of-scope blocks, but for the sake of being similar
3045   // to VarLocBasedLDV, eject these too.
3046   for (auto *MBB : ArtificialBlocks)
3047     if (MOutLocs[MBB->getNumber()])
3048       EjectBlock(*MBB);
3049 
3050   return emitTransfers(AllVarsNumbering);
3051 }
3052 
3053 bool InstrRefBasedLDV::emitTransfers(
3054     DenseMap<DebugVariable, unsigned> &AllVarsNumbering) {
3055   // Go through all the transfers recorded in the TransferTracker -- this is
3056   // both the live-ins to a block, and any movements of values that happen
3057   // in the middle.
3058   for (const auto &P : TTracker->Transfers) {
3059     // We have to insert DBG_VALUEs in a consistent order, otherwise they
3060     // appear in DWARF in different orders. Use the order that they appear
3061     // when walking through each block / each instruction, stored in
3062     // AllVarsNumbering.
3063     SmallVector<std::pair<unsigned, MachineInstr *>> Insts;
3064     for (MachineInstr *MI : P.Insts) {
3065       DebugVariable Var(MI->getDebugVariable(), MI->getDebugExpression(),
3066                         MI->getDebugLoc()->getInlinedAt());
3067       Insts.emplace_back(AllVarsNumbering.find(Var)->second, MI);
3068     }
3069     llvm::sort(Insts,
3070                [](const auto &A, const auto &B) { return A.first < B.first; });
3071 
3072     // Insert either before or after the designated point...
3073     if (P.MBB) {
3074       MachineBasicBlock &MBB = *P.MBB;
3075       for (const auto &Pair : Insts)
3076         MBB.insert(P.Pos, Pair.second);
3077     } else {
3078       // Terminators, like tail calls, can clobber things. Don't try and place
3079       // transfers after them.
3080       if (P.Pos->isTerminator())
3081         continue;
3082 
3083       MachineBasicBlock &MBB = *P.Pos->getParent();
3084       for (const auto &Pair : Insts)
3085         MBB.insertAfterBundle(P.Pos, Pair.second);
3086     }
3087   }
3088 
3089   return TTracker->Transfers.size() != 0;
3090 }
3091 
3092 /// Calculate the liveness information for the given machine function and
3093 /// extend ranges across basic blocks.
3094 bool InstrRefBasedLDV::ExtendRanges(MachineFunction &MF,
3095                                     MachineDominatorTree *DomTree,
3096                                     TargetPassConfig *TPC,
3097                                     unsigned InputBBLimit,
3098                                     unsigned InputDbgValLimit) {
3099   // No subprogram means this function contains no debuginfo.
3100   if (!MF.getFunction().getSubprogram())
3101     return false;
3102 
3103   LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
3104   this->TPC = TPC;
3105 
3106   this->DomTree = DomTree;
3107   TRI = MF.getSubtarget().getRegisterInfo();
3108   MRI = &MF.getRegInfo();
3109   TII = MF.getSubtarget().getInstrInfo();
3110   TFI = MF.getSubtarget().getFrameLowering();
3111   TFI->getCalleeSaves(MF, CalleeSavedRegs);
3112   MFI = &MF.getFrameInfo();
3113   LS.initialize(MF);
3114 
3115   const auto &STI = MF.getSubtarget();
3116   AdjustsStackInCalls = MFI->adjustsStack() &&
3117                         STI.getFrameLowering()->stackProbeFunctionModifiesSP();
3118   if (AdjustsStackInCalls)
3119     StackProbeSymbolName = STI.getTargetLowering()->getStackProbeSymbolName(MF);
3120 
3121   MTracker =
3122       new MLocTracker(MF, *TII, *TRI, *MF.getSubtarget().getTargetLowering());
3123   VTracker = nullptr;
3124   TTracker = nullptr;
3125 
3126   SmallVector<MLocTransferMap, 32> MLocTransfer;
3127   SmallVector<VLocTracker, 8> vlocs;
3128   LiveInsT SavedLiveIns;
3129 
3130   int MaxNumBlocks = -1;
3131   for (auto &MBB : MF)
3132     MaxNumBlocks = std::max(MBB.getNumber(), MaxNumBlocks);
3133   assert(MaxNumBlocks >= 0);
3134   ++MaxNumBlocks;
3135 
3136   MLocTransfer.resize(MaxNumBlocks);
3137   vlocs.resize(MaxNumBlocks, VLocTracker(OverlapFragments, EmptyExpr));
3138   SavedLiveIns.resize(MaxNumBlocks);
3139 
3140   initialSetup(MF);
3141 
3142   produceMLocTransferFunction(MF, MLocTransfer, MaxNumBlocks);
3143 
3144   // Allocate and initialize two array-of-arrays for the live-in and live-out
3145   // machine values. The outer dimension is the block number; while the inner
3146   // dimension is a LocIdx from MLocTracker.
3147   FuncValueTable MOutLocs = std::make_unique<ValueTable[]>(MaxNumBlocks);
3148   FuncValueTable MInLocs = std::make_unique<ValueTable[]>(MaxNumBlocks);
3149   unsigned NumLocs = MTracker->getNumLocs();
3150   for (int i = 0; i < MaxNumBlocks; ++i) {
3151     // These all auto-initialize to ValueIDNum::EmptyValue
3152     MOutLocs[i] = std::make_unique<ValueIDNum[]>(NumLocs);
3153     MInLocs[i] = std::make_unique<ValueIDNum[]>(NumLocs);
3154   }
3155 
3156   // Solve the machine value dataflow problem using the MLocTransfer function,
3157   // storing the computed live-ins / live-outs into the array-of-arrays. We use
3158   // both live-ins and live-outs for decision making in the variable value
3159   // dataflow problem.
3160   buildMLocValueMap(MF, MInLocs, MOutLocs, MLocTransfer);
3161 
3162   // Patch up debug phi numbers, turning unknown block-live-in values into
3163   // either live-through machine values, or PHIs.
3164   for (auto &DBG_PHI : DebugPHINumToValue) {
3165     // Identify unresolved block-live-ins.
3166     if (!DBG_PHI.ValueRead)
3167       continue;
3168 
3169     ValueIDNum &Num = *DBG_PHI.ValueRead;
3170     if (!Num.isPHI())
3171       continue;
3172 
3173     unsigned BlockNo = Num.getBlock();
3174     LocIdx LocNo = Num.getLoc();
3175     Num = MInLocs[BlockNo][LocNo.asU64()];
3176   }
3177   // Later, we'll be looking up ranges of instruction numbers.
3178   llvm::sort(DebugPHINumToValue);
3179 
3180   // Walk back through each block / instruction, collecting DBG_VALUE
3181   // instructions and recording what machine value their operands refer to.
3182   for (auto &OrderPair : OrderToBB) {
3183     MachineBasicBlock &MBB = *OrderPair.second;
3184     CurBB = MBB.getNumber();
3185     VTracker = &vlocs[CurBB];
3186     VTracker->MBB = &MBB;
3187     MTracker->loadFromArray(MInLocs[CurBB], CurBB);
3188     CurInst = 1;
3189     for (auto &MI : MBB) {
3190       process(MI, MOutLocs.get(), MInLocs.get());
3191       ++CurInst;
3192     }
3193     MTracker->reset();
3194   }
3195 
3196   // Number all variables in the order that they appear, to be used as a stable
3197   // insertion order later.
3198   DenseMap<DebugVariable, unsigned> AllVarsNumbering;
3199 
3200   // Map from one LexicalScope to all the variables in that scope.
3201   ScopeToVarsT ScopeToVars;
3202 
3203   // Map from One lexical scope to all blocks where assignments happen for
3204   // that scope.
3205   ScopeToAssignBlocksT ScopeToAssignBlocks;
3206 
3207   // Store map of DILocations that describes scopes.
3208   ScopeToDILocT ScopeToDILocation;
3209 
3210   // To mirror old LiveDebugValues, enumerate variables in RPOT order. Otherwise
3211   // the order is unimportant, it just has to be stable.
3212   unsigned VarAssignCount = 0;
3213   for (unsigned int I = 0; I < OrderToBB.size(); ++I) {
3214     auto *MBB = OrderToBB[I];
3215     auto *VTracker = &vlocs[MBB->getNumber()];
3216     // Collect each variable with a DBG_VALUE in this block.
3217     for (auto &idx : VTracker->Vars) {
3218       const auto &Var = idx.first;
3219       const DILocation *ScopeLoc = VTracker->Scopes[Var];
3220       assert(ScopeLoc != nullptr);
3221       auto *Scope = LS.findLexicalScope(ScopeLoc);
3222 
3223       // No insts in scope -> shouldn't have been recorded.
3224       assert(Scope != nullptr);
3225 
3226       AllVarsNumbering.insert(std::make_pair(Var, AllVarsNumbering.size()));
3227       ScopeToVars[Scope].insert(Var);
3228       ScopeToAssignBlocks[Scope].insert(VTracker->MBB);
3229       ScopeToDILocation[Scope] = ScopeLoc;
3230       ++VarAssignCount;
3231     }
3232   }
3233 
3234   bool Changed = false;
3235 
3236   // If we have an extremely large number of variable assignments and blocks,
3237   // bail out at this point. We've burnt some time doing analysis already,
3238   // however we should cut our losses.
3239   if ((unsigned)MaxNumBlocks > InputBBLimit &&
3240       VarAssignCount > InputDbgValLimit) {
3241     LLVM_DEBUG(dbgs() << "Disabling InstrRefBasedLDV: " << MF.getName()
3242                       << " has " << MaxNumBlocks << " basic blocks and "
3243                       << VarAssignCount
3244                       << " variable assignments, exceeding limits.\n");
3245   } else {
3246     // Optionally, solve the variable value problem and emit to blocks by using
3247     // a lexical-scope-depth search. It should be functionally identical to
3248     // the "else" block of this condition.
3249     Changed = depthFirstVLocAndEmit(
3250         MaxNumBlocks, ScopeToDILocation, ScopeToVars, ScopeToAssignBlocks,
3251         SavedLiveIns, MOutLocs, MInLocs, vlocs, MF, AllVarsNumbering, *TPC);
3252   }
3253 
3254   delete MTracker;
3255   delete TTracker;
3256   MTracker = nullptr;
3257   VTracker = nullptr;
3258   TTracker = nullptr;
3259 
3260   ArtificialBlocks.clear();
3261   OrderToBB.clear();
3262   BBToOrder.clear();
3263   BBNumToRPO.clear();
3264   DebugInstrNumToInstr.clear();
3265   DebugPHINumToValue.clear();
3266   OverlapFragments.clear();
3267   SeenFragments.clear();
3268   SeenDbgPHIs.clear();
3269 
3270   return Changed;
3271 }
3272 
3273 LDVImpl *llvm::makeInstrRefBasedLiveDebugValues() {
3274   return new InstrRefBasedLDV();
3275 }
3276 
3277 namespace {
3278 class LDVSSABlock;
3279 class LDVSSAUpdater;
3280 
3281 // Pick a type to identify incoming block values as we construct SSA. We
3282 // can't use anything more robust than an integer unfortunately, as SSAUpdater
3283 // expects to zero-initialize the type.
3284 typedef uint64_t BlockValueNum;
3285 
3286 /// Represents an SSA PHI node for the SSA updater class. Contains the block
3287 /// this PHI is in, the value number it would have, and the expected incoming
3288 /// values from parent blocks.
3289 class LDVSSAPhi {
3290 public:
3291   SmallVector<std::pair<LDVSSABlock *, BlockValueNum>, 4> IncomingValues;
3292   LDVSSABlock *ParentBlock;
3293   BlockValueNum PHIValNum;
3294   LDVSSAPhi(BlockValueNum PHIValNum, LDVSSABlock *ParentBlock)
3295       : ParentBlock(ParentBlock), PHIValNum(PHIValNum) {}
3296 
3297   LDVSSABlock *getParent() { return ParentBlock; }
3298 };
3299 
3300 /// Thin wrapper around a block predecessor iterator. Only difference from a
3301 /// normal block iterator is that it dereferences to an LDVSSABlock.
3302 class LDVSSABlockIterator {
3303 public:
3304   MachineBasicBlock::pred_iterator PredIt;
3305   LDVSSAUpdater &Updater;
3306 
3307   LDVSSABlockIterator(MachineBasicBlock::pred_iterator PredIt,
3308                       LDVSSAUpdater &Updater)
3309       : PredIt(PredIt), Updater(Updater) {}
3310 
3311   bool operator!=(const LDVSSABlockIterator &OtherIt) const {
3312     return OtherIt.PredIt != PredIt;
3313   }
3314 
3315   LDVSSABlockIterator &operator++() {
3316     ++PredIt;
3317     return *this;
3318   }
3319 
3320   LDVSSABlock *operator*();
3321 };
3322 
3323 /// Thin wrapper around a block for SSA Updater interface. Necessary because
3324 /// we need to track the PHI value(s) that we may have observed as necessary
3325 /// in this block.
3326 class LDVSSABlock {
3327 public:
3328   MachineBasicBlock &BB;
3329   LDVSSAUpdater &Updater;
3330   using PHIListT = SmallVector<LDVSSAPhi, 1>;
3331   /// List of PHIs in this block. There should only ever be one.
3332   PHIListT PHIList;
3333 
3334   LDVSSABlock(MachineBasicBlock &BB, LDVSSAUpdater &Updater)
3335       : BB(BB), Updater(Updater) {}
3336 
3337   LDVSSABlockIterator succ_begin() {
3338     return LDVSSABlockIterator(BB.succ_begin(), Updater);
3339   }
3340 
3341   LDVSSABlockIterator succ_end() {
3342     return LDVSSABlockIterator(BB.succ_end(), Updater);
3343   }
3344 
3345   /// SSAUpdater has requested a PHI: create that within this block record.
3346   LDVSSAPhi *newPHI(BlockValueNum Value) {
3347     PHIList.emplace_back(Value, this);
3348     return &PHIList.back();
3349   }
3350 
3351   /// SSAUpdater wishes to know what PHIs already exist in this block.
3352   PHIListT &phis() { return PHIList; }
3353 };
3354 
3355 /// Utility class for the SSAUpdater interface: tracks blocks, PHIs and values
3356 /// while SSAUpdater is exploring the CFG. It's passed as a handle / baton to
3357 // SSAUpdaterTraits<LDVSSAUpdater>.
3358 class LDVSSAUpdater {
3359 public:
3360   /// Map of value numbers to PHI records.
3361   DenseMap<BlockValueNum, LDVSSAPhi *> PHIs;
3362   /// Map of which blocks generate Undef values -- blocks that are not
3363   /// dominated by any Def.
3364   DenseMap<MachineBasicBlock *, BlockValueNum> UndefMap;
3365   /// Map of machine blocks to our own records of them.
3366   DenseMap<MachineBasicBlock *, LDVSSABlock *> BlockMap;
3367   /// Machine location where any PHI must occur.
3368   LocIdx Loc;
3369   /// Table of live-in machine value numbers for blocks / locations.
3370   const ValueTable *MLiveIns;
3371 
3372   LDVSSAUpdater(LocIdx L, const ValueTable *MLiveIns)
3373       : Loc(L), MLiveIns(MLiveIns) {}
3374 
3375   void reset() {
3376     for (auto &Block : BlockMap)
3377       delete Block.second;
3378 
3379     PHIs.clear();
3380     UndefMap.clear();
3381     BlockMap.clear();
3382   }
3383 
3384   ~LDVSSAUpdater() { reset(); }
3385 
3386   /// For a given MBB, create a wrapper block for it. Stores it in the
3387   /// LDVSSAUpdater block map.
3388   LDVSSABlock *getSSALDVBlock(MachineBasicBlock *BB) {
3389     auto it = BlockMap.find(BB);
3390     if (it == BlockMap.end()) {
3391       BlockMap[BB] = new LDVSSABlock(*BB, *this);
3392       it = BlockMap.find(BB);
3393     }
3394     return it->second;
3395   }
3396 
3397   /// Find the live-in value number for the given block. Looks up the value at
3398   /// the PHI location on entry.
3399   BlockValueNum getValue(LDVSSABlock *LDVBB) {
3400     return MLiveIns[LDVBB->BB.getNumber()][Loc.asU64()].asU64();
3401   }
3402 };
3403 
3404 LDVSSABlock *LDVSSABlockIterator::operator*() {
3405   return Updater.getSSALDVBlock(*PredIt);
3406 }
3407 
3408 #ifndef NDEBUG
3409 
3410 raw_ostream &operator<<(raw_ostream &out, const LDVSSAPhi &PHI) {
3411   out << "SSALDVPHI " << PHI.PHIValNum;
3412   return out;
3413 }
3414 
3415 #endif
3416 
3417 } // namespace
3418 
3419 namespace llvm {
3420 
3421 /// Template specialization to give SSAUpdater access to CFG and value
3422 /// information. SSAUpdater calls methods in these traits, passing in the
3423 /// LDVSSAUpdater object, to learn about blocks and the values they define.
3424 /// It also provides methods to create PHI nodes and track them.
3425 template <> class SSAUpdaterTraits<LDVSSAUpdater> {
3426 public:
3427   using BlkT = LDVSSABlock;
3428   using ValT = BlockValueNum;
3429   using PhiT = LDVSSAPhi;
3430   using BlkSucc_iterator = LDVSSABlockIterator;
3431 
3432   // Methods to access block successors -- dereferencing to our wrapper class.
3433   static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); }
3434   static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); }
3435 
3436   /// Iterator for PHI operands.
3437   class PHI_iterator {
3438   private:
3439     LDVSSAPhi *PHI;
3440     unsigned Idx;
3441 
3442   public:
3443     explicit PHI_iterator(LDVSSAPhi *P) // begin iterator
3444         : PHI(P), Idx(0) {}
3445     PHI_iterator(LDVSSAPhi *P, bool) // end iterator
3446         : PHI(P), Idx(PHI->IncomingValues.size()) {}
3447 
3448     PHI_iterator &operator++() {
3449       Idx++;
3450       return *this;
3451     }
3452     bool operator==(const PHI_iterator &X) const { return Idx == X.Idx; }
3453     bool operator!=(const PHI_iterator &X) const { return !operator==(X); }
3454 
3455     BlockValueNum getIncomingValue() { return PHI->IncomingValues[Idx].second; }
3456 
3457     LDVSSABlock *getIncomingBlock() { return PHI->IncomingValues[Idx].first; }
3458   };
3459 
3460   static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
3461 
3462   static inline PHI_iterator PHI_end(PhiT *PHI) {
3463     return PHI_iterator(PHI, true);
3464   }
3465 
3466   /// FindPredecessorBlocks - Put the predecessors of BB into the Preds
3467   /// vector.
3468   static void FindPredecessorBlocks(LDVSSABlock *BB,
3469                                     SmallVectorImpl<LDVSSABlock *> *Preds) {
3470     for (MachineBasicBlock *Pred : BB->BB.predecessors())
3471       Preds->push_back(BB->Updater.getSSALDVBlock(Pred));
3472   }
3473 
3474   /// GetUndefVal - Normally creates an IMPLICIT_DEF instruction with a new
3475   /// register. For LiveDebugValues, represents a block identified as not having
3476   /// any DBG_PHI predecessors.
3477   static BlockValueNum GetUndefVal(LDVSSABlock *BB, LDVSSAUpdater *Updater) {
3478     // Create a value number for this block -- it needs to be unique and in the
3479     // "undef" collection, so that we know it's not real. Use a number
3480     // representing a PHI into this block.
3481     BlockValueNum Num = ValueIDNum(BB->BB.getNumber(), 0, Updater->Loc).asU64();
3482     Updater->UndefMap[&BB->BB] = Num;
3483     return Num;
3484   }
3485 
3486   /// CreateEmptyPHI - Create a (representation of a) PHI in the given block.
3487   /// SSAUpdater will populate it with information about incoming values. The
3488   /// value number of this PHI is whatever the  machine value number problem
3489   /// solution determined it to be. This includes non-phi values if SSAUpdater
3490   /// tries to create a PHI where the incoming values are identical.
3491   static BlockValueNum CreateEmptyPHI(LDVSSABlock *BB, unsigned NumPreds,
3492                                    LDVSSAUpdater *Updater) {
3493     BlockValueNum PHIValNum = Updater->getValue(BB);
3494     LDVSSAPhi *PHI = BB->newPHI(PHIValNum);
3495     Updater->PHIs[PHIValNum] = PHI;
3496     return PHIValNum;
3497   }
3498 
3499   /// AddPHIOperand - Add the specified value as an operand of the PHI for
3500   /// the specified predecessor block.
3501   static void AddPHIOperand(LDVSSAPhi *PHI, BlockValueNum Val, LDVSSABlock *Pred) {
3502     PHI->IncomingValues.push_back(std::make_pair(Pred, Val));
3503   }
3504 
3505   /// ValueIsPHI - Check if the instruction that defines the specified value
3506   /// is a PHI instruction.
3507   static LDVSSAPhi *ValueIsPHI(BlockValueNum Val, LDVSSAUpdater *Updater) {
3508     auto PHIIt = Updater->PHIs.find(Val);
3509     if (PHIIt == Updater->PHIs.end())
3510       return nullptr;
3511     return PHIIt->second;
3512   }
3513 
3514   /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
3515   /// operands, i.e., it was just added.
3516   static LDVSSAPhi *ValueIsNewPHI(BlockValueNum Val, LDVSSAUpdater *Updater) {
3517     LDVSSAPhi *PHI = ValueIsPHI(Val, Updater);
3518     if (PHI && PHI->IncomingValues.size() == 0)
3519       return PHI;
3520     return nullptr;
3521   }
3522 
3523   /// GetPHIValue - For the specified PHI instruction, return the value
3524   /// that it defines.
3525   static BlockValueNum GetPHIValue(LDVSSAPhi *PHI) { return PHI->PHIValNum; }
3526 };
3527 
3528 } // end namespace llvm
3529 
3530 Optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIs(
3531     MachineFunction &MF, const ValueTable *MLiveOuts,
3532     const ValueTable *MLiveIns, MachineInstr &Here, uint64_t InstrNum) {
3533   assert(MLiveOuts && MLiveIns &&
3534          "Tried to resolve DBG_PHI before location "
3535          "tables allocated?");
3536 
3537   // This function will be called twice per DBG_INSTR_REF, and might end up
3538   // computing lots of SSA information: memoize it.
3539   auto SeenDbgPHIIt = SeenDbgPHIs.find(&Here);
3540   if (SeenDbgPHIIt != SeenDbgPHIs.end())
3541     return SeenDbgPHIIt->second;
3542 
3543   Optional<ValueIDNum> Result =
3544       resolveDbgPHIsImpl(MF, MLiveOuts, MLiveIns, Here, InstrNum);
3545   SeenDbgPHIs.insert({&Here, Result});
3546   return Result;
3547 }
3548 
3549 Optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIsImpl(
3550     MachineFunction &MF, const ValueTable *MLiveOuts,
3551     const ValueTable *MLiveIns, MachineInstr &Here, uint64_t InstrNum) {
3552   // Pick out records of DBG_PHI instructions that have been observed. If there
3553   // are none, then we cannot compute a value number.
3554   auto RangePair = std::equal_range(DebugPHINumToValue.begin(),
3555                                     DebugPHINumToValue.end(), InstrNum);
3556   auto LowerIt = RangePair.first;
3557   auto UpperIt = RangePair.second;
3558 
3559   // No DBG_PHI means there can be no location.
3560   if (LowerIt == UpperIt)
3561     return None;
3562 
3563   // If any DBG_PHIs referred to a location we didn't understand, don't try to
3564   // compute a value. There might be scenarios where we could recover a value
3565   // for some range of DBG_INSTR_REFs, but at this point we can have high
3566   // confidence that we've seen a bug.
3567   auto DBGPHIRange = make_range(LowerIt, UpperIt);
3568   for (const DebugPHIRecord &DBG_PHI : DBGPHIRange)
3569     if (!DBG_PHI.ValueRead)
3570       return None;
3571 
3572   // If there's only one DBG_PHI, then that is our value number.
3573   if (std::distance(LowerIt, UpperIt) == 1)
3574     return *LowerIt->ValueRead;
3575 
3576   // Pick out the location (physreg, slot) where any PHIs must occur. It's
3577   // technically possible for us to merge values in different registers in each
3578   // block, but highly unlikely that LLVM will generate such code after register
3579   // allocation.
3580   LocIdx Loc = *LowerIt->ReadLoc;
3581 
3582   // We have several DBG_PHIs, and a use position (the Here inst). All each
3583   // DBG_PHI does is identify a value at a program position. We can treat each
3584   // DBG_PHI like it's a Def of a value, and the use position is a Use of a
3585   // value, just like SSA. We use the bulk-standard LLVM SSA updater class to
3586   // determine which Def is used at the Use, and any PHIs that happen along
3587   // the way.
3588   // Adapted LLVM SSA Updater:
3589   LDVSSAUpdater Updater(Loc, MLiveIns);
3590   // Map of which Def or PHI is the current value in each block.
3591   DenseMap<LDVSSABlock *, BlockValueNum> AvailableValues;
3592   // Set of PHIs that we have created along the way.
3593   SmallVector<LDVSSAPhi *, 8> CreatedPHIs;
3594 
3595   // Each existing DBG_PHI is a Def'd value under this model. Record these Defs
3596   // for the SSAUpdater.
3597   for (const auto &DBG_PHI : DBGPHIRange) {
3598     LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB);
3599     const ValueIDNum &Num = *DBG_PHI.ValueRead;
3600     AvailableValues.insert(std::make_pair(Block, Num.asU64()));
3601   }
3602 
3603   LDVSSABlock *HereBlock = Updater.getSSALDVBlock(Here.getParent());
3604   const auto &AvailIt = AvailableValues.find(HereBlock);
3605   if (AvailIt != AvailableValues.end()) {
3606     // Actually, we already know what the value is -- the Use is in the same
3607     // block as the Def.
3608     return ValueIDNum::fromU64(AvailIt->second);
3609   }
3610 
3611   // Otherwise, we must use the SSA Updater. It will identify the value number
3612   // that we are to use, and the PHIs that must happen along the way.
3613   SSAUpdaterImpl<LDVSSAUpdater> Impl(&Updater, &AvailableValues, &CreatedPHIs);
3614   BlockValueNum ResultInt = Impl.GetValue(Updater.getSSALDVBlock(Here.getParent()));
3615   ValueIDNum Result = ValueIDNum::fromU64(ResultInt);
3616 
3617   // We have the number for a PHI, or possibly live-through value, to be used
3618   // at this Use. There are a number of things we have to check about it though:
3619   //  * Does any PHI use an 'Undef' (like an IMPLICIT_DEF) value? If so, this
3620   //    Use was not completely dominated by DBG_PHIs and we should abort.
3621   //  * Are the Defs or PHIs clobbered in a block? SSAUpdater isn't aware that
3622   //    we've left SSA form. Validate that the inputs to each PHI are the
3623   //    expected values.
3624   //  * Is a PHI we've created actually a merging of values, or are all the
3625   //    predecessor values the same, leading to a non-PHI machine value number?
3626   //    (SSAUpdater doesn't know that either). Remap validated PHIs into the
3627   //    the ValidatedValues collection below to sort this out.
3628   DenseMap<LDVSSABlock *, ValueIDNum> ValidatedValues;
3629 
3630   // Define all the input DBG_PHI values in ValidatedValues.
3631   for (const auto &DBG_PHI : DBGPHIRange) {
3632     LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB);
3633     const ValueIDNum &Num = *DBG_PHI.ValueRead;
3634     ValidatedValues.insert(std::make_pair(Block, Num));
3635   }
3636 
3637   // Sort PHIs to validate into RPO-order.
3638   SmallVector<LDVSSAPhi *, 8> SortedPHIs;
3639   for (auto &PHI : CreatedPHIs)
3640     SortedPHIs.push_back(PHI);
3641 
3642   std::sort(
3643       SortedPHIs.begin(), SortedPHIs.end(), [&](LDVSSAPhi *A, LDVSSAPhi *B) {
3644         return BBToOrder[&A->getParent()->BB] < BBToOrder[&B->getParent()->BB];
3645       });
3646 
3647   for (auto &PHI : SortedPHIs) {
3648     ValueIDNum ThisBlockValueNum =
3649         MLiveIns[PHI->ParentBlock->BB.getNumber()][Loc.asU64()];
3650 
3651     // Are all these things actually defined?
3652     for (auto &PHIIt : PHI->IncomingValues) {
3653       // Any undef input means DBG_PHIs didn't dominate the use point.
3654       if (Updater.UndefMap.find(&PHIIt.first->BB) != Updater.UndefMap.end())
3655         return None;
3656 
3657       ValueIDNum ValueToCheck;
3658       const ValueTable &BlockLiveOuts = MLiveOuts[PHIIt.first->BB.getNumber()];
3659 
3660       auto VVal = ValidatedValues.find(PHIIt.first);
3661       if (VVal == ValidatedValues.end()) {
3662         // We cross a loop, and this is a backedge. LLVMs tail duplication
3663         // happens so late that DBG_PHI instructions should not be able to
3664         // migrate into loops -- meaning we can only be live-through this
3665         // loop.
3666         ValueToCheck = ThisBlockValueNum;
3667       } else {
3668         // Does the block have as a live-out, in the location we're examining,
3669         // the value that we expect? If not, it's been moved or clobbered.
3670         ValueToCheck = VVal->second;
3671       }
3672 
3673       if (BlockLiveOuts[Loc.asU64()] != ValueToCheck)
3674         return None;
3675     }
3676 
3677     // Record this value as validated.
3678     ValidatedValues.insert({PHI->ParentBlock, ThisBlockValueNum});
3679   }
3680 
3681   // All the PHIs are valid: we can return what the SSAUpdater said our value
3682   // number was.
3683   return Result;
3684 }
3685