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