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