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