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