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