1//===- InstrRefBasedImpl.cpp - Tracking Debug Value MIs -------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8/// \file InstrRefBasedImpl.cpp
9///
10/// This is a separate implementation of LiveDebugValues, see
11/// LiveDebugValues.cpp and VarLocBasedImpl.cpp for more information.
12///
13/// This pass propagates variable locations between basic blocks, resolving
14/// control flow conflicts between them. The problem is SSA construction, where
15/// each debug instruction assigns the *value* that a variable has, and every
16/// instruction where the variable is in scope uses that variable. The resulting
17/// map of instruction-to-value is then translated into a register (or spill)
18/// location for each variable over each instruction.
19///
20/// The primary difference from normal SSA construction is that we cannot
21/// _create_ PHI values that contain variable values. CodeGen has already
22/// completed, and we can't alter it just to make debug-info complete. Thus:
23/// we can identify function positions where we would like a PHI value for a
24/// variable, but must search the MachineFunction to see whether such a PHI is
25/// available. If no such PHI exists, the variable location must be dropped.
26///
27/// To achieve this, we perform two kinds of analysis. First, we identify
28/// every value defined by every instruction (ignoring those that only move
29/// another value), then re-compute an SSA-form representation of the
30/// MachineFunction, using value propagation to eliminate any un-necessary
31/// PHI values. This gives us a map of every value computed in the function,
32/// and its location within the register file / stack.
33///
34/// Secondly, for each variable we perform the same analysis, where each debug
35/// instruction is considered a def, and every instruction where the variable
36/// is in lexical scope as a use. Value propagation is used again to eliminate
37/// any un-necessary PHIs. This gives us a map of each variable to the value
38/// it should have in a block.
39///
40/// Once both are complete, we have two maps for each block:
41/// * Variables to the values they should have,
42/// * Values to the register / spill slot they are located in.
43/// After which we can marry-up variable values with a location, and emit
44/// DBG_VALUE instructions specifying those locations. Variable locations may
45/// be dropped in this process due to the desired variable value not being
46/// resident in any machine location, or because there is no PHI value in any
47/// location that accurately represents the desired value. The building of
48/// location lists for each block is left to DbgEntityHistoryCalculator.
49///
50/// This pass is kept efficient because the size of the first SSA problem
51/// is proportional to the working-set size of the function, which the compiler
52/// tries to keep small. (It's also proportional to the number of blocks).
53/// Additionally, we repeatedly perform the second SSA problem analysis with
54/// only the variables and blocks in a single lexical scope, exploiting their
55/// locality.
56///
57/// ### Terminology
58///
59/// A machine location is a register or spill slot, a value is something that's
60/// defined by an instruction or PHI node, while a variable value is the value
61/// assigned to a variable. A variable location is a machine location, that must
62/// contain the appropriate variable value. A value that is a PHI node is
63/// occasionally called an mphi.
64///
65/// The first SSA problem is the "machine value location" problem,
66/// because we're determining which machine locations contain which values.
67/// The "locations" are constant: what's unknown is what value they contain.
68///
69/// The second SSA problem (the one for variables) is the "variable value
70/// problem", because it's determining what values a variable has, rather than
71/// what location those values are placed in.
72///
73/// TODO:
74/// Overlapping fragments
75/// Entry values
76/// Add back DEBUG statements for debugging this
77/// Collect statistics
78///
79//===----------------------------------------------------------------------===//
80
81#include "llvm/ADT/DenseMap.h"
82#include "llvm/ADT/PostOrderIterator.h"
83#include "llvm/ADT/STLExtras.h"
84#include "llvm/ADT/SmallPtrSet.h"
85#include "llvm/ADT/SmallSet.h"
86#include "llvm/ADT/SmallVector.h"
87#include "llvm/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/TargetRegisterInfo.h"
103#include "llvm/CodeGen/TargetSubtargetInfo.h"
104#include "llvm/Config/llvm-config.h"
105#include "llvm/IR/DebugInfoMetadata.h"
106#include "llvm/IR/DebugLoc.h"
107#include "llvm/IR/Function.h"
108#include "llvm/MC/MCRegisterInfo.h"
109#include "llvm/Support/Casting.h"
110#include "llvm/Support/Compiler.h"
111#include "llvm/Support/Debug.h"
112#include "llvm/Support/GenericIteratedDominanceFrontier.h"
113#include "llvm/Support/TypeSize.h"
114#include "llvm/Support/raw_ostream.h"
115#include "llvm/Target/TargetMachine.h"
116#include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
117#include <algorithm>
118#include <cassert>
119#include <climits>
120#include <cstdint>
121#include <functional>
122#include <queue>
123#include <tuple>
124#include <utility>
125#include <vector>
126
127#include "InstrRefBasedImpl.h"
128#include "LiveDebugValues.h"
129#include <optional>
130
131using namespace llvm;
132using namespace LiveDebugValues;
133
134// SSAUpdaterImple sets DEBUG_TYPE, change it.
135#undef DEBUG_TYPE
136#define DEBUG_TYPE "livedebugvalues"
137
138// Act more like the VarLoc implementation, by propagating some locations too
139// far and ignoring some transfers.
140static cl::opt<bool> EmulateOldLDV("emulate-old-livedebugvalues", cl::Hidden,
141 cl::desc("Act like old LiveDebugValues did"),
142 cl::init(Val: false));
143
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.
153static cl::opt<unsigned>
154 StackWorkingSetLimit("livedebugvalues-max-stack-slots", cl::Hidden,
155 cl::desc("livedebugvalues-stack-ws-limit"),
156 cl::init(Val: 250));
157
158DbgOpID DbgOpID::UndefID = DbgOpID(0xffffffff);
159
160/// Tracker for converting machine value locations and variable values into
161/// variable locations (the output of LiveDebugValues), recorded as DBG_VALUEs
162/// specifying block live-in locations and transfers within blocks.
163///
164/// Operating on a per-block basis, this class takes a (pre-loaded) MLocTracker
165/// and must be initialized with the set of variable values that are live-in to
166/// the block. The caller then repeatedly calls process(). TransferTracker picks
167/// out variable locations for the live-in variable values (if there _is_ a
168/// location) and creates the corresponding DBG_VALUEs. Then, as the block is
169/// stepped through, transfers of values between machine locations are
170/// identified and if profitable, a DBG_VALUE created.
171///
172/// This is where debug use-before-defs would be resolved: a variable with an
173/// unavailable value could materialize in the middle of a block, when the
174/// value becomes available. Or, we could detect clobbers and re-specify the
175/// variable in a backup location. (XXX these are unimplemented).
176class TransferTracker {
177public:
178 const TargetInstrInfo *TII;
179 const TargetLowering *TLI;
180 /// This machine location tracker is assumed to always contain the up-to-date
181 /// value mapping for all machine locations. TransferTracker only reads
182 /// information from it. (XXX make it const?)
183 MLocTracker *MTracker;
184 MachineFunction &MF;
185 const DebugVariableMap &DVMap;
186 bool ShouldEmitDebugEntryValues;
187
188 /// Record of all changes in variable locations at a block position. Awkwardly
189 /// we allow inserting either before or after the point: MBB != nullptr
190 /// indicates it's before, otherwise after.
191 struct Transfer {
192 MachineBasicBlock::instr_iterator Pos; /// Position to insert DBG_VALUes
193 MachineBasicBlock *MBB; /// non-null if we should insert after.
194 /// Vector of DBG_VALUEs to insert. Store with their DebugVariableID so that
195 /// they can be sorted into a stable order for emission at a later time.
196 SmallVector<std::pair<DebugVariableID, MachineInstr *>, 4> Insts;
197 };
198
199 /// Stores the resolved operands (machine locations and constants) and
200 /// qualifying meta-information needed to construct a concrete DBG_VALUE-like
201 /// instruction.
202 struct ResolvedDbgValue {
203 SmallVector<ResolvedDbgOp> Ops;
204 DbgValueProperties Properties;
205
206 ResolvedDbgValue(SmallVectorImpl<ResolvedDbgOp> &Ops,
207 DbgValueProperties Properties)
208 : Ops(Ops.begin(), Ops.end()), Properties(Properties) {}
209
210 /// Returns all the LocIdx values used in this struct, in the order in which
211 /// they appear as operands in the debug value; may contain duplicates.
212 auto loc_indices() const {
213 return map_range(
214 C: make_filter_range(
215 Range: Ops, Pred: [](const ResolvedDbgOp &Op) { return !Op.IsConst; }),
216 F: [](const ResolvedDbgOp &Op) { return Op.Loc; });
217 }
218 };
219
220 /// Collection of transfers (DBG_VALUEs) to be inserted.
221 SmallVector<Transfer, 32> Transfers;
222
223 /// Local cache of what-value-is-in-what-LocIdx. Used to identify differences
224 /// between TransferTrackers view of variable locations and MLocTrackers. For
225 /// example, MLocTracker observes all clobbers, but TransferTracker lazily
226 /// does not.
227 SmallVector<ValueIDNum, 32> VarLocs;
228
229 /// Map from LocIdxes to which DebugVariables are based that location.
230 /// Mantained while stepping through the block. Not accurate if
231 /// VarLocs[Idx] != MTracker->LocIdxToIDNum[Idx].
232 DenseMap<LocIdx, SmallSet<DebugVariableID, 4>> ActiveMLocs;
233
234 /// Map from DebugVariable to it's current location and qualifying meta
235 /// information. To be used in conjunction with ActiveMLocs to construct
236 /// enough information for the DBG_VALUEs for a particular LocIdx.
237 DenseMap<DebugVariableID, ResolvedDbgValue> ActiveVLocs;
238
239 /// Temporary cache of DBG_VALUEs to be entered into the Transfers collection.
240 SmallVector<std::pair<DebugVariableID, MachineInstr *>, 4> PendingDbgValues;
241
242 /// Record of a use-before-def: created when a value that's live-in to the
243 /// current block isn't available in any machine location, but it will be
244 /// defined in this block.
245 struct UseBeforeDef {
246 /// Value of this variable, def'd in block.
247 SmallVector<DbgOp> Values;
248 /// Identity of this variable.
249 DebugVariableID VarID;
250 /// Additional variable properties.
251 DbgValueProperties Properties;
252 UseBeforeDef(ArrayRef<DbgOp> Values, DebugVariableID VarID,
253 const DbgValueProperties &Properties)
254 : Values(Values), VarID(VarID), Properties(Properties) {}
255 };
256
257 /// Map from instruction index (within the block) to the set of UseBeforeDefs
258 /// that become defined at that instruction.
259 DenseMap<unsigned, SmallVector<UseBeforeDef, 1>> UseBeforeDefs;
260
261 /// The set of variables that are in UseBeforeDefs and can become a location
262 /// once the relevant value is defined. An element being erased from this
263 /// collection prevents the use-before-def materializing.
264 DenseSet<DebugVariableID> UseBeforeDefVariables;
265
266 const TargetRegisterInfo &TRI;
267 const BitVector &CalleeSavedRegs;
268
269 TransferTracker(const TargetInstrInfo *TII, MLocTracker *MTracker,
270 MachineFunction &MF, const DebugVariableMap &DVMap,
271 const TargetRegisterInfo &TRI,
272 const BitVector &CalleeSavedRegs,
273 bool ShouldEmitDebugEntryValues)
274 : TII(TII), MTracker(MTracker), MF(MF), DVMap(DVMap), TRI(TRI),
275 CalleeSavedRegs(CalleeSavedRegs) {
276 TLI = MF.getSubtarget().getTargetLowering();
277 this->ShouldEmitDebugEntryValues = ShouldEmitDebugEntryValues;
278 }
279
280 bool isCalleeSaved(LocIdx L) const {
281 unsigned Reg = MTracker->LocIdxToLocID[L];
282 if (Reg >= MTracker->NumRegs)
283 return false;
284 for (MCRegAliasIterator RAI(Reg, &TRI, true); RAI.isValid(); ++RAI)
285 if (CalleeSavedRegs.test(Idx: (*RAI).id()))
286 return true;
287 return false;
288 };
289
290 // An estimate of the expected lifespan of values at a machine location, with
291 // a greater value corresponding to a longer expected lifespan, i.e. spill
292 // slots generally live longer than callee-saved registers which generally
293 // live longer than non-callee-saved registers. The minimum value of 0
294 // corresponds to an illegal location that cannot have a "lifespan" at all.
295 enum class LocationQuality : unsigned char {
296 Illegal = 0,
297 Register,
298 CalleeSavedRegister,
299 SpillSlot,
300 Best = SpillSlot
301 };
302
303 class LocationAndQuality {
304 unsigned Location : 24;
305 unsigned Quality : 8;
306
307 public:
308 LocationAndQuality() : Location(0), Quality(0) {}
309 LocationAndQuality(LocIdx L, LocationQuality Q)
310 : Location(L.asU64()), Quality(static_cast<unsigned>(Q)) {}
311 LocIdx getLoc() const {
312 if (!Quality)
313 return LocIdx::MakeIllegalLoc();
314 return LocIdx(Location);
315 }
316 LocationQuality getQuality() const { return LocationQuality(Quality); }
317 bool isIllegal() const { return !Quality; }
318 bool isBest() const { return getQuality() == LocationQuality::Best; }
319 };
320
321 using ValueLocPair = std::pair<ValueIDNum, LocationAndQuality>;
322
323 static inline bool ValueToLocSort(const ValueLocPair &A,
324 const ValueLocPair &B) {
325 return A.first < B.first;
326 };
327
328 // Returns the LocationQuality for the location L iff the quality of L is
329 // is strictly greater than the provided minimum quality.
330 std::optional<LocationQuality>
331 getLocQualityIfBetter(LocIdx L, LocationQuality Min) const {
332 if (L.isIllegal())
333 return std::nullopt;
334 if (Min >= LocationQuality::SpillSlot)
335 return std::nullopt;
336 if (MTracker->isSpill(Idx: L))
337 return LocationQuality::SpillSlot;
338 if (Min >= LocationQuality::CalleeSavedRegister)
339 return std::nullopt;
340 if (isCalleeSaved(L))
341 return LocationQuality::CalleeSavedRegister;
342 if (Min >= LocationQuality::Register)
343 return std::nullopt;
344 return LocationQuality::Register;
345 }
346
347 /// For a variable \p Var with the live-in value \p Value, attempts to resolve
348 /// the DbgValue to a concrete DBG_VALUE, emitting that value and loading the
349 /// tracking information to track Var throughout the block.
350 /// \p ValueToLoc is a map containing the best known location for every
351 /// ValueIDNum that Value may use.
352 /// \p MBB is the basic block that we are loading the live-in value for.
353 /// \p DbgOpStore is the map containing the DbgOpID->DbgOp mapping needed to
354 /// determine the values used by Value.
355 void loadVarInloc(MachineBasicBlock &MBB, DbgOpIDMap &DbgOpStore,
356 const SmallVectorImpl<ValueLocPair> &ValueToLoc,
357 DebugVariableID VarID, DbgValue Value) {
358 SmallVector<DbgOp> DbgOps;
359 SmallVector<ResolvedDbgOp> ResolvedDbgOps;
360 bool IsValueValid = true;
361 unsigned LastUseBeforeDef = 0;
362 bool DbgLocAvailableAndIsEntryVal = false;
363
364 // If every value used by the incoming DbgValue is available at block
365 // entry, ResolvedDbgOps will contain the machine locations/constants for
366 // those values and will be used to emit a debug location.
367 // If one or more values are not yet available, but will all be defined in
368 // this block, then LastUseBeforeDef will track the instruction index in
369 // this BB at which the last of those values is defined, DbgOps will
370 // contain the values that we will emit when we reach that instruction.
371 // If one or more values are undef or not available throughout this block,
372 // and we can't recover as an entry value, we set IsValueValid=false and
373 // skip this variable.
374 for (DbgOpID ID : Value.getDbgOpIDs()) {
375 DbgOp Op = DbgOpStore.find(ID);
376 DbgOps.push_back(Elt: Op);
377 if (ID.isUndef()) {
378 IsValueValid = false;
379 break;
380 }
381 if (ID.isConst()) {
382 ResolvedDbgOps.push_back(Elt: Op.MO);
383 continue;
384 }
385
386 // Search for the desired ValueIDNum, to examine the best location found
387 // for it. Use an empty ValueLocPair to search for an entry in ValueToLoc.
388 const ValueIDNum &Num = Op.ID;
389 ValueLocPair Probe(Num, LocationAndQuality());
390 auto ValuesPreferredLoc =
391 llvm::lower_bound(Range: ValueToLoc, Value&: Probe, C: ValueToLocSort);
392
393 // There must be a legitimate entry found for Num.
394 assert(ValuesPreferredLoc != ValueToLoc.end() &&
395 ValuesPreferredLoc->first == Num);
396
397 if (ValuesPreferredLoc->second.isIllegal()) {
398 // If it's a def that occurs in this block, register it as a
399 // use-before-def to be resolved as we step through the block.
400 // Continue processing values so that we add any other UseBeforeDef
401 // entries needed for later.
402 if (Num.getBlock() == (unsigned)MBB.getNumber() && !Num.isPHI()) {
403 LastUseBeforeDef = std::max(a: LastUseBeforeDef,
404 b: static_cast<unsigned>(Num.getInst()));
405 continue;
406 }
407 recoverAsEntryValue(VarID, Prop: Value.Properties, Num);
408 IsValueValid = false;
409 break;
410 }
411
412 // Defer modifying ActiveVLocs until after we've confirmed we have a
413 // live range.
414 LocIdx M = ValuesPreferredLoc->second.getLoc();
415 ResolvedDbgOps.push_back(Elt: M);
416 if (Value.Properties.DIExpr->isEntryValue())
417 DbgLocAvailableAndIsEntryVal = true;
418 }
419
420 // If we cannot produce a valid value for the LiveIn value within this
421 // block, skip this variable.
422 if (!IsValueValid)
423 return;
424
425 // Add UseBeforeDef entry for the last value to be defined in this block.
426 if (LastUseBeforeDef) {
427 addUseBeforeDef(VarID, Properties: Value.Properties, DbgOps, Inst: LastUseBeforeDef);
428 return;
429 }
430
431 auto &[Var, DILoc] = DVMap.lookupDVID(ID: VarID);
432 PendingDbgValues.push_back(
433 Elt: std::make_pair(x&: VarID, y: &*MTracker->emitLoc(DbgOps: ResolvedDbgOps, Var, DILoc,
434 Properties: Value.Properties)));
435
436 // If the location is available at block entry and is an entry value, skip
437 // tracking and recording thr transfer.
438 if (DbgLocAvailableAndIsEntryVal)
439 return;
440
441 // The LiveIn value is available at block entry, begin tracking and record
442 // the transfer.
443 for (const ResolvedDbgOp &Op : ResolvedDbgOps)
444 if (!Op.IsConst)
445 ActiveMLocs[Op.Loc].insert(V: VarID);
446 auto NewValue = ResolvedDbgValue{ResolvedDbgOps, Value.Properties};
447 ActiveVLocs.insert_or_assign(Key: VarID, Val: std::move(NewValue));
448 }
449
450 /// Load object with live-in variable values. \p mlocs contains the live-in
451 /// values in each machine location, while \p vlocs the live-in variable
452 /// values. This method picks variable locations for the live-in variables,
453 /// creates DBG_VALUEs and puts them in #Transfers, then prepares the other
454 /// object fields to track variable locations as we step through the block.
455 /// FIXME: could just examine mloctracker instead of passing in \p mlocs?
456 void
457 loadInlocs(MachineBasicBlock &MBB, ValueTable &MLocs, DbgOpIDMap &DbgOpStore,
458 const SmallVectorImpl<std::pair<DebugVariableID, DbgValue>> &VLocs,
459 unsigned NumLocs) {
460 ActiveMLocs.clear();
461 ActiveVLocs.clear();
462 VarLocs.clear();
463 VarLocs.reserve(N: NumLocs);
464 UseBeforeDefs.clear();
465 UseBeforeDefVariables.clear();
466
467 // Mapping of the preferred locations for each value. Collected into this
468 // vector then sorted for easy searching.
469 SmallVector<ValueLocPair, 16> ValueToLoc;
470
471 // Initialized the preferred-location map with illegal locations, to be
472 // filled in later.
473 for (const auto &VLoc : VLocs)
474 if (VLoc.second.Kind == DbgValue::Def)
475 for (DbgOpID OpID : VLoc.second.getDbgOpIDs())
476 if (!OpID.ID.IsConst)
477 ValueToLoc.push_back(
478 Elt: {DbgOpStore.find(ID: OpID).ID, LocationAndQuality()});
479
480 llvm::sort(C&: ValueToLoc, Comp: ValueToLocSort);
481 ActiveMLocs.reserve(NumEntries: VLocs.size());
482 ActiveVLocs.reserve(NumEntries: VLocs.size());
483
484 // Produce a map of value numbers to the current machine locs they live
485 // in. When emulating VarLocBasedImpl, there should only be one
486 // location; when not, we get to pick.
487 for (auto Location : MTracker->locations()) {
488 LocIdx Idx = Location.Idx;
489 ValueIDNum &VNum = MLocs[Idx.asU64()];
490 if (VNum == ValueIDNum::EmptyValue)
491 continue;
492 VarLocs.push_back(Elt: VNum);
493
494 // Is there a variable that wants a location for this value? If not, skip.
495 ValueLocPair Probe(VNum, LocationAndQuality());
496 auto VIt = llvm::lower_bound(Range&: ValueToLoc, Value&: Probe, C: ValueToLocSort);
497 if (VIt == ValueToLoc.end() || VIt->first != VNum)
498 continue;
499
500 auto &Previous = VIt->second;
501 // If this is the first location with that value, pick it. Otherwise,
502 // consider whether it's a "longer term" location.
503 std::optional<LocationQuality> ReplacementQuality =
504 getLocQualityIfBetter(L: Idx, Min: Previous.getQuality());
505 if (ReplacementQuality)
506 Previous = LocationAndQuality(Idx, *ReplacementQuality);
507 }
508
509 // Now map variables to their picked LocIdxes.
510 for (const auto &Var : VLocs) {
511 loadVarInloc(MBB, DbgOpStore, ValueToLoc, VarID: Var.first, Value: Var.second);
512 }
513 flushDbgValues(Pos: MBB.begin(), MBB: &MBB);
514 }
515
516 /// Record that \p Var has value \p ID, a value that becomes available
517 /// later in the function.
518 void addUseBeforeDef(DebugVariableID VarID,
519 const DbgValueProperties &Properties,
520 const SmallVectorImpl<DbgOp> &DbgOps, unsigned Inst) {
521 UseBeforeDefs[Inst].emplace_back(Args: DbgOps, Args&: VarID, Args: Properties);
522 UseBeforeDefVariables.insert(V: VarID);
523 }
524
525 /// After the instruction at index \p Inst and position \p pos has been
526 /// processed, check whether it defines a variable value in a use-before-def.
527 /// If so, and the variable value hasn't changed since the start of the
528 /// block, create a DBG_VALUE.
529 void checkInstForNewValues(unsigned Inst, MachineBasicBlock::iterator pos) {
530 auto MIt = UseBeforeDefs.find(Val: Inst);
531 if (MIt == UseBeforeDefs.end())
532 return;
533
534 // Map of values to the locations that store them for every value used by
535 // the variables that may have become available.
536 SmallDenseMap<ValueIDNum, LocationAndQuality> ValueToLoc;
537
538 // Populate ValueToLoc with illegal default mappings for every value used by
539 // any UseBeforeDef variables for this instruction.
540 for (auto &Use : MIt->second) {
541 if (!UseBeforeDefVariables.count(V: Use.VarID))
542 continue;
543
544 for (DbgOp &Op : Use.Values) {
545 assert(!Op.isUndef() && "UseBeforeDef erroneously created for a "
546 "DbgValue with undef values.");
547 if (Op.IsConst)
548 continue;
549
550 ValueToLoc.insert(KV: {Op.ID, LocationAndQuality()});
551 }
552 }
553
554 // Exit early if we have no DbgValues to produce.
555 if (ValueToLoc.empty())
556 return;
557
558 // Determine the best location for each desired value.
559 for (auto Location : MTracker->locations()) {
560 LocIdx Idx = Location.Idx;
561 ValueIDNum &LocValueID = Location.Value;
562
563 // Is there a variable that wants a location for this value? If not, skip.
564 auto VIt = ValueToLoc.find(Val: LocValueID);
565 if (VIt == ValueToLoc.end())
566 continue;
567
568 auto &Previous = VIt->second;
569 // If this is the first location with that value, pick it. Otherwise,
570 // consider whether it's a "longer term" location.
571 std::optional<LocationQuality> ReplacementQuality =
572 getLocQualityIfBetter(L: Idx, Min: Previous.getQuality());
573 if (ReplacementQuality)
574 Previous = LocationAndQuality(Idx, *ReplacementQuality);
575 }
576
577 // Using the map of values to locations, produce a final set of values for
578 // this variable.
579 for (auto &Use : MIt->second) {
580 if (!UseBeforeDefVariables.count(V: Use.VarID))
581 continue;
582
583 SmallVector<ResolvedDbgOp> DbgOps;
584
585 for (DbgOp &Op : Use.Values) {
586 if (Op.IsConst) {
587 DbgOps.push_back(Elt: Op.MO);
588 continue;
589 }
590 LocIdx NewLoc = ValueToLoc.find(Val: Op.ID)->second.getLoc();
591 if (NewLoc.isIllegal())
592 break;
593 DbgOps.push_back(Elt: NewLoc);
594 }
595
596 // If at least one value used by this debug value is no longer available,
597 // i.e. one of the values was killed before we finished defining all of
598 // the values used by this variable, discard.
599 if (DbgOps.size() != Use.Values.size())
600 continue;
601
602 // Otherwise, we're good to go.
603 auto &[Var, DILoc] = DVMap.lookupDVID(ID: Use.VarID);
604 PendingDbgValues.push_back(Elt: std::make_pair(
605 x&: Use.VarID, y: MTracker->emitLoc(DbgOps, Var, DILoc, Properties: Use.Properties)));
606 }
607 flushDbgValues(Pos: pos, MBB: nullptr);
608 }
609
610 /// Helper to move created DBG_VALUEs into Transfers collection.
611 void flushDbgValues(MachineBasicBlock::iterator Pos, MachineBasicBlock *MBB) {
612 if (PendingDbgValues.size() == 0)
613 return;
614
615 // Pick out the instruction start position.
616 MachineBasicBlock::instr_iterator BundleStart;
617 if (MBB && Pos == MBB->begin())
618 BundleStart = MBB->instr_begin();
619 else
620 BundleStart = getBundleStart(I: Pos->getIterator());
621
622 Transfers.push_back(Elt: {.Pos: BundleStart, .MBB: MBB, .Insts: PendingDbgValues});
623 PendingDbgValues.clear();
624 }
625
626 bool isEntryValueVariable(const DebugVariable &Var,
627 const DIExpression *Expr) const {
628 if (!Var.getVariable()->isParameter())
629 return false;
630
631 if (Var.getInlinedAt())
632 return false;
633
634 if (Expr->getNumElements() > 0 && !Expr->isDeref())
635 return false;
636
637 return true;
638 }
639
640 bool isEntryValueValue(const ValueIDNum &Val) const {
641 // Must be in entry block (block number zero), and be a PHI / live-in value.
642 if (Val.getBlock() || !Val.isPHI())
643 return false;
644
645 // Entry values must enter in a register.
646 if (MTracker->isSpill(Idx: Val.getLoc()))
647 return false;
648
649 Register SP = TLI->getStackPointerRegisterToSaveRestore();
650 Register FP = TRI.getFrameRegister(MF);
651 Register Reg = MTracker->LocIdxToLocID[Val.getLoc()];
652 return Reg != SP && Reg != FP;
653 }
654
655 bool recoverAsEntryValue(DebugVariableID VarID,
656 const DbgValueProperties &Prop,
657 const ValueIDNum &Num) {
658 // Is this variable location a candidate to be an entry value. First,
659 // should we be trying this at all?
660 if (!ShouldEmitDebugEntryValues)
661 return false;
662
663 const DIExpression *DIExpr = Prop.DIExpr;
664
665 // We don't currently emit entry values for DBG_VALUE_LISTs.
666 if (Prop.IsVariadic) {
667 // If this debug value can be converted to be non-variadic, then do so;
668 // otherwise give up.
669 auto NonVariadicExpression =
670 DIExpression::convertToNonVariadicExpression(Expr: DIExpr);
671 if (!NonVariadicExpression)
672 return false;
673 DIExpr = *NonVariadicExpression;
674 }
675
676 auto &[Var, DILoc] = DVMap.lookupDVID(ID: VarID);
677
678 // If the expression is a DW_OP_entry_value, emit the variable location
679 // as-is.
680 if (DIExpr->isEntryValue()) {
681 Register Reg = MTracker->LocIdxToLocID[Num.getLoc()];
682 MachineOperand MO = MachineOperand::CreateReg(Reg, isDef: false);
683 PendingDbgValues.push_back(Elt: std::make_pair(
684 x&: VarID, y: &*emitMOLoc(MO, Var, Properties: {DIExpr, Prop.Indirect, false})));
685 return true;
686 }
687
688 // Is the variable appropriate for entry values (i.e., is a parameter).
689 if (!isEntryValueVariable(Var, Expr: DIExpr))
690 return false;
691
692 // Is the value assigned to this variable still the entry value?
693 if (!isEntryValueValue(Val: Num))
694 return false;
695
696 // Emit a variable location using an entry value expression.
697 DIExpression *NewExpr =
698 DIExpression::prepend(Expr: DIExpr, Flags: DIExpression::EntryValue);
699 Register Reg = MTracker->LocIdxToLocID[Num.getLoc()];
700 MachineOperand MO = MachineOperand::CreateReg(Reg, isDef: false);
701 PendingDbgValues.push_back(Elt: std::make_pair(
702 x&: VarID, y: &*emitMOLoc(MO, Var, Properties: {NewExpr, Prop.Indirect, false})));
703 return true;
704 }
705
706 /// Change a variable value after encountering a DBG_VALUE inside a block.
707 void redefVar(const MachineInstr &MI) {
708 DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
709 MI.getDebugLoc()->getInlinedAt());
710 DbgValueProperties Properties(MI);
711 DebugVariableID VarID = DVMap.getDVID(Var);
712
713 // Ignore non-register locations, we don't transfer those.
714 if (MI.isUndefDebugValue() || MI.getDebugExpression()->isEntryValue() ||
715 all_of(Range: MI.debug_operands(),
716 P: [](const MachineOperand &MO) { return !MO.isReg(); })) {
717 auto It = ActiveVLocs.find(Val: VarID);
718 if (It != ActiveVLocs.end()) {
719 for (LocIdx Loc : It->second.loc_indices())
720 ActiveMLocs[Loc].erase(V: VarID);
721 ActiveVLocs.erase(I: It);
722 }
723 // Any use-before-defs no longer apply.
724 UseBeforeDefVariables.erase(V: VarID);
725 return;
726 }
727
728 SmallVector<ResolvedDbgOp> NewLocs;
729 for (const MachineOperand &MO : MI.debug_operands()) {
730 if (MO.isReg()) {
731 // Any undef regs have already been filtered out above.
732 Register Reg = MO.getReg();
733 LocIdx NewLoc = MTracker->getRegMLoc(R: Reg);
734 NewLocs.push_back(Elt: NewLoc);
735 } else {
736 NewLocs.push_back(Elt: MO);
737 }
738 }
739
740 redefVar(MI, Properties, NewLocs);
741 }
742
743 /// Handle a change in variable location within a block. Terminate the
744 /// variables current location, and record the value it now refers to, so
745 /// that we can detect location transfers later on.
746 void redefVar(const MachineInstr &MI, const DbgValueProperties &Properties,
747 SmallVectorImpl<ResolvedDbgOp> &NewLocs) {
748 DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(),
749 MI.getDebugLoc()->getInlinedAt());
750 DebugVariableID VarID = DVMap.getDVID(Var);
751 // Any use-before-defs no longer apply.
752 UseBeforeDefVariables.erase(V: VarID);
753
754 // Erase any previous location.
755 auto It = ActiveVLocs.find(Val: VarID);
756 if (It != ActiveVLocs.end()) {
757 for (LocIdx Loc : It->second.loc_indices())
758 ActiveMLocs[Loc].erase(V: VarID);
759 }
760
761 // If there _is_ no new location, all we had to do was erase.
762 if (NewLocs.empty()) {
763 if (It != ActiveVLocs.end())
764 ActiveVLocs.erase(I: It);
765 return;
766 }
767
768 SmallVector<std::pair<LocIdx, DebugVariableID>> LostMLocs;
769 for (ResolvedDbgOp &Op : NewLocs) {
770 if (Op.IsConst)
771 continue;
772
773 LocIdx NewLoc = Op.Loc;
774
775 // Check whether our local copy of values-by-location in #VarLocs is out
776 // of date. Wipe old tracking data for the location if it's been clobbered
777 // in the meantime.
778 if (MTracker->readMLoc(L: NewLoc) != VarLocs[NewLoc.asU64()]) {
779 for (const auto &P : ActiveMLocs[NewLoc]) {
780 auto LostVLocIt = ActiveVLocs.find(Val: P);
781 if (LostVLocIt != ActiveVLocs.end()) {
782 for (LocIdx Loc : LostVLocIt->second.loc_indices()) {
783 // Every active variable mapping for NewLoc will be cleared, no
784 // need to track individual variables.
785 if (Loc == NewLoc)
786 continue;
787 LostMLocs.emplace_back(Args&: Loc, Args: P);
788 }
789 }
790 ActiveVLocs.erase(Val: P);
791 }
792 for (const auto &LostMLoc : LostMLocs)
793 ActiveMLocs[LostMLoc.first].erase(V: LostMLoc.second);
794 LostMLocs.clear();
795 It = ActiveVLocs.find(Val: VarID);
796 ActiveMLocs[NewLoc.asU64()].clear();
797 VarLocs[NewLoc.asU64()] = MTracker->readMLoc(L: NewLoc);
798 }
799
800 ActiveMLocs[NewLoc].insert(V: VarID);
801 }
802
803 if (It == ActiveVLocs.end()) {
804 ActiveVLocs.insert(
805 KV: std::make_pair(x&: VarID, y: ResolvedDbgValue(NewLocs, Properties)));
806 } else {
807 It->second.Ops.assign(RHS: NewLocs);
808 It->second.Properties = Properties;
809 }
810 }
811
812 /// Account for a location \p mloc being clobbered. Examine the variable
813 /// locations that will be terminated: and try to recover them by using
814 /// another location. Optionally, given \p MakeUndef, emit a DBG_VALUE to
815 /// explicitly terminate a location if it can't be recovered.
816 void clobberMloc(LocIdx MLoc, MachineBasicBlock::iterator Pos,
817 bool MakeUndef = true) {
818 auto ActiveMLocIt = ActiveMLocs.find(Val: MLoc);
819 if (ActiveMLocIt == ActiveMLocs.end())
820 return;
821
822 // What was the old variable value?
823 ValueIDNum OldValue = VarLocs[MLoc.asU64()];
824 clobberMloc(MLoc, OldValue, Pos, MakeUndef);
825 }
826 /// Overload that takes an explicit value \p OldValue for when the value in
827 /// \p MLoc has changed and the TransferTracker's locations have not been
828 /// updated yet.
829 void clobberMloc(LocIdx MLoc, ValueIDNum OldValue,
830 MachineBasicBlock::iterator Pos, bool MakeUndef = true) {
831 auto ActiveMLocIt = ActiveMLocs.find(Val: MLoc);
832 if (ActiveMLocIt == ActiveMLocs.end())
833 return;
834
835 VarLocs[MLoc.asU64()] = ValueIDNum::EmptyValue;
836
837 // Examine the remaining variable locations: if we can find the same value
838 // again, we can recover the location.
839 std::optional<LocIdx> NewLoc;
840 for (auto Loc : MTracker->locations())
841 if (Loc.Value == OldValue)
842 NewLoc = Loc.Idx;
843
844 // If there is no location, and we weren't asked to make the variable
845 // explicitly undef, then stop here.
846 if (!NewLoc && !MakeUndef) {
847 // Try and recover a few more locations with entry values.
848 for (DebugVariableID VarID : ActiveMLocIt->second) {
849 auto &Prop = ActiveVLocs.find(Val: VarID)->second.Properties;
850 recoverAsEntryValue(VarID, Prop, Num: OldValue);
851 }
852 flushDbgValues(Pos, MBB: nullptr);
853 return;
854 }
855
856 // Examine all the variables based on this location.
857 DenseSet<DebugVariableID> NewMLocs;
858 // If no new location has been found, every variable that depends on this
859 // MLoc is dead, so end their existing MLoc->Var mappings as well.
860 SmallVector<std::pair<LocIdx, DebugVariableID>> LostMLocs;
861 for (DebugVariableID VarID : ActiveMLocIt->second) {
862 auto ActiveVLocIt = ActiveVLocs.find(Val: VarID);
863 // Re-state the variable location: if there's no replacement then NewLoc
864 // is std::nullopt and a $noreg DBG_VALUE will be created. Otherwise, a
865 // DBG_VALUE identifying the alternative location will be emitted.
866 const DbgValueProperties &Properties = ActiveVLocIt->second.Properties;
867
868 // Produce the new list of debug ops - an empty list if no new location
869 // was found, or the existing list with the substitution MLoc -> NewLoc
870 // otherwise.
871 SmallVector<ResolvedDbgOp> DbgOps;
872 if (NewLoc) {
873 ResolvedDbgOp OldOp(MLoc);
874 ResolvedDbgOp NewOp(*NewLoc);
875 // Insert illegal ops to overwrite afterwards.
876 DbgOps.insert(I: DbgOps.begin(), NumToInsert: ActiveVLocIt->second.Ops.size(),
877 Elt: ResolvedDbgOp(LocIdx::MakeIllegalLoc()));
878 replace_copy(Range&: ActiveVLocIt->second.Ops, Out: DbgOps.begin(), OldValue: OldOp, NewValue: NewOp);
879 }
880
881 auto &[Var, DILoc] = DVMap.lookupDVID(ID: VarID);
882 PendingDbgValues.push_back(Elt: std::make_pair(
883 x&: VarID, y: &*MTracker->emitLoc(DbgOps, Var, DILoc, Properties)));
884
885 // Update machine locations <=> variable locations maps. Defer updating
886 // ActiveMLocs to avoid invalidating the ActiveMLocIt iterator.
887 if (!NewLoc) {
888 for (LocIdx Loc : ActiveVLocIt->second.loc_indices()) {
889 if (Loc != MLoc)
890 LostMLocs.emplace_back(Args&: Loc, Args&: VarID);
891 }
892 ActiveVLocs.erase(I: ActiveVLocIt);
893 } else {
894 ActiveVLocIt->second.Ops = DbgOps;
895 NewMLocs.insert(V: VarID);
896 }
897 }
898
899 // Remove variables from ActiveMLocs if they no longer use any other MLocs
900 // due to being killed by this clobber.
901 for (auto &LocVarIt : LostMLocs) {
902 auto LostMLocIt = ActiveMLocs.find(Val: LocVarIt.first);
903 assert(LostMLocIt != ActiveMLocs.end() &&
904 "Variable was using this MLoc, but ActiveMLocs[MLoc] has no "
905 "entries?");
906 LostMLocIt->second.erase(V: LocVarIt.second);
907 }
908
909 // We lazily track what locations have which values; if we've found a new
910 // location for the clobbered value, remember it.
911 if (NewLoc)
912 VarLocs[NewLoc->asU64()] = OldValue;
913
914 flushDbgValues(Pos, MBB: nullptr);
915
916 // Commit ActiveMLoc changes.
917 ActiveMLocIt->second.clear();
918 if (!NewMLocs.empty())
919 ActiveMLocs[*NewLoc].insert_range(R&: NewMLocs);
920 }
921
922 /// Transfer variables based on \p Src to be based on \p Dst. This handles
923 /// both register copies as well as spills and restores. Creates DBG_VALUEs
924 /// describing the movement.
925 void transferMlocs(LocIdx Src, LocIdx Dst, MachineBasicBlock::iterator Pos) {
926 // Does Src still contain the value num we expect? If not, it's been
927 // clobbered in the meantime, and our variable locations are stale.
928 if (VarLocs[Src.asU64()] != MTracker->readMLoc(L: Src))
929 return;
930
931 // assert(ActiveMLocs[Dst].size() == 0);
932 //^^^ Legitimate scenario on account of un-clobbered slot being assigned to?
933
934 // Move set of active variables from one location to another.
935 auto MovingVars = ActiveMLocs[Src];
936 ActiveMLocs[Dst].insert_range(R&: MovingVars);
937 VarLocs[Dst.asU64()] = VarLocs[Src.asU64()];
938
939 // For each variable based on Src; create a location at Dst.
940 ResolvedDbgOp SrcOp(Src);
941 ResolvedDbgOp DstOp(Dst);
942 for (DebugVariableID VarID : MovingVars) {
943 auto ActiveVLocIt = ActiveVLocs.find(Val: VarID);
944 assert(ActiveVLocIt != ActiveVLocs.end());
945
946 // Update all instances of Src in the variable's tracked values to Dst.
947 llvm::replace(Range&: ActiveVLocIt->second.Ops, OldValue: SrcOp, NewValue: DstOp);
948
949 auto &[Var, DILoc] = DVMap.lookupDVID(ID: VarID);
950 MachineInstr *MI = MTracker->emitLoc(DbgOps: ActiveVLocIt->second.Ops, Var, DILoc,
951 Properties: ActiveVLocIt->second.Properties);
952 PendingDbgValues.push_back(Elt: std::make_pair(x&: VarID, y&: MI));
953 }
954 ActiveMLocs[Src].clear();
955 flushDbgValues(Pos, MBB: nullptr);
956
957 // XXX XXX XXX "pretend to be old LDV" means dropping all tracking data
958 // about the old location.
959 if (EmulateOldLDV)
960 VarLocs[Src.asU64()] = ValueIDNum::EmptyValue;
961 }
962
963 MachineInstrBuilder emitMOLoc(const MachineOperand &MO,
964 const DebugVariable &Var,
965 const DbgValueProperties &Properties) {
966 DebugLoc DL = DILocation::get(Context&: Var.getVariable()->getContext(), Line: 0, Column: 0,
967 Scope: Var.getVariable()->getScope(),
968 InlinedAt: const_cast<DILocation *>(Var.getInlinedAt()));
969 auto MIB = BuildMI(MF, MIMD: DL, MCID: TII->get(Opcode: TargetOpcode::DBG_VALUE));
970 MIB.add(MO);
971 if (Properties.Indirect)
972 MIB.addImm(Val: 0);
973 else
974 MIB.addReg(RegNo: 0);
975 MIB.addMetadata(MD: Var.getVariable());
976 MIB.addMetadata(MD: Properties.DIExpr);
977 return MIB;
978 }
979};
980
981//===----------------------------------------------------------------------===//
982// Implementation
983//===----------------------------------------------------------------------===//
984
985ValueIDNum ValueIDNum::EmptyValue = {UINT_MAX, UINT_MAX, UINT_MAX};
986ValueIDNum ValueIDNum::TombstoneValue = {UINT_MAX, UINT_MAX, UINT_MAX - 1};
987
988#ifndef NDEBUG
989void ResolvedDbgOp::dump(const MLocTracker *MTrack) const {
990 if (IsConst) {
991 dbgs() << MO;
992 } else {
993 dbgs() << MTrack->LocIdxToName(Loc);
994 }
995}
996void DbgOp::dump(const MLocTracker *MTrack) const {
997 if (IsConst) {
998 dbgs() << MO;
999 } else if (!isUndef()) {
1000 dbgs() << MTrack->IDAsString(ID);
1001 }
1002}
1003void DbgOpID::dump(const MLocTracker *MTrack, const DbgOpIDMap *OpStore) const {
1004 if (!OpStore) {
1005 dbgs() << "ID(" << asU32() << ")";
1006 } else {
1007 OpStore->find(*this).dump(MTrack);
1008 }
1009}
1010void DbgValue::dump(const MLocTracker *MTrack,
1011 const DbgOpIDMap *OpStore) const {
1012 if (Kind == NoVal) {
1013 dbgs() << "NoVal(" << BlockNo << ")";
1014 } else if (Kind == VPHI || Kind == Def) {
1015 if (Kind == VPHI)
1016 dbgs() << "VPHI(" << BlockNo << ",";
1017 else
1018 dbgs() << "Def(";
1019 for (unsigned Idx = 0; Idx < getDbgOpIDs().size(); ++Idx) {
1020 getDbgOpID(Idx).dump(MTrack, OpStore);
1021 if (Idx != 0)
1022 dbgs() << ",";
1023 }
1024 dbgs() << ")";
1025 }
1026 if (Properties.Indirect)
1027 dbgs() << " indir";
1028 if (Properties.DIExpr)
1029 dbgs() << " " << *Properties.DIExpr;
1030}
1031#endif
1032
1033MLocTracker::MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII,
1034 const TargetRegisterInfo &TRI,
1035 const TargetLowering &TLI)
1036 : MF(MF), TII(TII), TRI(TRI), TLI(TLI),
1037 LocIdxToIDNum(ValueIDNum::EmptyValue), LocIdxToLocID(0) {
1038 NumRegs = TRI.getNumRegs();
1039 reset();
1040 LocIDToLocIdx.resize(new_size: NumRegs, x: LocIdx::MakeIllegalLoc());
1041 assert(NumRegs < (1u << NUM_LOC_BITS)); // Detect bit packing failure
1042
1043 // Always track SP. This avoids the implicit clobbering caused by regmasks
1044 // from affectings its values. (LiveDebugValues disbelieves calls and
1045 // regmasks that claim to clobber SP).
1046 Register SP = TLI.getStackPointerRegisterToSaveRestore();
1047 if (SP) {
1048 unsigned ID = getLocID(Reg: SP);
1049 (void)lookupOrTrackRegister(ID);
1050
1051 for (MCRegAliasIterator RAI(SP, &TRI, true); RAI.isValid(); ++RAI)
1052 SPAliases.insert(V: *RAI);
1053 }
1054
1055 // Build some common stack positions -- full registers being spilt to the
1056 // stack.
1057 StackSlotIdxes.insert(KV: {{8, 0}, 0});
1058 StackSlotIdxes.insert(KV: {{16, 0}, 1});
1059 StackSlotIdxes.insert(KV: {{32, 0}, 2});
1060 StackSlotIdxes.insert(KV: {{64, 0}, 3});
1061 StackSlotIdxes.insert(KV: {{128, 0}, 4});
1062 StackSlotIdxes.insert(KV: {{256, 0}, 5});
1063 StackSlotIdxes.insert(KV: {{512, 0}, 6});
1064
1065 // Traverse all the subregister idxes, and ensure there's an index for them.
1066 // Duplicates are no problem: we're interested in their position in the
1067 // stack slot, we don't want to type the slot.
1068 for (unsigned int I = 1; I < TRI.getNumSubRegIndices(); ++I) {
1069 unsigned Size = TRI.getSubRegIdxSize(Idx: I);
1070 unsigned Offs = TRI.getSubRegIdxOffset(Idx: I);
1071 unsigned Idx = StackSlotIdxes.size();
1072
1073 // Some subregs have -1, -2 and so forth fed into their fields, to mean
1074 // special backend things. Ignore those.
1075 if (Size > 60000 || Offs > 60000)
1076 continue;
1077
1078 StackSlotIdxes.insert(KV: {{Size, Offs}, Idx});
1079 }
1080
1081 // There may also be strange register class sizes (think x86 fp80s).
1082 for (const TargetRegisterClass *RC : TRI.regclasses()) {
1083 unsigned Size = TRI.getRegSizeInBits(RC: *RC);
1084
1085 // We might see special reserved values as sizes, and classes for other
1086 // stuff the machine tries to model. If it's more than 512 bits, then it
1087 // is very unlikely to be a register than can be spilt.
1088 if (Size > 512)
1089 continue;
1090
1091 unsigned Idx = StackSlotIdxes.size();
1092 StackSlotIdxes.insert(KV: {{Size, 0}, Idx});
1093 }
1094
1095 for (auto &Idx : StackSlotIdxes)
1096 StackIdxesToPos[Idx.second] = Idx.first;
1097
1098 NumSlotIdxes = StackSlotIdxes.size();
1099}
1100
1101LocIdx MLocTracker::trackRegister(unsigned ID) {
1102 assert(ID != 0);
1103 LocIdx NewIdx = LocIdx(LocIdxToIDNum.size());
1104 LocIdxToIDNum.grow(N: NewIdx);
1105 LocIdxToLocID.grow(N: NewIdx);
1106
1107 // Default: it's an mphi.
1108 ValueIDNum ValNum = {CurBB, 0, NewIdx};
1109 // Was this reg ever touched by a regmask?
1110 for (const auto &MaskPair : reverse(C&: Masks)) {
1111 if (MaskPair.first->clobbersPhysReg(PhysReg: ID)) {
1112 // There was an earlier def we skipped.
1113 ValNum = {CurBB, MaskPair.second, NewIdx};
1114 break;
1115 }
1116 }
1117
1118 LocIdxToIDNum[NewIdx] = ValNum;
1119 LocIdxToLocID[NewIdx] = ID;
1120 return NewIdx;
1121}
1122
1123void MLocTracker::writeRegMask(const MachineOperand *MO, unsigned CurBB,
1124 unsigned InstID) {
1125 // Def any register we track have that isn't preserved. The regmask
1126 // terminates the liveness of a register, meaning its value can't be
1127 // relied upon -- we represent this by giving it a new value.
1128 for (auto Location : locations()) {
1129 unsigned ID = LocIdxToLocID[Location.Idx];
1130 // Don't clobber SP, even if the mask says it's clobbered.
1131 if (ID < NumRegs && !SPAliases.count(V: ID) && MO->clobbersPhysReg(PhysReg: ID))
1132 defReg(R: ID, BB: CurBB, Inst: InstID);
1133 }
1134 Masks.push_back(Elt: std::make_pair(x&: MO, y&: InstID));
1135}
1136
1137std::optional<SpillLocationNo> MLocTracker::getOrTrackSpillLoc(SpillLoc L) {
1138 SpillLocationNo SpillID(SpillLocs.idFor(Entry: L));
1139
1140 if (SpillID.id() == 0) {
1141 // If there is no location, and we have reached the limit of how many stack
1142 // slots to track, then don't track this one.
1143 if (SpillLocs.size() >= StackWorkingSetLimit)
1144 return std::nullopt;
1145
1146 // Spill location is untracked: create record for this one, and all
1147 // subregister slots too.
1148 SpillID = SpillLocationNo(SpillLocs.insert(Entry: L));
1149 for (unsigned StackIdx = 0; StackIdx < NumSlotIdxes; ++StackIdx) {
1150 unsigned L = getSpillIDWithIdx(Spill: SpillID, Idx: StackIdx);
1151 LocIdx Idx = LocIdx(LocIdxToIDNum.size()); // New idx
1152 LocIdxToIDNum.grow(N: Idx);
1153 LocIdxToLocID.grow(N: Idx);
1154 LocIDToLocIdx.push_back(x: Idx);
1155 LocIdxToLocID[Idx] = L;
1156 // Initialize to PHI value; corresponds to the location's live-in value
1157 // during transfer function construction.
1158 LocIdxToIDNum[Idx] = ValueIDNum(CurBB, 0, Idx);
1159 }
1160 }
1161 return SpillID;
1162}
1163
1164std::string MLocTracker::LocIdxToName(LocIdx Idx) const {
1165 unsigned ID = LocIdxToLocID[Idx];
1166 if (ID >= NumRegs) {
1167 StackSlotPos Pos = locIDToSpillIdx(ID);
1168 ID -= NumRegs;
1169 unsigned Slot = ID / NumSlotIdxes;
1170 return Twine("slot ")
1171 .concat(Suffix: Twine(Slot).concat(Suffix: Twine(" sz ").concat(Suffix: Twine(Pos.first)
1172 .concat(Suffix: Twine(" offs ").concat(Suffix: Twine(Pos.second))))))
1173 .str();
1174 } else {
1175 return TRI.getRegAsmName(Reg: ID).str();
1176 }
1177}
1178
1179std::string MLocTracker::IDAsString(const ValueIDNum &Num) const {
1180 std::string DefName = LocIdxToName(Idx: Num.getLoc());
1181 return Num.asString(mlocname: DefName);
1182}
1183
1184#ifndef NDEBUG
1185LLVM_DUMP_METHOD void MLocTracker::dump() {
1186 for (auto Location : locations()) {
1187 std::string MLocName = LocIdxToName(Location.Value.getLoc());
1188 std::string DefName = Location.Value.asString(MLocName);
1189 dbgs() << LocIdxToName(Location.Idx) << " --> " << DefName << "\n";
1190 }
1191}
1192
1193LLVM_DUMP_METHOD void MLocTracker::dump_mloc_map() {
1194 for (auto Location : locations()) {
1195 std::string foo = LocIdxToName(Location.Idx);
1196 dbgs() << "Idx " << Location.Idx.asU64() << " " << foo << "\n";
1197 }
1198}
1199#endif
1200
1201MachineInstrBuilder
1202MLocTracker::emitLoc(const SmallVectorImpl<ResolvedDbgOp> &DbgOps,
1203 const DebugVariable &Var, const DILocation *DILoc,
1204 const DbgValueProperties &Properties) {
1205 DebugLoc DL = DebugLoc(DILoc);
1206
1207 const MCInstrDesc &Desc = Properties.IsVariadic
1208 ? TII.get(Opcode: TargetOpcode::DBG_VALUE_LIST)
1209 : TII.get(Opcode: TargetOpcode::DBG_VALUE);
1210
1211#ifdef EXPENSIVE_CHECKS
1212 assert(all_of(DbgOps,
1213 [](const ResolvedDbgOp &Op) {
1214 return Op.IsConst || !Op.Loc.isIllegal();
1215 }) &&
1216 "Did not expect illegal ops in DbgOps.");
1217 assert((DbgOps.size() == 0 ||
1218 DbgOps.size() == Properties.getLocationOpCount()) &&
1219 "Expected to have either one DbgOp per MI LocationOp, or none.");
1220#endif
1221
1222 auto GetRegOp = [](unsigned Reg) -> MachineOperand {
1223 return MachineOperand::CreateReg(
1224 /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
1225 /* isKill */ false, /* isDead */ false,
1226 /* isUndef */ false, /* isEarlyClobber */ false,
1227 /* SubReg */ 0, /* isDebug */ true);
1228 };
1229
1230 SmallVector<MachineOperand> MOs;
1231
1232 auto EmitUndef = [&]() {
1233 MOs.clear();
1234 MOs.assign(NumElts: Properties.getLocationOpCount(), Elt: GetRegOp(0));
1235 return BuildMI(MF, DL, MCID: Desc, IsIndirect: false, MOs, Variable: Var.getVariable(),
1236 Expr: Properties.DIExpr);
1237 };
1238
1239 // Don't bother passing any real operands to BuildMI if any of them would be
1240 // $noreg.
1241 if (DbgOps.empty())
1242 return EmitUndef();
1243
1244 bool Indirect = Properties.Indirect;
1245
1246 const DIExpression *Expr = Properties.DIExpr;
1247
1248 assert(DbgOps.size() == Properties.getLocationOpCount());
1249
1250 // If all locations are valid, accumulate them into our list of
1251 // MachineOperands. For any spilled locations, either update the indirectness
1252 // register or apply the appropriate transformations in the DIExpression.
1253 for (size_t Idx = 0; Idx < Properties.getLocationOpCount(); ++Idx) {
1254 const ResolvedDbgOp &Op = DbgOps[Idx];
1255
1256 if (Op.IsConst) {
1257 MOs.push_back(Elt: Op.MO);
1258 continue;
1259 }
1260
1261 LocIdx MLoc = Op.Loc;
1262 unsigned LocID = LocIdxToLocID[MLoc];
1263 if (LocID >= NumRegs) {
1264 SpillLocationNo SpillID = locIDToSpill(ID: LocID);
1265 StackSlotPos StackIdx = locIDToSpillIdx(ID: LocID);
1266 unsigned short Offset = StackIdx.second;
1267
1268 // TODO: support variables that are located in spill slots, with non-zero
1269 // offsets from the start of the spill slot. It would require some more
1270 // complex DIExpression calculations. This doesn't seem to be produced by
1271 // LLVM right now, so don't try and support it.
1272 // Accept no-subregister slots and subregisters where the offset is zero.
1273 // The consumer should already have type information to work out how large
1274 // the variable is.
1275 if (Offset == 0) {
1276 const SpillLoc &Spill = SpillLocs[SpillID.id()];
1277 unsigned Base = Spill.SpillBase;
1278
1279 // There are several ways we can dereference things, and several inputs
1280 // to consider:
1281 // * NRVO variables will appear with IsIndirect set, but should have
1282 // nothing else in their DIExpressions,
1283 // * Variables with DW_OP_stack_value in their expr already need an
1284 // explicit dereference of the stack location,
1285 // * Values that don't match the variable size need DW_OP_deref_size,
1286 // * Everything else can just become a simple location expression.
1287
1288 // We need to use deref_size whenever there's a mismatch between the
1289 // size of value and the size of variable portion being read.
1290 // Additionally, we should use it whenever dealing with stack_value
1291 // fragments, to avoid the consumer having to determine the deref size
1292 // from DW_OP_piece.
1293 bool UseDerefSize = false;
1294 unsigned ValueSizeInBits = getLocSizeInBits(L: MLoc);
1295 unsigned DerefSizeInBytes = ValueSizeInBits / 8;
1296 if (auto Fragment = Var.getFragment()) {
1297 unsigned VariableSizeInBits = Fragment->SizeInBits;
1298 if (VariableSizeInBits != ValueSizeInBits || Expr->isComplex())
1299 UseDerefSize = true;
1300 } else if (auto Size = Var.getVariable()->getSizeInBits()) {
1301 if (*Size != ValueSizeInBits) {
1302 UseDerefSize = true;
1303 }
1304 }
1305
1306 // https://github.com/llvm/llvm-project/issues/64093
1307 // in particular #issuecomment-2531264124. We use variable locations
1308 // such as DBG_VALUE $xmm0 as shorthand to refer to "the low lane of
1309 // $xmm0", and this is reflected in how DWARF is interpreted too.
1310 // However InstrRefBasedLDV tries to be smart and interprets such a
1311 // DBG_VALUE as a 128-bit reference. We then issue a DW_OP_deref_size
1312 // of 128 bits to the stack, which isn't permitted by DWARF (it's
1313 // larger than a pointer).
1314 //
1315 // Solve this for now by not using DW_OP_deref_size if it would be
1316 // illegal. Instead we'll use DW_OP_deref, and the consumer will load
1317 // the variable type from the stack, which should be correct.
1318 //
1319 // There's still a risk of imprecision when LLVM decides to use
1320 // smaller or larger value types than the source-variable type, which
1321 // manifests as too-little or too-much memory being read from the stack.
1322 // However we can't solve that without putting more type information in
1323 // debug-info.
1324 if (ValueSizeInBits > MF.getTarget().getPointerSizeInBits(AS: 0))
1325 UseDerefSize = false;
1326
1327 SmallVector<uint64_t, 5> OffsetOps;
1328 TRI.getOffsetOpcodes(Offset: Spill.SpillOffset, Ops&: OffsetOps);
1329 bool StackValue = false;
1330
1331 if (Properties.Indirect) {
1332 // This is something like an NRVO variable, where the pointer has been
1333 // spilt to the stack. It should end up being a memory location, with
1334 // the pointer to the variable loaded off the stack with a deref:
1335 assert(!Expr->isImplicit());
1336 OffsetOps.push_back(Elt: dwarf::DW_OP_deref);
1337 } else if (UseDerefSize && Expr->isSingleLocationExpression()) {
1338 // TODO: Figure out how to handle deref size issues for variadic
1339 // values.
1340 // We're loading a value off the stack that's not the same size as the
1341 // variable. Add / subtract stack offset, explicitly deref with a
1342 // size, and add DW_OP_stack_value if not already present.
1343 OffsetOps.push_back(Elt: dwarf::DW_OP_deref_size);
1344 OffsetOps.push_back(Elt: DerefSizeInBytes);
1345 StackValue = true;
1346 } else if (Expr->isComplex() || Properties.IsVariadic) {
1347 // A variable with no size ambiguity, but with extra elements in it's
1348 // expression. Manually dereference the stack location.
1349 OffsetOps.push_back(Elt: dwarf::DW_OP_deref);
1350 } else {
1351 // A plain value that has been spilt to the stack, with no further
1352 // context. Request a location expression, marking the DBG_VALUE as
1353 // IsIndirect.
1354 Indirect = true;
1355 }
1356
1357 Expr = DIExpression::appendOpsToArg(Expr, Ops: OffsetOps, ArgNo: Idx, StackValue);
1358 MOs.push_back(Elt: GetRegOp(Base));
1359 } else {
1360 // This is a stack location with a weird subregister offset: emit an
1361 // undef DBG_VALUE instead.
1362 return EmitUndef();
1363 }
1364 } else {
1365 // Non-empty, non-stack slot, must be a plain register.
1366 MOs.push_back(Elt: GetRegOp(LocID));
1367 }
1368 }
1369
1370 return BuildMI(MF, DL, MCID: Desc, IsIndirect: Indirect, MOs, Variable: Var.getVariable(), Expr);
1371}
1372
1373/// Default construct and initialize the pass.
1374InstrRefBasedLDV::InstrRefBasedLDV() = default;
1375
1376bool InstrRefBasedLDV::isCalleeSaved(LocIdx L) const {
1377 unsigned Reg = MTracker->LocIdxToLocID[L];
1378 return isCalleeSavedReg(R: Reg);
1379}
1380bool InstrRefBasedLDV::isCalleeSavedReg(Register R) const {
1381 for (MCRegAliasIterator RAI(R, TRI, true); RAI.isValid(); ++RAI)
1382 if (CalleeSavedRegs.test(Idx: (*RAI).id()))
1383 return true;
1384 return false;
1385}
1386
1387//===----------------------------------------------------------------------===//
1388// Debug Range Extension Implementation
1389//===----------------------------------------------------------------------===//
1390
1391#ifndef NDEBUG
1392// Something to restore in the future.
1393// void InstrRefBasedLDV::printVarLocInMBB(..)
1394#endif
1395
1396std::optional<SpillLocationNo>
1397InstrRefBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
1398 assert(MI.hasOneMemOperand() &&
1399 "Spill instruction does not have exactly one memory operand?");
1400 auto MMOI = MI.memoperands_begin();
1401 const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
1402 assert(PVal->kind() == PseudoSourceValue::FixedStack &&
1403 "Inconsistent memory operand in spill instruction");
1404 int FI = cast<FixedStackPseudoSourceValue>(Val: PVal)->getFrameIndex();
1405 const MachineBasicBlock *MBB = MI.getParent();
1406 Register Reg;
1407 StackOffset Offset = TFI->getFrameIndexReference(MF: *MBB->getParent(), FI, FrameReg&: Reg);
1408 return MTracker->getOrTrackSpillLoc(L: {.SpillBase: Reg, .SpillOffset: Offset});
1409}
1410
1411std::optional<LocIdx>
1412InstrRefBasedLDV::findLocationForMemOperand(const MachineInstr &MI) {
1413 std::optional<SpillLocationNo> SpillLoc = extractSpillBaseRegAndOffset(MI);
1414 if (!SpillLoc)
1415 return std::nullopt;
1416
1417 // Where in the stack slot is this value defined -- i.e., what size of value
1418 // is this? An important question, because it could be loaded into a register
1419 // from the stack at some point. Happily the memory operand will tell us
1420 // the size written to the stack.
1421 auto *MemOperand = *MI.memoperands_begin();
1422 LocationSize SizeInBits = MemOperand->getSizeInBits();
1423 assert(SizeInBits.hasValue() && "Expected to find a valid size!");
1424
1425 // Find that position in the stack indexes we're tracking.
1426 auto IdxIt = MTracker->StackSlotIdxes.find(Val: {SizeInBits.getValue(), 0});
1427 if (IdxIt == MTracker->StackSlotIdxes.end())
1428 // That index is not tracked. This is suprising, and unlikely to ever
1429 // occur, but the safe action is to indicate the variable is optimised out.
1430 return std::nullopt;
1431
1432 unsigned SpillID = MTracker->getSpillIDWithIdx(Spill: *SpillLoc, Idx: IdxIt->second);
1433 return MTracker->getSpillMLoc(SpillID);
1434}
1435
1436/// End all previous ranges related to @MI and start a new range from @MI
1437/// if it is a DBG_VALUE instr.
1438bool InstrRefBasedLDV::transferDebugValue(const MachineInstr &MI) {
1439 if (!MI.isDebugValue())
1440 return false;
1441
1442 assert(MI.getDebugVariable()->isValidLocationForIntrinsic(MI.getDebugLoc()) &&
1443 "Expected inlined-at fields to agree");
1444
1445 // If there are no instructions in this lexical scope, do no location tracking
1446 // at all, this variable shouldn't get a legitimate location range.
1447 auto *Scope = LS.findLexicalScope(DL: MI.getDebugLoc().get());
1448 if (Scope == nullptr)
1449 return true; // handled it; by doing nothing
1450
1451 // MLocTracker needs to know that this register is read, even if it's only
1452 // read by a debug inst.
1453 for (const MachineOperand &MO : MI.debug_operands())
1454 if (MO.isReg() && MO.getReg() != 0)
1455 (void)MTracker->readReg(R: MO.getReg());
1456
1457 // If we're preparing for the second analysis (variables), the machine value
1458 // locations are already solved, and we report this DBG_VALUE and the value
1459 // it refers to to VLocTracker.
1460 if (VTracker) {
1461 SmallVector<DbgOpID> DebugOps;
1462 // Feed defVar the new variable location, or if this is a DBG_VALUE $noreg,
1463 // feed defVar None.
1464 if (!MI.isUndefDebugValue()) {
1465 for (const MachineOperand &MO : MI.debug_operands()) {
1466 // There should be no undef registers here, as we've screened for undef
1467 // debug values.
1468 if (MO.isReg()) {
1469 DebugOps.push_back(Elt: DbgOpStore.insert(Op: MTracker->readReg(R: MO.getReg())));
1470 } else if (MO.isImm() || MO.isFPImm() || MO.isCImm()) {
1471 DebugOps.push_back(Elt: DbgOpStore.insert(Op: MO));
1472 } else {
1473 llvm_unreachable("Unexpected debug operand type.");
1474 }
1475 }
1476 }
1477 VTracker->defVar(MI, Properties: DbgValueProperties(MI), DebugOps);
1478 }
1479
1480 // If performing final tracking of transfers, report this variable definition
1481 // to the TransferTracker too.
1482 if (TTracker)
1483 TTracker->redefVar(MI);
1484 return true;
1485}
1486
1487std::optional<ValueIDNum> InstrRefBasedLDV::getValueForInstrRef(
1488 unsigned InstNo, unsigned OpNo, MachineInstr &MI,
1489 const FuncValueTable *MLiveOuts, const FuncValueTable *MLiveIns) {
1490 // Various optimizations may have happened to the value during codegen,
1491 // recorded in the value substitution table. Apply any substitutions to
1492 // the instruction / operand number in this DBG_INSTR_REF, and collect
1493 // any subregister extractions performed during optimization.
1494 const MachineFunction &MF = *MI.getParent()->getParent();
1495
1496 // Create dummy substitution with Src set, for lookup.
1497 auto SoughtSub =
1498 MachineFunction::DebugSubstitution({InstNo, OpNo}, {0, 0}, 0);
1499
1500 SmallVector<unsigned, 4> SeenSubregs;
1501 auto LowerBoundIt = llvm::lower_bound(Range: MF.DebugValueSubstitutions, Value&: SoughtSub);
1502 while (LowerBoundIt != MF.DebugValueSubstitutions.end() &&
1503 LowerBoundIt->Src == SoughtSub.Src) {
1504 std::tie(args&: InstNo, args&: OpNo) = LowerBoundIt->Dest;
1505 SoughtSub.Src = LowerBoundIt->Dest;
1506 if (unsigned Subreg = LowerBoundIt->Subreg)
1507 SeenSubregs.push_back(Elt: Subreg);
1508 LowerBoundIt = llvm::lower_bound(Range: MF.DebugValueSubstitutions, Value&: SoughtSub);
1509 }
1510
1511 // Default machine value number is <None> -- if no instruction defines
1512 // the corresponding value, it must have been optimized out.
1513 std::optional<ValueIDNum> NewID;
1514
1515 // Try to lookup the instruction number, and find the machine value number
1516 // that it defines. It could be an instruction, or a PHI.
1517 auto InstrIt = DebugInstrNumToInstr.find(x: InstNo);
1518 auto PHIIt = llvm::lower_bound(Range&: DebugPHINumToValue, Value&: InstNo);
1519 if (InstrIt != DebugInstrNumToInstr.end()) {
1520 const MachineInstr &TargetInstr = *InstrIt->second.first;
1521 uint64_t BlockNo = TargetInstr.getParent()->getNumber();
1522
1523 // Pick out the designated operand. It might be a memory reference, if
1524 // a register def was folded into a stack store.
1525 if (OpNo == MachineFunction::DebugOperandMemNumber &&
1526 TargetInstr.hasOneMemOperand()) {
1527 std::optional<LocIdx> L = findLocationForMemOperand(MI: TargetInstr);
1528 if (L)
1529 NewID = ValueIDNum(BlockNo, InstrIt->second.second, *L);
1530 } else if (OpNo != MachineFunction::DebugOperandMemNumber) {
1531 // Permit the debug-info to be completely wrong: identifying a nonexistant
1532 // operand, or one that is not a register definition, means something
1533 // unexpected happened during optimisation. Broken debug-info, however,
1534 // shouldn't crash the compiler -- instead leave the variable value as
1535 // None, which will make it appear "optimised out".
1536 if (OpNo < TargetInstr.getNumOperands()) {
1537 const MachineOperand &MO = TargetInstr.getOperand(i: OpNo);
1538
1539 if (MO.isReg() && MO.isDef() && MO.getReg()) {
1540 unsigned LocID = MTracker->getLocID(Reg: MO.getReg());
1541 LocIdx L = MTracker->LocIDToLocIdx[LocID];
1542 NewID = ValueIDNum(BlockNo, InstrIt->second.second, L);
1543 }
1544 }
1545
1546 if (!NewID) {
1547 LLVM_DEBUG(
1548 { dbgs() << "Seen instruction reference to illegal operand\n"; });
1549 }
1550 }
1551 // else: NewID is left as None.
1552 } else if (PHIIt != DebugPHINumToValue.end() && PHIIt->InstrNum == InstNo) {
1553 // It's actually a PHI value. Which value it is might not be obvious, use
1554 // the resolver helper to find out.
1555 assert(MLiveOuts && MLiveIns);
1556 NewID = resolveDbgPHIs(MF&: *MI.getParent()->getParent(), MLiveOuts: *MLiveOuts, MLiveIns: *MLiveIns,
1557 Here&: MI, InstrNum: InstNo);
1558 }
1559
1560 // Apply any subregister extractions, in reverse. We might have seen code
1561 // like this:
1562 // CALL64 @foo, implicit-def $rax
1563 // %0:gr64 = COPY $rax
1564 // %1:gr32 = COPY %0.sub_32bit
1565 // %2:gr16 = COPY %1.sub_16bit
1566 // %3:gr8 = COPY %2.sub_8bit
1567 // In which case each copy would have been recorded as a substitution with
1568 // a subregister qualifier. Apply those qualifiers now.
1569 if (NewID && !SeenSubregs.empty()) {
1570 unsigned Offset = 0;
1571 unsigned Size = 0;
1572
1573 // Look at each subregister that we passed through, and progressively
1574 // narrow in, accumulating any offsets that occur. Substitutions should
1575 // only ever be the same or narrower width than what they read from;
1576 // iterate in reverse order so that we go from wide to small.
1577 for (unsigned Subreg : reverse(C&: SeenSubregs)) {
1578 unsigned ThisSize = TRI->getSubRegIdxSize(Idx: Subreg);
1579 unsigned ThisOffset = TRI->getSubRegIdxOffset(Idx: Subreg);
1580 Offset += ThisOffset;
1581 Size = (Size == 0) ? ThisSize : std::min(a: Size, b: ThisSize);
1582 }
1583
1584 // If that worked, look for an appropriate subregister with the register
1585 // where the define happens. Don't look at values that were defined during
1586 // a stack write: we can't currently express register locations within
1587 // spills.
1588 LocIdx L = NewID->getLoc();
1589 if (NewID && !MTracker->isSpill(Idx: L)) {
1590 // Find the register class for the register where this def happened.
1591 // FIXME: no index for this?
1592 Register Reg = MTracker->LocIdxToLocID[L];
1593 const TargetRegisterClass *TRC = nullptr;
1594 for (const auto *TRCI : TRI->regclasses())
1595 if (TRCI->contains(Reg))
1596 TRC = TRCI;
1597 assert(TRC && "Couldn't find target register class?");
1598
1599 // If the register we have isn't the right size or in the right place,
1600 // Try to find a subregister inside it.
1601 unsigned MainRegSize = TRI->getRegSizeInBits(RC: *TRC);
1602 if (Size != MainRegSize || Offset) {
1603 // Enumerate all subregisters, searching.
1604 Register NewReg = Register();
1605 for (MCRegister SR : TRI->subregs(Reg)) {
1606 unsigned Subreg = TRI->getSubRegIndex(RegNo: Reg, SubRegNo: SR);
1607 unsigned SubregSize = TRI->getSubRegIdxSize(Idx: Subreg);
1608 unsigned SubregOffset = TRI->getSubRegIdxOffset(Idx: Subreg);
1609 if (SubregSize == Size && SubregOffset == Offset) {
1610 NewReg = SR;
1611 break;
1612 }
1613 }
1614
1615 // If we didn't find anything: there's no way to express our value.
1616 if (!NewReg) {
1617 NewID = std::nullopt;
1618 } else {
1619 // Re-state the value as being defined within the subregister
1620 // that we found.
1621 LocIdx NewLoc =
1622 MTracker->lookupOrTrackRegister(ID: MTracker->getLocID(Reg: NewReg));
1623 NewID = ValueIDNum(NewID->getBlock(), NewID->getInst(), NewLoc);
1624 }
1625 }
1626 } else {
1627 // If we can't handle subregisters, unset the new value.
1628 NewID = std::nullopt;
1629 }
1630 }
1631
1632 return NewID;
1633}
1634
1635bool InstrRefBasedLDV::transferDebugInstrRef(MachineInstr &MI,
1636 const FuncValueTable *MLiveOuts,
1637 const FuncValueTable *MLiveIns) {
1638 if (!MI.isDebugRef())
1639 return false;
1640
1641 // Only handle this instruction when we are building the variable value
1642 // transfer function.
1643 if (!VTracker && !TTracker)
1644 return false;
1645
1646 const DILocalVariable *Var = MI.getDebugVariable();
1647 const DIExpression *Expr = MI.getDebugExpression();
1648 const DILocation *DebugLoc = MI.getDebugLoc();
1649 const DILocation *InlinedAt = DebugLoc->getInlinedAt();
1650 assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
1651 "Expected inlined-at fields to agree");
1652
1653 DebugVariable V(Var, Expr, InlinedAt);
1654
1655 auto *Scope = LS.findLexicalScope(DL: MI.getDebugLoc().get());
1656 if (Scope == nullptr)
1657 return true; // Handled by doing nothing. This variable is never in scope.
1658
1659 SmallVector<DbgOpID> DbgOpIDs;
1660 for (const MachineOperand &MO : MI.debug_operands()) {
1661 if (!MO.isDbgInstrRef()) {
1662 assert(!MO.isReg() && "DBG_INSTR_REF should not contain registers");
1663 DbgOpID ConstOpID = DbgOpStore.insert(Op: DbgOp(MO));
1664 DbgOpIDs.push_back(Elt: ConstOpID);
1665 continue;
1666 }
1667
1668 unsigned InstNo = MO.getInstrRefInstrIndex();
1669 unsigned OpNo = MO.getInstrRefOpIndex();
1670
1671 // Default machine value number is <None> -- if no instruction defines
1672 // the corresponding value, it must have been optimized out.
1673 std::optional<ValueIDNum> NewID =
1674 getValueForInstrRef(InstNo, OpNo, MI, MLiveOuts, MLiveIns);
1675 // We have a value number or std::nullopt. If the latter, then kill the
1676 // entire debug value.
1677 if (NewID) {
1678 DbgOpIDs.push_back(Elt: DbgOpStore.insert(Op: *NewID));
1679 } else {
1680 DbgOpIDs.clear();
1681 break;
1682 }
1683 }
1684
1685 // We have a DbgOpID for every value or for none. Tell the variable value
1686 // tracker about it. The rest of this LiveDebugValues implementation acts
1687 // exactly the same for DBG_INSTR_REFs as DBG_VALUEs (just, the former can
1688 // refer to values that aren't immediately available).
1689 DbgValueProperties Properties(Expr, false, true);
1690 if (VTracker)
1691 VTracker->defVar(MI, Properties, DebugOps: DbgOpIDs);
1692
1693 // If we're on the final pass through the function, decompose this INSTR_REF
1694 // into a plain DBG_VALUE.
1695 if (!TTracker)
1696 return true;
1697
1698 // Fetch the concrete DbgOps now, as we will need them later.
1699 SmallVector<DbgOp> DbgOps;
1700 for (DbgOpID OpID : DbgOpIDs) {
1701 DbgOps.push_back(Elt: DbgOpStore.find(ID: OpID));
1702 }
1703
1704 // Pick a location for the machine value number, if such a location exists.
1705 // (This information could be stored in TransferTracker to make it faster).
1706 SmallDenseMap<ValueIDNum, TransferTracker::LocationAndQuality> FoundLocs;
1707 SmallVector<ValueIDNum> ValuesToFind;
1708 // Initialized the preferred-location map with illegal locations, to be
1709 // filled in later.
1710 for (const DbgOp &Op : DbgOps) {
1711 if (!Op.IsConst)
1712 if (FoundLocs.try_emplace(Key: Op.ID).second)
1713 ValuesToFind.push_back(Elt: Op.ID);
1714 }
1715
1716 for (auto Location : MTracker->locations()) {
1717 LocIdx CurL = Location.Idx;
1718 ValueIDNum ID = MTracker->readMLoc(L: CurL);
1719 auto ValueToFindIt = find(Range&: ValuesToFind, Val: ID);
1720 if (ValueToFindIt == ValuesToFind.end())
1721 continue;
1722 auto &Previous = FoundLocs.find(Val: ID)->second;
1723 // If this is the first location with that value, pick it. Otherwise,
1724 // consider whether it's a "longer term" location.
1725 std::optional<TransferTracker::LocationQuality> ReplacementQuality =
1726 TTracker->getLocQualityIfBetter(L: CurL, Min: Previous.getQuality());
1727 if (ReplacementQuality) {
1728 Previous = TransferTracker::LocationAndQuality(CurL, *ReplacementQuality);
1729 if (Previous.isBest()) {
1730 ValuesToFind.erase(CI: ValueToFindIt);
1731 if (ValuesToFind.empty())
1732 break;
1733 }
1734 }
1735 }
1736
1737 SmallVector<ResolvedDbgOp> NewLocs;
1738 for (const DbgOp &DbgOp : DbgOps) {
1739 if (DbgOp.IsConst) {
1740 NewLocs.push_back(Elt: DbgOp.MO);
1741 continue;
1742 }
1743 LocIdx FoundLoc = FoundLocs.find(Val: DbgOp.ID)->second.getLoc();
1744 if (FoundLoc.isIllegal()) {
1745 NewLocs.clear();
1746 break;
1747 }
1748 NewLocs.push_back(Elt: FoundLoc);
1749 }
1750 // Tell transfer tracker that the variable value has changed.
1751 TTracker->redefVar(MI, Properties, NewLocs);
1752
1753 // If there were values with no location, but all such values are defined in
1754 // later instructions in this block, this is a block-local use-before-def.
1755 if (!DbgOps.empty() && NewLocs.empty()) {
1756 bool IsValidUseBeforeDef = true;
1757 uint64_t LastUseBeforeDef = 0;
1758 for (auto ValueLoc : FoundLocs) {
1759 ValueIDNum NewID = ValueLoc.first;
1760 LocIdx FoundLoc = ValueLoc.second.getLoc();
1761 if (!FoundLoc.isIllegal())
1762 continue;
1763 // If we have an value with no location that is not defined in this block,
1764 // then it has no location in this block, leaving this value undefined.
1765 if (NewID.getBlock() != CurBB || NewID.getInst() <= CurInst) {
1766 IsValidUseBeforeDef = false;
1767 break;
1768 }
1769 LastUseBeforeDef = std::max(a: LastUseBeforeDef, b: NewID.getInst());
1770 }
1771 if (IsValidUseBeforeDef) {
1772 DebugVariableID VID = DVMap.insertDVID(Var&: V, Loc: MI.getDebugLoc().get());
1773 TTracker->addUseBeforeDef(VarID: VID, Properties: {MI.getDebugExpression(), false, true},
1774 DbgOps, Inst: LastUseBeforeDef);
1775 }
1776 }
1777
1778 // Produce a DBG_VALUE representing what this DBG_INSTR_REF meant.
1779 // This DBG_VALUE is potentially a $noreg / undefined location, if
1780 // FoundLoc is illegal.
1781 // (XXX -- could morph the DBG_INSTR_REF in the future).
1782 MachineInstr *DbgMI =
1783 MTracker->emitLoc(DbgOps: NewLocs, Var: V, DILoc: MI.getDebugLoc().get(), Properties);
1784 DebugVariableID ID = DVMap.getDVID(Var: V);
1785
1786 TTracker->PendingDbgValues.push_back(Elt: std::make_pair(x&: ID, y&: DbgMI));
1787 TTracker->flushDbgValues(Pos: MI.getIterator(), MBB: nullptr);
1788 return true;
1789}
1790
1791bool InstrRefBasedLDV::transferDebugPHI(MachineInstr &MI) {
1792 if (!MI.isDebugPHI())
1793 return false;
1794
1795 // Analyse these only when solving the machine value location problem.
1796 if (VTracker || TTracker)
1797 return true;
1798
1799 // First operand is the value location, either a stack slot or register.
1800 // Second is the debug instruction number of the original PHI.
1801 const MachineOperand &MO = MI.getOperand(i: 0);
1802 unsigned InstrNum = MI.getOperand(i: 1).getImm();
1803
1804 auto EmitBadPHI = [this, &MI, InstrNum]() -> bool {
1805 // Helper lambda to do any accounting when we fail to find a location for
1806 // a DBG_PHI. This can happen if DBG_PHIs are malformed, or refer to a
1807 // dead stack slot, for example.
1808 // Record a DebugPHIRecord with an empty value + location.
1809 DebugPHINumToValue.push_back(
1810 Elt: {.InstrNum: InstrNum, .MBB: MI.getParent(), .ValueRead: std::nullopt, .ReadLoc: std::nullopt});
1811 return true;
1812 };
1813
1814 if (MO.isReg() && MO.getReg()) {
1815 // The value is whatever's currently in the register. Read and record it,
1816 // to be analysed later.
1817 Register Reg = MO.getReg();
1818 ValueIDNum Num = MTracker->readReg(R: Reg);
1819 auto PHIRec = DebugPHIRecord(
1820 {.InstrNum: InstrNum, .MBB: MI.getParent(), .ValueRead: Num,
1821 .ReadLoc: MTracker->lookupOrTrackRegister(ID: MTracker->getLocID(Reg))});
1822 DebugPHINumToValue.push_back(Elt: PHIRec);
1823
1824 // Ensure this register is tracked.
1825 for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1826 MTracker->lookupOrTrackRegister(ID: MTracker->getLocID(Reg: *RAI));
1827 } else if (MO.isFI()) {
1828 // The value is whatever's in this stack slot.
1829 unsigned FI = MO.getIndex();
1830
1831 // If the stack slot is dead, then this was optimized away.
1832 // FIXME: stack slot colouring should account for slots that get merged.
1833 if (MFI->isDeadObjectIndex(ObjectIdx: FI))
1834 return EmitBadPHI();
1835
1836 // Identify this spill slot, ensure it's tracked.
1837 Register Base;
1838 StackOffset Offs = TFI->getFrameIndexReference(MF: *MI.getMF(), FI, FrameReg&: Base);
1839 SpillLoc SL = {.SpillBase: Base, .SpillOffset: Offs};
1840 std::optional<SpillLocationNo> SpillNo = MTracker->getOrTrackSpillLoc(L: SL);
1841
1842 // We might be able to find a value, but have chosen not to, to avoid
1843 // tracking too much stack information.
1844 if (!SpillNo)
1845 return EmitBadPHI();
1846
1847 // Any stack location DBG_PHI should have an associate bit-size.
1848 assert(MI.getNumOperands() == 3 && "Stack DBG_PHI with no size?");
1849 unsigned slotBitSize = MI.getOperand(i: 2).getImm();
1850
1851 unsigned SpillID = MTracker->getLocID(Spill: *SpillNo, Idx: {slotBitSize, 0});
1852 LocIdx SpillLoc = MTracker->getSpillMLoc(SpillID);
1853 ValueIDNum Result = MTracker->readMLoc(L: SpillLoc);
1854
1855 // Record this DBG_PHI for later analysis.
1856 auto DbgPHI = DebugPHIRecord({.InstrNum: InstrNum, .MBB: MI.getParent(), .ValueRead: Result, .ReadLoc: SpillLoc});
1857 DebugPHINumToValue.push_back(Elt: DbgPHI);
1858 } else {
1859 // Else: if the operand is neither a legal register or a stack slot, then
1860 // we're being fed illegal debug-info. Record an empty PHI, so that any
1861 // debug users trying to read this number will be put off trying to
1862 // interpret the value.
1863 LLVM_DEBUG(
1864 { dbgs() << "Seen DBG_PHI with unrecognised operand format\n"; });
1865 return EmitBadPHI();
1866 }
1867
1868 return true;
1869}
1870
1871void InstrRefBasedLDV::transferRegisterDef(MachineInstr &MI) {
1872 // Meta Instructions do not affect the debug liveness of any register they
1873 // define.
1874 if (MI.isImplicitDef()) {
1875 // Except when there's an implicit def, and the location it's defining has
1876 // no value number. The whole point of an implicit def is to announce that
1877 // the register is live, without be specific about it's value. So define
1878 // a value if there isn't one already.
1879 ValueIDNum Num = MTracker->readReg(R: MI.getOperand(i: 0).getReg());
1880 // Has a legitimate value -> ignore the implicit def.
1881 if (Num.getLoc() != 0)
1882 return;
1883 // Otherwise, def it here.
1884 } else if (MI.isMetaInstruction())
1885 return;
1886
1887 // We always ignore SP defines on call instructions, they don't actually
1888 // change the value of the stack pointer... except for win32's _chkstk. This
1889 // is rare: filter quickly for the common case (no stack adjustments, not a
1890 // call, etc). If it is a call that modifies SP, recognise the SP register
1891 // defs.
1892 bool CallChangesSP = false;
1893 if (AdjustsStackInCalls && MI.isCall() && MI.getOperand(i: 0).isSymbol() &&
1894 !strcmp(s1: MI.getOperand(i: 0).getSymbolName(), s2: StackProbeSymbolName.data()))
1895 CallChangesSP = true;
1896
1897 // Test whether we should ignore a def of this register due to it being part
1898 // of the stack pointer.
1899 auto IgnoreSPAlias = [this, &MI, CallChangesSP](Register R) -> bool {
1900 if (CallChangesSP)
1901 return false;
1902 return MI.isCall() && MTracker->SPAliases.count(V: R);
1903 };
1904
1905 // Find the regs killed by MI, and find regmasks of preserved regs.
1906 // Max out the number of statically allocated elements in `DeadRegs`, as this
1907 // prevents fallback to std::set::count() operations.
1908 SmallSet<uint32_t, 32> DeadRegs;
1909 SmallVector<const uint32_t *, 4> RegMasks;
1910 SmallVector<const MachineOperand *, 4> RegMaskPtrs;
1911 for (const MachineOperand &MO : MI.operands()) {
1912 // Determine whether the operand is a register def.
1913 if (MO.isReg() && MO.isDef() && MO.getReg() && MO.getReg().isPhysical() &&
1914 !IgnoreSPAlias(MO.getReg())) {
1915 // Remove ranges of all aliased registers.
1916 for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1917 // FIXME: Can we break out of this loop early if no insertion occurs?
1918 DeadRegs.insert(V: (*RAI).id());
1919 } else if (MO.isRegMask()) {
1920 RegMasks.push_back(Elt: MO.getRegMask());
1921 RegMaskPtrs.push_back(Elt: &MO);
1922 }
1923 }
1924
1925 // Tell MLocTracker about all definitions, of regmasks and otherwise.
1926 for (uint32_t DeadReg : DeadRegs)
1927 MTracker->defReg(R: DeadReg, BB: CurBB, Inst: CurInst);
1928
1929 for (const auto *MO : RegMaskPtrs)
1930 MTracker->writeRegMask(MO, CurBB, InstID: CurInst);
1931
1932 // If this instruction writes to a spill slot, def that slot.
1933 if (hasFoldedStackStore(MI)) {
1934 if (std::optional<SpillLocationNo> SpillNo =
1935 extractSpillBaseRegAndOffset(MI)) {
1936 for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) {
1937 unsigned SpillID = MTracker->getSpillIDWithIdx(Spill: *SpillNo, Idx: I);
1938 LocIdx L = MTracker->getSpillMLoc(SpillID);
1939 MTracker->setMLoc(L, Num: ValueIDNum(CurBB, CurInst, L));
1940 }
1941 }
1942 }
1943
1944 if (!TTracker)
1945 return;
1946
1947 // When committing variable values to locations: tell transfer tracker that
1948 // we've clobbered things. It may be able to recover the variable from a
1949 // different location.
1950
1951 // Inform TTracker about any direct clobbers.
1952 for (MCRegister DeadReg : DeadRegs) {
1953 LocIdx Loc = MTracker->lookupOrTrackRegister(ID: MTracker->getLocID(Reg: DeadReg));
1954 TTracker->clobberMloc(MLoc: Loc, Pos: MI.getIterator(), MakeUndef: false);
1955 }
1956
1957 // Look for any clobbers performed by a register mask. Only test locations
1958 // that are actually being tracked.
1959 if (!RegMaskPtrs.empty()) {
1960 for (auto L : MTracker->locations()) {
1961 // Stack locations can't be clobbered by regmasks.
1962 if (MTracker->isSpill(Idx: L.Idx))
1963 continue;
1964
1965 Register Reg = MTracker->LocIdxToLocID[L.Idx];
1966 if (IgnoreSPAlias(Reg))
1967 continue;
1968
1969 for (const auto *MO : RegMaskPtrs)
1970 if (MO->clobbersPhysReg(PhysReg: Reg))
1971 TTracker->clobberMloc(MLoc: L.Idx, Pos: MI.getIterator(), MakeUndef: false);
1972 }
1973 }
1974
1975 // Tell TTracker about any folded stack store.
1976 if (hasFoldedStackStore(MI)) {
1977 if (std::optional<SpillLocationNo> SpillNo =
1978 extractSpillBaseRegAndOffset(MI)) {
1979 for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) {
1980 unsigned SpillID = MTracker->getSpillIDWithIdx(Spill: *SpillNo, Idx: I);
1981 LocIdx L = MTracker->getSpillMLoc(SpillID);
1982 TTracker->clobberMloc(MLoc: L, Pos: MI.getIterator(), MakeUndef: true);
1983 }
1984 }
1985 }
1986}
1987
1988void InstrRefBasedLDV::performCopy(Register SrcRegNum, Register DstRegNum) {
1989 // In all circumstances, re-def all aliases. It's definitely a new value now.
1990 for (MCRegAliasIterator RAI(DstRegNum, TRI, true); RAI.isValid(); ++RAI)
1991 MTracker->defReg(R: *RAI, BB: CurBB, Inst: CurInst);
1992
1993 ValueIDNum SrcValue = MTracker->readReg(R: SrcRegNum);
1994 MTracker->setReg(R: DstRegNum, ValueID: SrcValue);
1995
1996 // Copy subregisters from one location to another.
1997 for (MCSubRegIndexIterator SRI(SrcRegNum, TRI); SRI.isValid(); ++SRI) {
1998 MCRegister SrcSubReg = SRI.getSubReg();
1999 unsigned SubRegIdx = SRI.getSubRegIndex();
2000 MCRegister DstSubReg = TRI->getSubReg(Reg: DstRegNum, Idx: SubRegIdx);
2001 if (!DstSubReg)
2002 continue;
2003
2004 // Do copy. There are two matching subregisters, the source value should
2005 // have been def'd when the super-reg was, the latter might not be tracked
2006 // yet.
2007 // This will force SrcSubReg to be tracked, if it isn't yet. Will read
2008 // mphi values if it wasn't tracked.
2009 LocIdx SrcL =
2010 MTracker->lookupOrTrackRegister(ID: MTracker->getLocID(Reg: SrcSubReg));
2011 LocIdx DstL =
2012 MTracker->lookupOrTrackRegister(ID: MTracker->getLocID(Reg: DstSubReg));
2013 (void)SrcL;
2014 (void)DstL;
2015 ValueIDNum CpyValue = MTracker->readReg(R: SrcSubReg);
2016
2017 MTracker->setReg(R: DstSubReg, ValueID: CpyValue);
2018 }
2019}
2020
2021std::optional<SpillLocationNo>
2022InstrRefBasedLDV::isSpillInstruction(const MachineInstr &MI,
2023 MachineFunction *MF) {
2024 // TODO: Handle multiple stores folded into one.
2025 if (!MI.hasOneMemOperand())
2026 return std::nullopt;
2027
2028 // Reject any memory operand that's aliased -- we can't guarantee its value.
2029 auto MMOI = MI.memoperands_begin();
2030 const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
2031 if (PVal->isAliased(MFI))
2032 return std::nullopt;
2033
2034 if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
2035 return std::nullopt; // This is not a spill instruction, since no valid size
2036 // was returned from either function.
2037
2038 return extractSpillBaseRegAndOffset(MI);
2039}
2040
2041bool InstrRefBasedLDV::isLocationSpill(const MachineInstr &MI,
2042 MachineFunction *MF, unsigned &Reg) {
2043 if (!isSpillInstruction(MI, MF))
2044 return false;
2045
2046 int FI;
2047 Reg = TII->isStoreToStackSlotPostFE(MI, FrameIndex&: FI);
2048 return Reg != 0;
2049}
2050
2051std::optional<SpillLocationNo>
2052InstrRefBasedLDV::isRestoreInstruction(const MachineInstr &MI,
2053 MachineFunction *MF, unsigned &Reg) {
2054 if (!MI.hasOneMemOperand())
2055 return std::nullopt;
2056
2057 // FIXME: Handle folded restore instructions with more than one memory
2058 // operand.
2059 if (MI.getRestoreSize(TII)) {
2060 Reg = MI.getOperand(i: 0).getReg();
2061 return extractSpillBaseRegAndOffset(MI);
2062 }
2063 return std::nullopt;
2064}
2065
2066bool InstrRefBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI) {
2067 // XXX -- it's too difficult to implement VarLocBasedImpl's stack location
2068 // limitations under the new model. Therefore, when comparing them, compare
2069 // versions that don't attempt spills or restores at all.
2070 if (EmulateOldLDV)
2071 return false;
2072
2073 // Strictly limit ourselves to plain loads and stores, not all instructions
2074 // that can access the stack.
2075 int DummyFI = -1;
2076 if (!TII->isStoreToStackSlotPostFE(MI, FrameIndex&: DummyFI) &&
2077 !TII->isLoadFromStackSlotPostFE(MI, FrameIndex&: DummyFI))
2078 return false;
2079
2080 MachineFunction *MF = MI.getMF();
2081 unsigned Reg;
2082
2083 LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
2084
2085 // Strictly limit ourselves to plain loads and stores, not all instructions
2086 // that can access the stack.
2087 int FIDummy;
2088 if (!TII->isStoreToStackSlotPostFE(MI, FrameIndex&: FIDummy) &&
2089 !TII->isLoadFromStackSlotPostFE(MI, FrameIndex&: FIDummy))
2090 return false;
2091
2092 // First, if there are any DBG_VALUEs pointing at a spill slot that is
2093 // written to, terminate that variable location. The value in memory
2094 // will have changed. DbgEntityHistoryCalculator doesn't try to detect this.
2095 if (std::optional<SpillLocationNo> Loc = isSpillInstruction(MI, MF)) {
2096 // Un-set this location and clobber, so that earlier locations don't
2097 // continue past this store.
2098 for (unsigned SlotIdx = 0; SlotIdx < MTracker->NumSlotIdxes; ++SlotIdx) {
2099 unsigned SpillID = MTracker->getSpillIDWithIdx(Spill: *Loc, Idx: SlotIdx);
2100 std::optional<LocIdx> MLoc = MTracker->getSpillMLoc(SpillID);
2101 if (!MLoc)
2102 continue;
2103
2104 // We need to over-write the stack slot with something (here, a def at
2105 // this instruction) to ensure no values are preserved in this stack slot
2106 // after the spill. It also prevents TTracker from trying to recover the
2107 // location and re-installing it in the same place.
2108 ValueIDNum Def(CurBB, CurInst, *MLoc);
2109 MTracker->setMLoc(L: *MLoc, Num: Def);
2110 if (TTracker)
2111 TTracker->clobberMloc(MLoc: *MLoc, Pos: MI.getIterator());
2112 }
2113 }
2114
2115 // Try to recognise spill and restore instructions that may transfer a value.
2116 if (isLocationSpill(MI, MF, Reg)) {
2117 // isLocationSpill returning true should guarantee we can extract a
2118 // location.
2119 SpillLocationNo Loc = *extractSpillBaseRegAndOffset(MI);
2120
2121 auto DoTransfer = [&](Register SrcReg, unsigned SpillID) {
2122 auto ReadValue = MTracker->readReg(R: SrcReg);
2123 LocIdx DstLoc = MTracker->getSpillMLoc(SpillID);
2124 MTracker->setMLoc(L: DstLoc, Num: ReadValue);
2125
2126 if (TTracker) {
2127 LocIdx SrcLoc = MTracker->getRegMLoc(R: SrcReg);
2128 TTracker->transferMlocs(Src: SrcLoc, Dst: DstLoc, Pos: MI.getIterator());
2129 }
2130 };
2131
2132 // Then, transfer subreg bits.
2133 for (MCPhysReg SR : TRI->subregs(Reg)) {
2134 // Ensure this reg is tracked,
2135 (void)MTracker->lookupOrTrackRegister(ID: MTracker->getLocID(Reg: SR));
2136 unsigned SubregIdx = TRI->getSubRegIndex(RegNo: Reg, SubRegNo: SR);
2137 unsigned SpillID = MTracker->getLocID(Spill: Loc, SpillSubReg: SubregIdx);
2138 DoTransfer(SR, SpillID);
2139 }
2140
2141 // Directly lookup size of main source reg, and transfer.
2142 unsigned Size = TRI->getRegSizeInBits(Reg, MRI: *MRI);
2143 unsigned SpillID = MTracker->getLocID(Spill: Loc, Idx: {Size, 0});
2144 DoTransfer(Reg, SpillID);
2145 } else {
2146 std::optional<SpillLocationNo> Loc = isRestoreInstruction(MI, MF, Reg);
2147 if (!Loc)
2148 return false;
2149
2150 // Assumption: we're reading from the base of the stack slot, not some
2151 // offset into it. It seems very unlikely LLVM would ever generate
2152 // restores where this wasn't true. This then becomes a question of what
2153 // subregisters in the destination register line up with positions in the
2154 // stack slot.
2155
2156 // Def all registers that alias the destination.
2157 for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
2158 MTracker->defReg(R: *RAI, BB: CurBB, Inst: CurInst);
2159
2160 // Now find subregisters within the destination register, and load values
2161 // from stack slot positions.
2162 auto DoTransfer = [&](Register DestReg, unsigned SpillID) {
2163 LocIdx SrcIdx = MTracker->getSpillMLoc(SpillID);
2164 auto ReadValue = MTracker->readMLoc(L: SrcIdx);
2165 MTracker->setReg(R: DestReg, ValueID: ReadValue);
2166 };
2167
2168 for (MCPhysReg SR : TRI->subregs(Reg)) {
2169 unsigned Subreg = TRI->getSubRegIndex(RegNo: Reg, SubRegNo: SR);
2170 unsigned SpillID = MTracker->getLocID(Spill: *Loc, SpillSubReg: Subreg);
2171 DoTransfer(SR, SpillID);
2172 }
2173
2174 // Directly look up this registers slot idx by size, and transfer.
2175 unsigned Size = TRI->getRegSizeInBits(Reg, MRI: *MRI);
2176 unsigned SpillID = MTracker->getLocID(Spill: *Loc, Idx: {Size, 0});
2177 DoTransfer(Reg, SpillID);
2178 }
2179 return true;
2180}
2181
2182bool InstrRefBasedLDV::transferRegisterCopy(MachineInstr &MI) {
2183 auto DestSrc = TII->isCopyLikeInstr(MI);
2184 if (!DestSrc)
2185 return false;
2186
2187 const MachineOperand *DestRegOp = DestSrc->Destination;
2188 const MachineOperand *SrcRegOp = DestSrc->Source;
2189
2190 Register SrcReg = SrcRegOp->getReg();
2191 Register DestReg = DestRegOp->getReg();
2192
2193 // Ignore identity copies. Yep, these make it as far as LiveDebugValues.
2194 if (SrcReg == DestReg)
2195 return true;
2196
2197 // For emulating VarLocBasedImpl:
2198 // We want to recognize instructions where destination register is callee
2199 // saved register. If register that could be clobbered by the call is
2200 // included, there would be a great chance that it is going to be clobbered
2201 // soon. It is more likely that previous register, which is callee saved, is
2202 // going to stay unclobbered longer, even if it is killed.
2203 //
2204 // For InstrRefBasedImpl, we can track multiple locations per value, so
2205 // ignore this condition.
2206 if (EmulateOldLDV && !isCalleeSavedReg(R: DestReg))
2207 return false;
2208
2209 // InstrRefBasedImpl only followed killing copies.
2210 if (EmulateOldLDV && !SrcRegOp->isKill())
2211 return false;
2212
2213 // Before we update MTracker, remember which values were present in each of
2214 // the locations about to be overwritten, so that we can recover any
2215 // potentially clobbered variables.
2216 DenseMap<LocIdx, ValueIDNum> ClobberedLocs;
2217 if (TTracker) {
2218 for (MCRegAliasIterator RAI(DestReg, TRI, true); RAI.isValid(); ++RAI) {
2219 LocIdx ClobberedLoc = MTracker->getRegMLoc(R: *RAI);
2220 auto MLocIt = TTracker->ActiveMLocs.find(Val: ClobberedLoc);
2221 // If ActiveMLocs isn't tracking this location or there are no variables
2222 // using it, don't bother remembering.
2223 if (MLocIt == TTracker->ActiveMLocs.end() || MLocIt->second.empty())
2224 continue;
2225 ValueIDNum Value = MTracker->readReg(R: *RAI);
2226 ClobberedLocs[ClobberedLoc] = Value;
2227 }
2228 }
2229
2230 // Copy MTracker info, including subregs if available.
2231 InstrRefBasedLDV::performCopy(SrcRegNum: SrcReg, DstRegNum: DestReg);
2232
2233 // The copy might have clobbered variables based on the destination register.
2234 // Tell TTracker about it, passing the old ValueIDNum to search for
2235 // alternative locations (or else terminating those variables).
2236 if (TTracker) {
2237 for (auto LocVal : ClobberedLocs) {
2238 TTracker->clobberMloc(MLoc: LocVal.first, OldValue: LocVal.second, Pos: MI.getIterator(), MakeUndef: false);
2239 }
2240 }
2241
2242 // Only produce a transfer of DBG_VALUE within a block where old LDV
2243 // would have. We might make use of the additional value tracking in some
2244 // other way, later.
2245 if (TTracker && isCalleeSavedReg(R: DestReg) && SrcRegOp->isKill())
2246 TTracker->transferMlocs(Src: MTracker->getRegMLoc(R: SrcReg),
2247 Dst: MTracker->getRegMLoc(R: DestReg), Pos: MI.getIterator());
2248
2249 // VarLocBasedImpl would quit tracking the old location after copying.
2250 if (EmulateOldLDV && SrcReg != DestReg)
2251 MTracker->defReg(R: SrcReg, BB: CurBB, Inst: CurInst);
2252
2253 return true;
2254}
2255
2256/// Accumulate a mapping between each DILocalVariable fragment and other
2257/// fragments of that DILocalVariable which overlap. This reduces work during
2258/// the data-flow stage from "Find any overlapping fragments" to "Check if the
2259/// known-to-overlap fragments are present".
2260/// \param MI A previously unprocessed debug instruction to analyze for
2261/// fragment usage.
2262void InstrRefBasedLDV::accumulateFragmentMap(MachineInstr &MI) {
2263 assert(MI.isDebugValueLike());
2264 DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(),
2265 MI.getDebugLoc()->getInlinedAt());
2266 FragmentInfo ThisFragment = MIVar.getFragmentOrDefault();
2267
2268 // If this is the first sighting of this variable, then we are guaranteed
2269 // there are currently no overlapping fragments either. Initialize the set
2270 // of seen fragments, record no overlaps for the current one, and return.
2271 auto [SeenIt, Inserted] = SeenFragments.try_emplace(Key: MIVar.getVariable());
2272 if (Inserted) {
2273 SeenIt->second.insert(V: ThisFragment);
2274
2275 OverlapFragments.insert(KV: {{MIVar.getVariable(), ThisFragment}, {}});
2276 return;
2277 }
2278
2279 // If this particular Variable/Fragment pair already exists in the overlap
2280 // map, it has already been accounted for.
2281 auto IsInOLapMap =
2282 OverlapFragments.insert(KV: {{MIVar.getVariable(), ThisFragment}, {}});
2283 if (!IsInOLapMap.second)
2284 return;
2285
2286 auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
2287 auto &AllSeenFragments = SeenIt->second;
2288
2289 // Otherwise, examine all other seen fragments for this variable, with "this"
2290 // fragment being a previously unseen fragment. Record any pair of
2291 // overlapping fragments.
2292 for (const auto &ASeenFragment : AllSeenFragments) {
2293 // Does this previously seen fragment overlap?
2294 if (DIExpression::fragmentsOverlap(A: ThisFragment, B: ASeenFragment)) {
2295 // Yes: Mark the current fragment as being overlapped.
2296 ThisFragmentsOverlaps.push_back(Elt: ASeenFragment);
2297 // Mark the previously seen fragment as being overlapped by the current
2298 // one.
2299 auto ASeenFragmentsOverlaps =
2300 OverlapFragments.find(Val: {MIVar.getVariable(), ASeenFragment});
2301 assert(ASeenFragmentsOverlaps != OverlapFragments.end() &&
2302 "Previously seen var fragment has no vector of overlaps");
2303 ASeenFragmentsOverlaps->second.push_back(Elt: ThisFragment);
2304 }
2305 }
2306
2307 AllSeenFragments.insert(V: ThisFragment);
2308}
2309
2310void InstrRefBasedLDV::process(MachineInstr &MI,
2311 const FuncValueTable *MLiveOuts,
2312 const FuncValueTable *MLiveIns) {
2313 // Try to interpret an MI as a debug or transfer instruction. Only if it's
2314 // none of these should we interpret it's register defs as new value
2315 // definitions.
2316 if (transferDebugValue(MI))
2317 return;
2318 if (transferDebugInstrRef(MI, MLiveOuts, MLiveIns))
2319 return;
2320 if (transferDebugPHI(MI))
2321 return;
2322 if (transferRegisterCopy(MI))
2323 return;
2324 if (transferSpillOrRestoreInst(MI))
2325 return;
2326 transferRegisterDef(MI);
2327}
2328
2329void InstrRefBasedLDV::produceMLocTransferFunction(
2330 MachineFunction &MF, SmallVectorImpl<MLocTransferMap> &MLocTransfer,
2331 unsigned MaxNumBlocks) {
2332 // Because we try to optimize around register mask operands by ignoring regs
2333 // that aren't currently tracked, we set up something ugly for later: RegMask
2334 // operands that are seen earlier than the first use of a register, still need
2335 // to clobber that register in the transfer function. But this information
2336 // isn't actively recorded. Instead, we track each RegMask used in each block,
2337 // and accumulated the clobbered but untracked registers in each block into
2338 // the following bitvector. Later, if new values are tracked, we can add
2339 // appropriate clobbers.
2340 SmallVector<BitVector, 32> BlockMasks;
2341 BlockMasks.resize(N: MaxNumBlocks);
2342
2343 // Reserve one bit per register for the masks described above.
2344 unsigned BVWords = MachineOperand::getRegMaskSize(NumRegs: TRI->getNumRegs());
2345 for (auto &BV : BlockMasks)
2346 BV.resize(N: TRI->getNumRegs(), t: true);
2347
2348 // Step through all instructions and inhale the transfer function.
2349 for (auto &MBB : MF) {
2350 // Object fields that are read by trackers to know where we are in the
2351 // function.
2352 CurBB = MBB.getNumber();
2353 CurInst = 1;
2354
2355 // Set all machine locations to a PHI value. For transfer function
2356 // production only, this signifies the live-in value to the block.
2357 MTracker->reset();
2358 MTracker->setMPhis(CurBB);
2359
2360 // Step through each instruction in this block.
2361 for (auto &MI : MBB) {
2362 // Pass in an empty unique_ptr for the value tables when accumulating the
2363 // machine transfer function.
2364 process(MI, MLiveOuts: nullptr, MLiveIns: nullptr);
2365
2366 // Also accumulate fragment map.
2367 if (MI.isDebugValueLike())
2368 accumulateFragmentMap(MI);
2369
2370 // Create a map from the instruction number (if present) to the
2371 // MachineInstr and its position.
2372 if (uint64_t InstrNo = MI.peekDebugInstrNum()) {
2373 auto InstrAndPos = std::make_pair(x: &MI, y&: CurInst);
2374 auto InsertResult =
2375 DebugInstrNumToInstr.insert(x: std::make_pair(x&: InstrNo, y&: InstrAndPos));
2376
2377 // There should never be duplicate instruction numbers.
2378 assert(InsertResult.second);
2379 (void)InsertResult;
2380 }
2381
2382 ++CurInst;
2383 }
2384
2385 // Produce the transfer function, a map of machine location to new value. If
2386 // any machine location has the live-in phi value from the start of the
2387 // block, it's live-through and doesn't need recording in the transfer
2388 // function.
2389 for (auto Location : MTracker->locations()) {
2390 LocIdx Idx = Location.Idx;
2391 ValueIDNum &P = Location.Value;
2392 if (P.isPHI() && P.getLoc() == Idx.asU64())
2393 continue;
2394
2395 // Insert-or-update.
2396 auto &TransferMap = MLocTransfer[CurBB];
2397 auto Result = TransferMap.insert(KV: std::make_pair(x: Idx.asU64(), y&: P));
2398 if (!Result.second)
2399 Result.first->second = P;
2400 }
2401
2402 // Accumulate any bitmask operands into the clobbered reg mask for this
2403 // block.
2404 for (auto &P : MTracker->Masks) {
2405 BlockMasks[CurBB].clearBitsNotInMask(Mask: P.first->getRegMask(), MaskWords: BVWords);
2406 }
2407 }
2408
2409 // Compute a bitvector of all the registers that are tracked in this block.
2410 BitVector UsedRegs(TRI->getNumRegs());
2411 for (auto Location : MTracker->locations()) {
2412 unsigned ID = MTracker->LocIdxToLocID[Location.Idx];
2413 // Ignore stack slots, and aliases of the stack pointer.
2414 if (ID >= TRI->getNumRegs() || MTracker->SPAliases.count(V: ID))
2415 continue;
2416 UsedRegs.set(ID);
2417 }
2418
2419 // Check that any regmask-clobber of a register that gets tracked, is not
2420 // live-through in the transfer function. It needs to be clobbered at the
2421 // very least.
2422 for (unsigned int I = 0; I < MaxNumBlocks; ++I) {
2423 BitVector &BV = BlockMasks[I];
2424 BV.flip();
2425 BV &= UsedRegs;
2426 // This produces all the bits that we clobber, but also use. Check that
2427 // they're all clobbered or at least set in the designated transfer
2428 // elem.
2429 for (unsigned Bit : BV.set_bits()) {
2430 unsigned ID = MTracker->getLocID(Reg: Bit);
2431 LocIdx Idx = MTracker->LocIDToLocIdx[ID];
2432 auto &TransferMap = MLocTransfer[I];
2433
2434 // Install a value representing the fact that this location is effectively
2435 // written to in this block. As there's no reserved value, instead use
2436 // a value number that is never generated. Pick the value number for the
2437 // first instruction in the block, def'ing this location, which we know
2438 // this block never used anyway.
2439 ValueIDNum NotGeneratedNum = ValueIDNum(I, 1, Idx);
2440 auto Result =
2441 TransferMap.insert(KV: std::make_pair(x: Idx.asU64(), y&: NotGeneratedNum));
2442 if (!Result.second) {
2443 ValueIDNum &ValueID = Result.first->second;
2444 if (ValueID.getBlock() == I && ValueID.isPHI())
2445 // It was left as live-through. Set it to clobbered.
2446 ValueID = NotGeneratedNum;
2447 }
2448 }
2449 }
2450}
2451
2452bool InstrRefBasedLDV::mlocJoin(
2453 MachineBasicBlock &MBB, SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
2454 FuncValueTable &OutLocs, ValueTable &InLocs) {
2455 LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
2456 bool Changed = false;
2457
2458 // Handle value-propagation when control flow merges on entry to a block. For
2459 // any location without a PHI already placed, the location has the same value
2460 // as its predecessors. If a PHI is placed, test to see whether it's now a
2461 // redundant PHI that we can eliminate.
2462
2463 SmallVector<const MachineBasicBlock *, 8> BlockOrders(MBB.predecessors());
2464
2465 // Visit predecessors in RPOT order.
2466 auto Cmp = [&](const MachineBasicBlock *A, const MachineBasicBlock *B) {
2467 return BBToOrder.find(Val: A)->second < BBToOrder.find(Val: B)->second;
2468 };
2469 llvm::sort(C&: BlockOrders, Comp: Cmp);
2470
2471 // Skip entry block.
2472 if (BlockOrders.size() == 0) {
2473 // FIXME: We don't use assert here to prevent instr-ref-unreachable.mir
2474 // failing.
2475 LLVM_DEBUG(if (!MBB.isEntryBlock()) dbgs()
2476 << "Found not reachable block " << MBB.getFullName()
2477 << " from entry which may lead out of "
2478 "bound access to VarLocs\n");
2479 return false;
2480 }
2481
2482 // Step through all machine locations, look at each predecessor and test
2483 // whether we can eliminate redundant PHIs.
2484 for (auto Location : MTracker->locations()) {
2485 LocIdx Idx = Location.Idx;
2486
2487 // Pick out the first predecessors live-out value for this location. It's
2488 // guaranteed to not be a backedge, as we order by RPO.
2489 ValueIDNum FirstVal = OutLocs[*BlockOrders[0]][Idx.asU64()];
2490
2491 // If we've already eliminated a PHI here, do no further checking, just
2492 // propagate the first live-in value into this block.
2493 if (InLocs[Idx.asU64()] != ValueIDNum(MBB.getNumber(), 0, Idx)) {
2494 if (InLocs[Idx.asU64()] != FirstVal) {
2495 InLocs[Idx.asU64()] = FirstVal;
2496 Changed |= true;
2497 }
2498 continue;
2499 }
2500
2501 // We're now examining a PHI to see whether it's un-necessary. Loop around
2502 // the other live-in values and test whether they're all the same.
2503 bool Disagree = false;
2504 for (unsigned int I = 1; I < BlockOrders.size(); ++I) {
2505 const MachineBasicBlock *PredMBB = BlockOrders[I];
2506 const ValueIDNum &PredLiveOut = OutLocs[*PredMBB][Idx.asU64()];
2507
2508 // Incoming values agree, continue trying to eliminate this PHI.
2509 if (FirstVal == PredLiveOut)
2510 continue;
2511
2512 // We can also accept a PHI value that feeds back into itself.
2513 if (PredLiveOut == ValueIDNum(MBB.getNumber(), 0, Idx))
2514 continue;
2515
2516 // Live-out of a predecessor disagrees with the first predecessor.
2517 Disagree = true;
2518 }
2519
2520 // No disagreement? No PHI. Otherwise, leave the PHI in live-ins.
2521 if (!Disagree) {
2522 InLocs[Idx.asU64()] = FirstVal;
2523 Changed |= true;
2524 }
2525 }
2526
2527 // TODO: Reimplement NumInserted and NumRemoved.
2528 return Changed;
2529}
2530
2531void InstrRefBasedLDV::findStackIndexInterference(
2532 SmallVectorImpl<unsigned> &Slots) {
2533 // We could spend a bit of time finding the exact, minimal, set of stack
2534 // indexes that interfere with each other, much like reg units. Or, we can
2535 // rely on the fact that:
2536 // * The smallest / lowest index will interfere with everything at zero
2537 // offset, which will be the largest set of registers,
2538 // * Most indexes with non-zero offset will end up being interference units
2539 // anyway.
2540 // So just pick those out and return them.
2541
2542 // We can rely on a single-byte stack index existing already, because we
2543 // initialize them in MLocTracker.
2544 auto It = MTracker->StackSlotIdxes.find(Val: {8, 0});
2545 assert(It != MTracker->StackSlotIdxes.end());
2546 Slots.push_back(Elt: It->second);
2547
2548 // Find anything that has a non-zero offset and add that too.
2549 for (auto &Pair : MTracker->StackSlotIdxes) {
2550 // Is offset zero? If so, ignore.
2551 if (!Pair.first.second)
2552 continue;
2553 Slots.push_back(Elt: Pair.second);
2554 }
2555}
2556
2557void InstrRefBasedLDV::placeMLocPHIs(
2558 MachineFunction &MF, SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
2559 FuncValueTable &MInLocs, SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
2560 SmallVector<unsigned, 4> StackUnits;
2561 findStackIndexInterference(Slots&: StackUnits);
2562
2563 // To avoid repeatedly running the PHI placement algorithm, leverage the
2564 // fact that a def of register MUST also def its register units. Find the
2565 // units for registers, place PHIs for them, and then replicate them for
2566 // aliasing registers. Some inputs that are never def'd (DBG_PHIs of
2567 // arguments) don't lead to register units being tracked, just place PHIs for
2568 // those registers directly. Stack slots have their own form of "unit",
2569 // store them to one side.
2570 SmallSet<Register, 32> RegUnitsToPHIUp;
2571 SmallSet<LocIdx, 32> NormalLocsToPHI;
2572 SmallSet<SpillLocationNo, 32> StackSlots;
2573 for (auto Location : MTracker->locations()) {
2574 LocIdx L = Location.Idx;
2575 if (MTracker->isSpill(Idx: L)) {
2576 StackSlots.insert(V: MTracker->locIDToSpill(ID: MTracker->LocIdxToLocID[L]));
2577 continue;
2578 }
2579
2580 Register R = MTracker->LocIdxToLocID[L];
2581 SmallSet<Register, 8> FoundRegUnits;
2582 bool AnyIllegal = false;
2583 for (MCRegUnit Unit : TRI->regunits(Reg: R.asMCReg())) {
2584 for (MCRegUnitRootIterator URoot(Unit, TRI); URoot.isValid(); ++URoot) {
2585 if (!MTracker->isRegisterTracked(R: *URoot)) {
2586 // Not all roots were loaded into the tracking map: this register
2587 // isn't actually def'd anywhere, we only read from it. Generate PHIs
2588 // for this reg, but don't iterate units.
2589 AnyIllegal = true;
2590 } else {
2591 FoundRegUnits.insert(V: *URoot);
2592 }
2593 }
2594 }
2595
2596 if (AnyIllegal) {
2597 NormalLocsToPHI.insert(V: L);
2598 continue;
2599 }
2600
2601 RegUnitsToPHIUp.insert_range(R&: FoundRegUnits);
2602 }
2603
2604 // Lambda to fetch PHIs for a given location, and write into the PHIBlocks
2605 // collection.
2606 SmallVector<MachineBasicBlock *, 32> PHIBlocks;
2607 auto CollectPHIsForLoc = [&](LocIdx L) {
2608 // Collect the set of defs.
2609 SmallPtrSet<MachineBasicBlock *, 32> DefBlocks;
2610 for (MachineBasicBlock *MBB : OrderToBB) {
2611 const auto &TransferFunc = MLocTransfer[MBB->getNumber()];
2612 if (TransferFunc.contains(Val: L))
2613 DefBlocks.insert(Ptr: MBB);
2614 }
2615
2616 // The entry block defs the location too: it's the live-in / argument value.
2617 // Only insert if there are other defs though; everything is trivially live
2618 // through otherwise.
2619 if (!DefBlocks.empty())
2620 DefBlocks.insert(Ptr: &*MF.begin());
2621
2622 // Ask the SSA construction algorithm where we should put PHIs. Clear
2623 // anything that might have been hanging around from earlier.
2624 PHIBlocks.clear();
2625 BlockPHIPlacement(AllBlocks, DefBlocks, PHIBlocks);
2626 };
2627
2628 auto InstallPHIsAtLoc = [&PHIBlocks, &MInLocs](LocIdx L) {
2629 for (const MachineBasicBlock *MBB : PHIBlocks)
2630 MInLocs[*MBB][L.asU64()] = ValueIDNum(MBB->getNumber(), 0, L);
2631 };
2632
2633 // For locations with no reg units, just place PHIs.
2634 for (LocIdx L : NormalLocsToPHI) {
2635 CollectPHIsForLoc(L);
2636 // Install those PHI values into the live-in value array.
2637 InstallPHIsAtLoc(L);
2638 }
2639
2640 // For stack slots, calculate PHIs for the equivalent of the units, then
2641 // install for each index.
2642 for (SpillLocationNo Slot : StackSlots) {
2643 for (unsigned Idx : StackUnits) {
2644 unsigned SpillID = MTracker->getSpillIDWithIdx(Spill: Slot, Idx);
2645 LocIdx L = MTracker->getSpillMLoc(SpillID);
2646 CollectPHIsForLoc(L);
2647 InstallPHIsAtLoc(L);
2648
2649 // Find anything that aliases this stack index, install PHIs for it too.
2650 unsigned Size, Offset;
2651 std::tie(args&: Size, args&: Offset) = MTracker->StackIdxesToPos[Idx];
2652 for (auto &Pair : MTracker->StackSlotIdxes) {
2653 unsigned ThisSize, ThisOffset;
2654 std::tie(args&: ThisSize, args&: ThisOffset) = Pair.first;
2655 if (ThisSize + ThisOffset <= Offset || Size + Offset <= ThisOffset)
2656 continue;
2657
2658 unsigned ThisID = MTracker->getSpillIDWithIdx(Spill: Slot, Idx: Pair.second);
2659 LocIdx ThisL = MTracker->getSpillMLoc(SpillID: ThisID);
2660 InstallPHIsAtLoc(ThisL);
2661 }
2662 }
2663 }
2664
2665 // For reg units, place PHIs, and then place them for any aliasing registers.
2666 for (Register R : RegUnitsToPHIUp) {
2667 LocIdx L = MTracker->lookupOrTrackRegister(ID: MTracker->getLocID(Reg: R));
2668 CollectPHIsForLoc(L);
2669
2670 // Install those PHI values into the live-in value array.
2671 InstallPHIsAtLoc(L);
2672
2673 // Now find aliases and install PHIs for those.
2674 for (MCRegAliasIterator RAI(R, TRI, true); RAI.isValid(); ++RAI) {
2675 // Super-registers that are "above" the largest register read/written by
2676 // the function will alias, but will not be tracked.
2677 if (!MTracker->isRegisterTracked(R: *RAI))
2678 continue;
2679
2680 LocIdx AliasLoc =
2681 MTracker->lookupOrTrackRegister(ID: MTracker->getLocID(Reg: *RAI));
2682 InstallPHIsAtLoc(AliasLoc);
2683 }
2684 }
2685}
2686
2687void InstrRefBasedLDV::buildMLocValueMap(
2688 MachineFunction &MF, FuncValueTable &MInLocs, FuncValueTable &MOutLocs,
2689 SmallVectorImpl<MLocTransferMap> &MLocTransfer) {
2690 std::priority_queue<unsigned int, std::vector<unsigned int>,
2691 std::greater<unsigned int>>
2692 Worklist, Pending;
2693
2694 // We track what is on the current and pending worklist to avoid inserting
2695 // the same thing twice. We could avoid this with a custom priority queue,
2696 // but this is probably not worth it.
2697 SmallPtrSet<MachineBasicBlock *, 16> OnPending, OnWorklist;
2698
2699 // Initialize worklist with every block to be visited. Also produce list of
2700 // all blocks.
2701 SmallPtrSet<MachineBasicBlock *, 32> AllBlocks;
2702 for (unsigned int I = 0; I < BBToOrder.size(); ++I) {
2703 Worklist.push(x: I);
2704 OnWorklist.insert(Ptr: OrderToBB[I]);
2705 AllBlocks.insert(Ptr: OrderToBB[I]);
2706 }
2707
2708 // Initialize entry block to PHIs. These represent arguments.
2709 for (auto Location : MTracker->locations())
2710 MInLocs.tableForEntryMBB()[Location.Idx.asU64()] =
2711 ValueIDNum(0, 0, Location.Idx);
2712
2713 MTracker->reset();
2714
2715 // Start by placing PHIs, using the usual SSA constructor algorithm. Consider
2716 // any machine-location that isn't live-through a block to be def'd in that
2717 // block.
2718 placeMLocPHIs(MF, AllBlocks, MInLocs, MLocTransfer);
2719
2720 // Propagate values to eliminate redundant PHIs. At the same time, this
2721 // produces the table of Block x Location => Value for the entry to each
2722 // block.
2723 // The kind of PHIs we can eliminate are, for example, where one path in a
2724 // conditional spills and restores a register, and the register still has
2725 // the same value once control flow joins, unbeknowns to the PHI placement
2726 // code. Propagating values allows us to identify such un-necessary PHIs and
2727 // remove them.
2728 SmallPtrSet<const MachineBasicBlock *, 16> Visited;
2729 while (!Worklist.empty() || !Pending.empty()) {
2730 // Vector for storing the evaluated block transfer function.
2731 SmallVector<std::pair<LocIdx, ValueIDNum>, 32> ToRemap;
2732
2733 while (!Worklist.empty()) {
2734 MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
2735 CurBB = MBB->getNumber();
2736 Worklist.pop();
2737
2738 // Join the values in all predecessor blocks.
2739 bool InLocsChanged;
2740 InLocsChanged = mlocJoin(MBB&: *MBB, Visited, OutLocs&: MOutLocs, InLocs&: MInLocs[*MBB]);
2741 InLocsChanged |= Visited.insert(Ptr: MBB).second;
2742
2743 // Don't examine transfer function if we've visited this loc at least
2744 // once, and inlocs haven't changed.
2745 if (!InLocsChanged)
2746 continue;
2747
2748 // Load the current set of live-ins into MLocTracker.
2749 MTracker->loadFromArray(Locs&: MInLocs[*MBB], NewCurBB: CurBB);
2750
2751 // Each element of the transfer function can be a new def, or a read of
2752 // a live-in value. Evaluate each element, and store to "ToRemap".
2753 ToRemap.clear();
2754 for (auto &P : MLocTransfer[CurBB]) {
2755 if (P.second.getBlock() == CurBB && P.second.isPHI()) {
2756 // This is a movement of whatever was live in. Read it.
2757 ValueIDNum NewID = MTracker->readMLoc(L: P.second.getLoc());
2758 ToRemap.push_back(Elt: std::make_pair(x&: P.first, y&: NewID));
2759 } else {
2760 // It's a def. Just set it.
2761 assert(P.second.getBlock() == CurBB);
2762 ToRemap.push_back(Elt: std::make_pair(x&: P.first, y&: P.second));
2763 }
2764 }
2765
2766 // Commit the transfer function changes into mloc tracker, which
2767 // transforms the contents of the MLocTracker into the live-outs.
2768 for (auto &P : ToRemap)
2769 MTracker->setMLoc(L: P.first, Num: P.second);
2770
2771 // Now copy out-locs from mloc tracker into out-loc vector, checking
2772 // whether changes have occurred. These changes can have come from both
2773 // the transfer function, and mlocJoin.
2774 bool OLChanged = false;
2775 for (auto Location : MTracker->locations()) {
2776 OLChanged |= MOutLocs[*MBB][Location.Idx.asU64()] != Location.Value;
2777 MOutLocs[*MBB][Location.Idx.asU64()] = Location.Value;
2778 }
2779
2780 MTracker->reset();
2781
2782 // No need to examine successors again if out-locs didn't change.
2783 if (!OLChanged)
2784 continue;
2785
2786 // All successors should be visited: put any back-edges on the pending
2787 // list for the next pass-through, and any other successors to be
2788 // visited this pass, if they're not going to be already.
2789 for (auto *s : MBB->successors()) {
2790 // Does branching to this successor represent a back-edge?
2791 unsigned Order = BBToOrder[s];
2792 if (Order > BBToOrder[MBB]) {
2793 // No: visit it during this dataflow iteration.
2794 if (OnWorklist.insert(Ptr: s).second)
2795 Worklist.push(x: Order);
2796 } else {
2797 // Yes: visit it on the next iteration.
2798 if (OnPending.insert(Ptr: s).second)
2799 Pending.push(x: Order);
2800 }
2801 }
2802 }
2803
2804 Worklist.swap(pq&: Pending);
2805 std::swap(LHS&: OnPending, RHS&: OnWorklist);
2806 OnPending.clear();
2807 // At this point, pending must be empty, since it was just the empty
2808 // worklist
2809 assert(Pending.empty() && "Pending should be empty");
2810 }
2811
2812 // Once all the live-ins don't change on mlocJoin(), we've eliminated all
2813 // redundant PHIs.
2814}
2815
2816void InstrRefBasedLDV::BlockPHIPlacement(
2817 const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks,
2818 const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks,
2819 SmallVectorImpl<MachineBasicBlock *> &PHIBlocks) {
2820 // Apply IDF calculator to the designated set of location defs, storing
2821 // required PHIs into PHIBlocks. Uses the dominator tree stored in the
2822 // InstrRefBasedLDV object.
2823 IDFCalculatorBase<MachineBasicBlock, false> IDF(*DomTree);
2824
2825 IDF.setLiveInBlocks(AllBlocks);
2826 IDF.setDefiningBlocks(DefBlocks);
2827 IDF.calculate(IDFBlocks&: PHIBlocks);
2828}
2829
2830bool InstrRefBasedLDV::pickVPHILoc(
2831 SmallVectorImpl<DbgOpID> &OutValues, const MachineBasicBlock &MBB,
2832 const LiveIdxT &LiveOuts, FuncValueTable &MOutLocs,
2833 const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) {
2834
2835 // No predecessors means no PHIs.
2836 if (BlockOrders.empty())
2837 return false;
2838
2839 // All the location operands that do not already agree need to be joined,
2840 // track the indices of each such location operand here.
2841 SmallDenseSet<unsigned> LocOpsToJoin;
2842
2843 auto FirstValueIt = LiveOuts.find(Val: BlockOrders[0]);
2844 if (FirstValueIt == LiveOuts.end())
2845 return false;
2846 const DbgValue &FirstValue = *FirstValueIt->second;
2847
2848 for (const auto p : BlockOrders) {
2849 auto OutValIt = LiveOuts.find(Val: p);
2850 if (OutValIt == LiveOuts.end())
2851 // If we have a predecessor not in scope, we'll never find a PHI position.
2852 return false;
2853 const DbgValue &OutVal = *OutValIt->second;
2854
2855 // No-values cannot have locations we can join on.
2856 if (OutVal.Kind == DbgValue::NoVal)
2857 return false;
2858
2859 // For unjoined VPHIs where we don't know the location, we definitely
2860 // can't find a join loc unless the VPHI is a backedge.
2861 if (OutVal.isUnjoinedPHI() && OutVal.BlockNo != MBB.getNumber())
2862 return false;
2863
2864 if (!FirstValue.Properties.isJoinable(Other: OutVal.Properties))
2865 return false;
2866
2867 for (unsigned Idx = 0; Idx < FirstValue.getLocationOpCount(); ++Idx) {
2868 // An unjoined PHI has no defined locations, and so a shared location must
2869 // be found for every operand.
2870 if (OutVal.isUnjoinedPHI()) {
2871 LocOpsToJoin.insert(V: Idx);
2872 continue;
2873 }
2874 DbgOpID FirstValOp = FirstValue.getDbgOpID(Index: Idx);
2875 DbgOpID OutValOp = OutVal.getDbgOpID(Index: Idx);
2876 if (FirstValOp != OutValOp) {
2877 // We can never join constant ops - the ops must either both be equal
2878 // constant ops or non-const ops.
2879 if (FirstValOp.isConst() || OutValOp.isConst())
2880 return false;
2881 else
2882 LocOpsToJoin.insert(V: Idx);
2883 }
2884 }
2885 }
2886
2887 SmallVector<DbgOpID> NewDbgOps;
2888
2889 for (unsigned Idx = 0; Idx < FirstValue.getLocationOpCount(); ++Idx) {
2890 // If this op doesn't need to be joined because the values agree, use that
2891 // already-agreed value.
2892 if (!LocOpsToJoin.contains(V: Idx)) {
2893 NewDbgOps.push_back(Elt: FirstValue.getDbgOpID(Index: Idx));
2894 continue;
2895 }
2896
2897 std::optional<ValueIDNum> JoinedOpLoc =
2898 pickOperandPHILoc(DbgOpIdx: Idx, MBB, LiveOuts, MOutLocs, BlockOrders);
2899
2900 if (!JoinedOpLoc)
2901 return false;
2902
2903 NewDbgOps.push_back(Elt: DbgOpStore.insert(Op: *JoinedOpLoc));
2904 }
2905
2906 OutValues.append(RHS: NewDbgOps);
2907 return true;
2908}
2909
2910std::optional<ValueIDNum> InstrRefBasedLDV::pickOperandPHILoc(
2911 unsigned DbgOpIdx, const MachineBasicBlock &MBB, const LiveIdxT &LiveOuts,
2912 FuncValueTable &MOutLocs,
2913 const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) {
2914
2915 // Collect a set of locations from predecessor where its live-out value can
2916 // be found.
2917 SmallVector<SmallVector<LocIdx, 4>, 8> Locs;
2918 unsigned NumLocs = MTracker->getNumLocs();
2919
2920 for (const auto p : BlockOrders) {
2921 auto OutValIt = LiveOuts.find(Val: p);
2922 assert(OutValIt != LiveOuts.end());
2923 const DbgValue &OutVal = *OutValIt->second;
2924 DbgOpID OutValOpID = OutVal.getDbgOpID(Index: DbgOpIdx);
2925 DbgOp OutValOp = DbgOpStore.find(ID: OutValOpID);
2926 assert(!OutValOp.IsConst);
2927
2928 // Create new empty vector of locations.
2929 Locs.resize(N: Locs.size() + 1);
2930
2931 // If the live-in value is a def, find the locations where that value is
2932 // present. Do the same for VPHIs where we know the VPHI value.
2933 if (OutVal.Kind == DbgValue::Def ||
2934 (OutVal.Kind == DbgValue::VPHI && OutVal.BlockNo != MBB.getNumber() &&
2935 !OutValOp.isUndef())) {
2936 ValueIDNum ValToLookFor = OutValOp.ID;
2937 // Search the live-outs of the predecessor for the specified value.
2938 for (unsigned int I = 0; I < NumLocs; ++I) {
2939 if (MOutLocs[*p][I] == ValToLookFor)
2940 Locs.back().push_back(Elt: LocIdx(I));
2941 }
2942 } else {
2943 assert(OutVal.Kind == DbgValue::VPHI);
2944 // Otherwise: this is a VPHI on a backedge feeding back into itself, i.e.
2945 // a value that's live-through the whole loop. (It has to be a backedge,
2946 // because a block can't dominate itself). We can accept as a PHI location
2947 // any location where the other predecessors agree, _and_ the machine
2948 // locations feed back into themselves. Therefore, add all self-looping
2949 // machine-value PHI locations.
2950 for (unsigned int I = 0; I < NumLocs; ++I) {
2951 ValueIDNum MPHI(MBB.getNumber(), 0, LocIdx(I));
2952 if (MOutLocs[*p][I] == MPHI)
2953 Locs.back().push_back(Elt: LocIdx(I));
2954 }
2955 }
2956 }
2957 // We should have found locations for all predecessors, or returned.
2958 assert(Locs.size() == BlockOrders.size());
2959
2960 // Starting with the first set of locations, take the intersection with
2961 // subsequent sets.
2962 SmallVector<LocIdx, 4> CandidateLocs = Locs[0];
2963 for (unsigned int I = 1; I < Locs.size(); ++I) {
2964 auto &LocVec = Locs[I];
2965 SmallVector<LocIdx, 4> NewCandidates;
2966 std::set_intersection(first1: CandidateLocs.begin(), last1: CandidateLocs.end(),
2967 first2: LocVec.begin(), last2: LocVec.end(), result: std::inserter(x&: NewCandidates, i: NewCandidates.begin()));
2968 CandidateLocs = std::move(NewCandidates);
2969 }
2970 if (CandidateLocs.empty())
2971 return std::nullopt;
2972
2973 // We now have a set of LocIdxes that contain the right output value in
2974 // each of the predecessors. Pick the lowest; if there's a register loc,
2975 // that'll be it.
2976 LocIdx L = *CandidateLocs.begin();
2977
2978 // Return a PHI-value-number for the found location.
2979 ValueIDNum PHIVal = {(unsigned)MBB.getNumber(), 0, L};
2980 return PHIVal;
2981}
2982
2983bool InstrRefBasedLDV::vlocJoin(
2984 MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs,
2985 SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore,
2986 DbgValue &LiveIn) {
2987 LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
2988 bool Changed = false;
2989
2990 // Order predecessors by RPOT order, for exploring them in that order.
2991 SmallVector<MachineBasicBlock *, 8> BlockOrders(MBB.predecessors());
2992
2993 auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
2994 return BBToOrder[A] < BBToOrder[B];
2995 };
2996
2997 llvm::sort(C&: BlockOrders, Comp: Cmp);
2998
2999 unsigned CurBlockRPONum = BBToOrder[&MBB];
3000
3001 // Collect all the incoming DbgValues for this variable, from predecessor
3002 // live-out values.
3003 SmallVector<InValueT, 8> Values;
3004 bool Bail = false;
3005 int BackEdgesStart = 0;
3006 for (auto *p : BlockOrders) {
3007 // If the predecessor isn't in scope / to be explored, we'll never be
3008 // able to join any locations.
3009 if (!BlocksToExplore.contains(Ptr: p)) {
3010 Bail = true;
3011 break;
3012 }
3013
3014 // All Live-outs will have been initialized.
3015 DbgValue &OutLoc = *VLOCOutLocs.find(Val: p)->second;
3016
3017 // Keep track of where back-edges begin in the Values vector. Relies on
3018 // BlockOrders being sorted by RPO.
3019 unsigned ThisBBRPONum = BBToOrder[p];
3020 if (ThisBBRPONum < CurBlockRPONum)
3021 ++BackEdgesStart;
3022
3023 Values.push_back(Elt: std::make_pair(x&: p, y: &OutLoc));
3024 }
3025
3026 // If there were no values, or one of the predecessors couldn't have a
3027 // value, then give up immediately. It's not safe to produce a live-in
3028 // value. Leave as whatever it was before.
3029 if (Bail || Values.size() == 0)
3030 return false;
3031
3032 // All (non-entry) blocks have at least one non-backedge predecessor.
3033 // Pick the variable value from the first of these, to compare against
3034 // all others.
3035 const DbgValue &FirstVal = *Values[0].second;
3036
3037 // If the old live-in value is not a PHI then either a) no PHI is needed
3038 // here, or b) we eliminated the PHI that was here. If so, we can just
3039 // propagate in the first parent's incoming value.
3040 if (LiveIn.Kind != DbgValue::VPHI || LiveIn.BlockNo != MBB.getNumber()) {
3041 Changed = LiveIn != FirstVal;
3042 if (Changed)
3043 LiveIn = FirstVal;
3044 return Changed;
3045 }
3046
3047 // Scan for variable values that can never be resolved: if they have
3048 // different DIExpressions, different indirectness, or are mixed constants /
3049 // non-constants.
3050 for (const auto &V : Values) {
3051 if (!V.second->Properties.isJoinable(Other: FirstVal.Properties))
3052 return false;
3053 if (V.second->Kind == DbgValue::NoVal)
3054 return false;
3055 if (!V.second->hasJoinableLocOps(Other: FirstVal))
3056 return false;
3057 }
3058
3059 // Try to eliminate this PHI. Do the incoming values all agree?
3060 bool Disagree = false;
3061 for (auto &V : Values) {
3062 if (*V.second == FirstVal)
3063 continue; // No disagreement.
3064
3065 // If both values are not equal but have equal non-empty IDs then they refer
3066 // to the same value from different sources (e.g. one is VPHI and the other
3067 // is Def), which does not cause disagreement.
3068 if (V.second->hasIdenticalValidLocOps(Other: FirstVal))
3069 continue;
3070
3071 // Eliminate if a backedge feeds a VPHI back into itself.
3072 if (V.second->Kind == DbgValue::VPHI &&
3073 V.second->BlockNo == MBB.getNumber() &&
3074 // Is this a backedge?
3075 std::distance(first: Values.begin(), last: &V) >= BackEdgesStart)
3076 continue;
3077
3078 Disagree = true;
3079 }
3080
3081 // No disagreement -> live-through value.
3082 if (!Disagree) {
3083 Changed = LiveIn != FirstVal;
3084 if (Changed)
3085 LiveIn = FirstVal;
3086 return Changed;
3087 } else {
3088 // Otherwise use a VPHI.
3089 DbgValue VPHI(MBB.getNumber(), FirstVal.Properties, DbgValue::VPHI);
3090 Changed = LiveIn != VPHI;
3091 if (Changed)
3092 LiveIn = VPHI;
3093 return Changed;
3094 }
3095}
3096
3097void InstrRefBasedLDV::getBlocksForScope(
3098 const DILocation *DILoc,
3099 SmallPtrSetImpl<const MachineBasicBlock *> &BlocksToExplore,
3100 const SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks) {
3101 // Get the set of "normal" in-lexical-scope blocks.
3102 LS.getMachineBasicBlocks(DL: DILoc, MBBs&: BlocksToExplore);
3103
3104 // VarLoc LiveDebugValues tracks variable locations that are defined in
3105 // blocks not in scope. This is something we could legitimately ignore, but
3106 // lets allow it for now for the sake of coverage.
3107 BlocksToExplore.insert_range(R: AssignBlocks);
3108
3109 // Storage for artificial blocks we intend to add to BlocksToExplore.
3110 DenseSet<const MachineBasicBlock *> ToAdd;
3111
3112 // To avoid needlessly dropping large volumes of variable locations, propagate
3113 // variables through aritifical blocks, i.e. those that don't have any
3114 // instructions in scope at all. To accurately replicate VarLoc
3115 // LiveDebugValues, this means exploring all artificial successors too.
3116 // Perform a depth-first-search to enumerate those blocks.
3117 for (const auto *MBB : BlocksToExplore) {
3118 // Depth-first-search state: each node is a block and which successor
3119 // we're currently exploring.
3120 SmallVector<std::pair<const MachineBasicBlock *,
3121 MachineBasicBlock::const_succ_iterator>,
3122 8>
3123 DFS;
3124
3125 // Find any artificial successors not already tracked.
3126 for (auto *succ : MBB->successors()) {
3127 if (BlocksToExplore.count(Ptr: succ))
3128 continue;
3129 if (!ArtificialBlocks.count(Ptr: succ))
3130 continue;
3131 ToAdd.insert(V: succ);
3132 DFS.push_back(Elt: {succ, succ->succ_begin()});
3133 }
3134
3135 // Search all those blocks, depth first.
3136 while (!DFS.empty()) {
3137 const MachineBasicBlock *CurBB = DFS.back().first;
3138 MachineBasicBlock::const_succ_iterator &CurSucc = DFS.back().second;
3139 // Walk back if we've explored this blocks successors to the end.
3140 if (CurSucc == CurBB->succ_end()) {
3141 DFS.pop_back();
3142 continue;
3143 }
3144
3145 // If the current successor is artificial and unexplored, descend into
3146 // it.
3147 if (!ToAdd.count(V: *CurSucc) && ArtificialBlocks.count(Ptr: *CurSucc)) {
3148 ToAdd.insert(V: *CurSucc);
3149 DFS.push_back(Elt: {*CurSucc, (*CurSucc)->succ_begin()});
3150 continue;
3151 }
3152
3153 ++CurSucc;
3154 }
3155 };
3156
3157 BlocksToExplore.insert_range(R&: ToAdd);
3158}
3159
3160void InstrRefBasedLDV::buildVLocValueMap(
3161 const DILocation *DILoc,
3162 const SmallSet<DebugVariableID, 4> &VarsWeCareAbout,
3163 SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, LiveInsT &Output,
3164 FuncValueTable &MOutLocs, FuncValueTable &MInLocs,
3165 SmallVectorImpl<VLocTracker> &AllTheVLocs) {
3166 // This method is much like buildMLocValueMap: but focuses on a single
3167 // LexicalScope at a time. Pick out a set of blocks and variables that are
3168 // to have their value assignments solved, then run our dataflow algorithm
3169 // until a fixedpoint is reached.
3170 std::priority_queue<unsigned int, std::vector<unsigned int>,
3171 std::greater<unsigned int>>
3172 Worklist, Pending;
3173 SmallPtrSet<MachineBasicBlock *, 16> OnWorklist, OnPending;
3174
3175 // The set of blocks we'll be examining.
3176 SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
3177
3178 // The order in which to examine them (RPO).
3179 SmallVector<MachineBasicBlock *, 16> BlockOrders;
3180 SmallVector<unsigned, 32> BlockOrderNums;
3181
3182 getBlocksForScope(DILoc, BlocksToExplore, AssignBlocks);
3183
3184 // Single block scope: not interesting! No propagation at all. Note that
3185 // this could probably go above ArtificialBlocks without damage, but
3186 // that then produces output differences from original-live-debug-values,
3187 // which propagates from a single block into many artificial ones.
3188 if (BlocksToExplore.size() == 1)
3189 return;
3190
3191 // Convert a const set to a non-const set. LexicalScopes
3192 // getMachineBasicBlocks returns const MBB pointers, IDF wants mutable ones.
3193 // (Neither of them mutate anything).
3194 SmallPtrSet<MachineBasicBlock *, 8> MutBlocksToExplore;
3195 for (const auto *MBB : BlocksToExplore)
3196 MutBlocksToExplore.insert(Ptr: const_cast<MachineBasicBlock *>(MBB));
3197
3198 // Picks out relevants blocks RPO order and sort them. Sort their
3199 // order-numbers and map back to MBB pointers later, to avoid repeated
3200 // DenseMap queries during comparisons.
3201 for (const auto *MBB : BlocksToExplore)
3202 BlockOrderNums.push_back(Elt: BBToOrder[MBB]);
3203
3204 llvm::sort(C&: BlockOrderNums);
3205 for (unsigned int I : BlockOrderNums)
3206 BlockOrders.push_back(Elt: OrderToBB[I]);
3207 BlockOrderNums.clear();
3208 unsigned NumBlocks = BlockOrders.size();
3209
3210 // Allocate some vectors for storing the live ins and live outs. Large.
3211 SmallVector<DbgValue, 32> LiveIns, LiveOuts;
3212 LiveIns.reserve(N: NumBlocks);
3213 LiveOuts.reserve(N: NumBlocks);
3214
3215 // Initialize all values to start as NoVals. This signifies "it's live
3216 // through, but we don't know what it is".
3217 DbgValueProperties EmptyProperties(EmptyExpr, false, false);
3218 for (unsigned int I = 0; I < NumBlocks; ++I) {
3219 DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal);
3220 LiveIns.push_back(Elt: EmptyDbgValue);
3221 LiveOuts.push_back(Elt: EmptyDbgValue);
3222 }
3223
3224 // Produce by-MBB indexes of live-in/live-outs, to ease lookup within
3225 // vlocJoin.
3226 LiveIdxT LiveOutIdx, LiveInIdx;
3227 LiveOutIdx.reserve(NumEntries: NumBlocks);
3228 LiveInIdx.reserve(NumEntries: NumBlocks);
3229 for (unsigned I = 0; I < NumBlocks; ++I) {
3230 LiveOutIdx[BlockOrders[I]] = &LiveOuts[I];
3231 LiveInIdx[BlockOrders[I]] = &LiveIns[I];
3232 }
3233
3234 // Loop over each variable and place PHIs for it, then propagate values
3235 // between blocks. This keeps the locality of working on one lexical scope at
3236 // at time, but avoids re-processing variable values because some other
3237 // variable has been assigned.
3238 for (DebugVariableID VarID : VarsWeCareAbout) {
3239 // Re-initialize live-ins and live-outs, to clear the remains of previous
3240 // variables live-ins / live-outs.
3241 for (unsigned int I = 0; I < NumBlocks; ++I) {
3242 DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal);
3243 LiveIns[I] = EmptyDbgValue;
3244 LiveOuts[I] = EmptyDbgValue;
3245 }
3246
3247 // Place PHIs for variable values, using the LLVM IDF calculator.
3248 // Collect the set of blocks where variables are def'd.
3249 SmallPtrSet<MachineBasicBlock *, 32> DefBlocks;
3250 for (const MachineBasicBlock *ExpMBB : BlocksToExplore) {
3251 auto &TransferFunc = AllTheVLocs[ExpMBB->getNumber()].Vars;
3252 if (TransferFunc.contains(Key: VarID))
3253 DefBlocks.insert(Ptr: const_cast<MachineBasicBlock *>(ExpMBB));
3254 }
3255
3256 SmallVector<MachineBasicBlock *, 32> PHIBlocks;
3257
3258 // Request the set of PHIs we should insert for this variable. If there's
3259 // only one value definition, things are very simple.
3260 if (DefBlocks.size() == 1) {
3261 placePHIsForSingleVarDefinition(InScopeBlocks: MutBlocksToExplore, MBB: *DefBlocks.begin(),
3262 AllTheVLocs, Var: VarID, Output);
3263 continue;
3264 }
3265
3266 // Otherwise: we need to place PHIs through SSA and propagate values.
3267 BlockPHIPlacement(AllBlocks: MutBlocksToExplore, DefBlocks, PHIBlocks);
3268
3269 // Insert PHIs into the per-block live-in tables for this variable.
3270 for (MachineBasicBlock *PHIMBB : PHIBlocks) {
3271 unsigned BlockNo = PHIMBB->getNumber();
3272 DbgValue *LiveIn = LiveInIdx[PHIMBB];
3273 *LiveIn = DbgValue(BlockNo, EmptyProperties, DbgValue::VPHI);
3274 }
3275
3276 for (auto *MBB : BlockOrders) {
3277 Worklist.push(x: BBToOrder[MBB]);
3278 OnWorklist.insert(Ptr: MBB);
3279 }
3280
3281 // Iterate over all the blocks we selected, propagating the variables value.
3282 // This loop does two things:
3283 // * Eliminates un-necessary VPHIs in vlocJoin,
3284 // * Evaluates the blocks transfer function (i.e. variable assignments) and
3285 // stores the result to the blocks live-outs.
3286 // Always evaluate the transfer function on the first iteration, and when
3287 // the live-ins change thereafter.
3288 bool FirstTrip = true;
3289 while (!Worklist.empty() || !Pending.empty()) {
3290 while (!Worklist.empty()) {
3291 auto *MBB = OrderToBB[Worklist.top()];
3292 CurBB = MBB->getNumber();
3293 Worklist.pop();
3294
3295 auto LiveInsIt = LiveInIdx.find(Val: MBB);
3296 assert(LiveInsIt != LiveInIdx.end());
3297 DbgValue *LiveIn = LiveInsIt->second;
3298
3299 // Join values from predecessors. Updates LiveInIdx, and writes output
3300 // into JoinedInLocs.
3301 bool InLocsChanged =
3302 vlocJoin(MBB&: *MBB, VLOCOutLocs&: LiveOutIdx, BlocksToExplore, LiveIn&: *LiveIn);
3303
3304 SmallVector<const MachineBasicBlock *, 8> Preds(MBB->predecessors());
3305
3306 // If this block's live-in value is a VPHI, try to pick a machine-value
3307 // for it. This makes the machine-value available and propagated
3308 // through all blocks by the time value propagation finishes. We can't
3309 // do this any earlier as it needs to read the block live-outs.
3310 if (LiveIn->Kind == DbgValue::VPHI && LiveIn->BlockNo == (int)CurBB) {
3311 // There's a small possibility that on a preceeding path, a VPHI is
3312 // eliminated and transitions from VPHI-with-location to
3313 // live-through-value. As a result, the selected location of any VPHI
3314 // might change, so we need to re-compute it on each iteration.
3315 SmallVector<DbgOpID> JoinedOps;
3316
3317 if (pickVPHILoc(OutValues&: JoinedOps, MBB: *MBB, LiveOuts: LiveOutIdx, MOutLocs, BlockOrders: Preds)) {
3318 bool NewLocPicked = !equal(LRange: LiveIn->getDbgOpIDs(), RRange&: JoinedOps);
3319 InLocsChanged |= NewLocPicked;
3320 if (NewLocPicked)
3321 LiveIn->setDbgOpIDs(JoinedOps);
3322 }
3323 }
3324
3325 if (!InLocsChanged && !FirstTrip)
3326 continue;
3327
3328 DbgValue *LiveOut = LiveOutIdx[MBB];
3329 bool OLChanged = false;
3330
3331 // Do transfer function.
3332 auto &VTracker = AllTheVLocs[MBB->getNumber()];
3333 auto TransferIt = VTracker.Vars.find(Key: VarID);
3334 if (TransferIt != VTracker.Vars.end()) {
3335 // Erase on empty transfer (DBG_VALUE $noreg).
3336 if (TransferIt->second.Kind == DbgValue::Undef) {
3337 DbgValue NewVal(MBB->getNumber(), EmptyProperties, DbgValue::NoVal);
3338 if (*LiveOut != NewVal) {
3339 *LiveOut = NewVal;
3340 OLChanged = true;
3341 }
3342 } else {
3343 // Insert new variable value; or overwrite.
3344 if (*LiveOut != TransferIt->second) {
3345 *LiveOut = TransferIt->second;
3346 OLChanged = true;
3347 }
3348 }
3349 } else {
3350 // Just copy live-ins to live-outs, for anything not transferred.
3351 if (*LiveOut != *LiveIn) {
3352 *LiveOut = *LiveIn;
3353 OLChanged = true;
3354 }
3355 }
3356
3357 // If no live-out value changed, there's no need to explore further.
3358 if (!OLChanged)
3359 continue;
3360
3361 // We should visit all successors. Ensure we'll visit any non-backedge
3362 // successors during this dataflow iteration; book backedge successors
3363 // to be visited next time around.
3364 for (auto *s : MBB->successors()) {
3365 // Ignore out of scope / not-to-be-explored successors.
3366 if (!LiveInIdx.contains(Val: s))
3367 continue;
3368
3369 unsigned Order = BBToOrder[s];
3370 if (Order > BBToOrder[MBB]) {
3371 if (OnWorklist.insert(Ptr: s).second)
3372 Worklist.push(x: Order);
3373 } else if (OnPending.insert(Ptr: s).second && (FirstTrip || OLChanged)) {
3374 Pending.push(x: Order);
3375 }
3376 }
3377 }
3378 Worklist.swap(pq&: Pending);
3379 std::swap(LHS&: OnWorklist, RHS&: OnPending);
3380 OnPending.clear();
3381 assert(Pending.empty());
3382 FirstTrip = false;
3383 }
3384
3385 // Save live-ins to output vector. Ignore any that are still marked as being
3386 // VPHIs with no location -- those are variables that we know the value of,
3387 // but are not actually available in the register file.
3388 for (auto *MBB : BlockOrders) {
3389 DbgValue *BlockLiveIn = LiveInIdx[MBB];
3390 if (BlockLiveIn->Kind == DbgValue::NoVal)
3391 continue;
3392 if (BlockLiveIn->isUnjoinedPHI())
3393 continue;
3394 if (BlockLiveIn->Kind == DbgValue::VPHI)
3395 BlockLiveIn->Kind = DbgValue::Def;
3396 [[maybe_unused]] auto &[Var, DILoc] = DVMap.lookupDVID(ID: VarID);
3397 assert(BlockLiveIn->Properties.DIExpr->getFragmentInfo() ==
3398 Var.getFragment() &&
3399 "Fragment info missing during value prop");
3400 Output[MBB->getNumber()].push_back(Elt: std::make_pair(x&: VarID, y&: *BlockLiveIn));
3401 }
3402 } // Per-variable loop.
3403
3404 BlockOrders.clear();
3405 BlocksToExplore.clear();
3406}
3407
3408void InstrRefBasedLDV::placePHIsForSingleVarDefinition(
3409 const SmallPtrSetImpl<MachineBasicBlock *> &InScopeBlocks,
3410 MachineBasicBlock *AssignMBB, SmallVectorImpl<VLocTracker> &AllTheVLocs,
3411 DebugVariableID VarID, LiveInsT &Output) {
3412 // If there is a single definition of the variable, then working out it's
3413 // value everywhere is very simple: it's every block dominated by the
3414 // definition. At the dominance frontier, the usual algorithm would:
3415 // * Place PHIs,
3416 // * Propagate values into them,
3417 // * Find there's no incoming variable value from the other incoming branches
3418 // of the dominance frontier,
3419 // * Specify there's no variable value in blocks past the frontier.
3420 // This is a common case, hence it's worth special-casing it.
3421
3422 // Pick out the variables value from the block transfer function.
3423 VLocTracker &VLocs = AllTheVLocs[AssignMBB->getNumber()];
3424 auto ValueIt = VLocs.Vars.find(Key: VarID);
3425 const DbgValue &Value = ValueIt->second;
3426
3427 // If it's an explicit assignment of "undef", that means there is no location
3428 // anyway, anywhere.
3429 if (Value.Kind == DbgValue::Undef)
3430 return;
3431
3432 // Assign the variable value to entry to each dominated block that's in scope.
3433 // Skip the definition block -- it's assigned the variable value in the middle
3434 // of the block somewhere.
3435 for (auto *ScopeBlock : InScopeBlocks) {
3436 if (!DomTree->properlyDominates(A: AssignMBB, B: ScopeBlock))
3437 continue;
3438
3439 Output[ScopeBlock->getNumber()].push_back(Elt: {VarID, Value});
3440 }
3441
3442 // All blocks that aren't dominated have no live-in value, thus no variable
3443 // value will be given to them.
3444}
3445
3446#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3447void InstrRefBasedLDV::dump_mloc_transfer(
3448 const MLocTransferMap &mloc_transfer) const {
3449 for (const auto &P : mloc_transfer) {
3450 std::string foo = MTracker->LocIdxToName(P.first);
3451 std::string bar = MTracker->IDAsString(P.second);
3452 dbgs() << "Loc " << foo << " --> " << bar << "\n";
3453 }
3454}
3455#endif
3456
3457void InstrRefBasedLDV::initialSetup(MachineFunction &MF) {
3458 // Build some useful data structures.
3459
3460 LLVMContext &Context = MF.getFunction().getContext();
3461 EmptyExpr = DIExpression::get(Context, Elements: {});
3462
3463 auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
3464 if (const DebugLoc &DL = MI.getDebugLoc())
3465 return DL.getLine() != 0;
3466 return false;
3467 };
3468
3469 // Collect a set of all the artificial blocks. Collect the size too, ilist
3470 // size calls are O(n).
3471 unsigned int Size = 0;
3472 for (auto &MBB : MF) {
3473 ++Size;
3474 if (none_of(Range: MBB.instrs(), P: hasNonArtificialLocation))
3475 ArtificialBlocks.insert(Ptr: &MBB);
3476 }
3477
3478 // Compute mappings of block <=> RPO order.
3479 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
3480 unsigned int RPONumber = 0;
3481 OrderToBB.reserve(N: Size);
3482 BBToOrder.reserve(NumEntries: Size);
3483 BBNumToRPO.reserve(NumEntries: Size);
3484 auto processMBB = [&](MachineBasicBlock *MBB) {
3485 OrderToBB.push_back(Elt: MBB);
3486 BBToOrder[MBB] = RPONumber;
3487 BBNumToRPO[MBB->getNumber()] = RPONumber;
3488 ++RPONumber;
3489 };
3490 for (MachineBasicBlock *MBB : RPOT)
3491 processMBB(MBB);
3492 for (MachineBasicBlock &MBB : MF)
3493 if (!BBToOrder.contains(Val: &MBB))
3494 processMBB(&MBB);
3495
3496 // Order value substitutions by their "source" operand pair, for quick lookup.
3497 llvm::sort(C&: MF.DebugValueSubstitutions);
3498
3499#ifdef EXPENSIVE_CHECKS
3500 // As an expensive check, test whether there are any duplicate substitution
3501 // sources in the collection.
3502 if (MF.DebugValueSubstitutions.size() > 2) {
3503 for (auto It = MF.DebugValueSubstitutions.begin();
3504 It != std::prev(MF.DebugValueSubstitutions.end()); ++It) {
3505 assert(It->Src != std::next(It)->Src && "Duplicate variable location "
3506 "substitution seen");
3507 }
3508 }
3509#endif
3510}
3511
3512// Produce an "ejection map" for blocks, i.e., what's the highest-numbered
3513// lexical scope it's used in. When exploring in DFS order and we pass that
3514// scope, the block can be processed and any tracking information freed.
3515void InstrRefBasedLDV::makeDepthFirstEjectionMap(
3516 SmallVectorImpl<unsigned> &EjectionMap,
3517 const ScopeToDILocT &ScopeToDILocation,
3518 ScopeToAssignBlocksT &ScopeToAssignBlocks) {
3519 SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
3520 SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack;
3521 auto *TopScope = LS.getCurrentFunctionScope();
3522
3523 // Unlike lexical scope explorers, we explore in reverse order, to find the
3524 // "last" lexical scope used for each block early.
3525 WorkStack.push_back(Elt: {TopScope, TopScope->getChildren().size() - 1});
3526
3527 while (!WorkStack.empty()) {
3528 auto &ScopePosition = WorkStack.back();
3529 LexicalScope *WS = ScopePosition.first;
3530 ssize_t ChildNum = ScopePosition.second--;
3531
3532 const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();
3533 if (ChildNum >= 0) {
3534 // If ChildNum is positive, there are remaining children to explore.
3535 // Push the child and its children-count onto the stack.
3536 auto &ChildScope = Children[ChildNum];
3537 WorkStack.push_back(
3538 Elt: std::make_pair(x: ChildScope, y: ChildScope->getChildren().size() - 1));
3539 } else {
3540 WorkStack.pop_back();
3541
3542 // We've explored all children and any later blocks: examine all blocks
3543 // in our scope. If they haven't yet had an ejection number set, then
3544 // this scope will be the last to use that block.
3545 auto DILocationIt = ScopeToDILocation.find(Val: WS);
3546 if (DILocationIt != ScopeToDILocation.end()) {
3547 getBlocksForScope(DILoc: DILocationIt->second, BlocksToExplore,
3548 AssignBlocks: ScopeToAssignBlocks.find(Val: WS)->second);
3549 for (const auto *MBB : BlocksToExplore) {
3550 unsigned BBNum = MBB->getNumber();
3551 if (EjectionMap[BBNum] == 0)
3552 EjectionMap[BBNum] = WS->getDFSOut();
3553 }
3554
3555 BlocksToExplore.clear();
3556 }
3557 }
3558 }
3559}
3560
3561bool InstrRefBasedLDV::depthFirstVLocAndEmit(
3562 unsigned MaxNumBlocks, const ScopeToDILocT &ScopeToDILocation,
3563 const ScopeToVarsT &ScopeToVars, ScopeToAssignBlocksT &ScopeToAssignBlocks,
3564 LiveInsT &Output, FuncValueTable &MOutLocs, FuncValueTable &MInLocs,
3565 SmallVectorImpl<VLocTracker> &AllTheVLocs, MachineFunction &MF,
3566 bool ShouldEmitDebugEntryValues) {
3567 TTracker = new TransferTracker(TII, MTracker, MF, DVMap, *TRI,
3568 CalleeSavedRegs, ShouldEmitDebugEntryValues);
3569 unsigned NumLocs = MTracker->getNumLocs();
3570 VTracker = nullptr;
3571
3572 // No scopes? No variable locations.
3573 if (!LS.getCurrentFunctionScope())
3574 return false;
3575
3576 // Build map from block number to the last scope that uses the block.
3577 SmallVector<unsigned, 16> EjectionMap;
3578 EjectionMap.resize(N: MaxNumBlocks, NV: 0);
3579 makeDepthFirstEjectionMap(EjectionMap, ScopeToDILocation,
3580 ScopeToAssignBlocks);
3581
3582 // Helper lambda for ejecting a block -- if nothing is going to use the block,
3583 // we can translate the variable location information into DBG_VALUEs and then
3584 // free all of InstrRefBasedLDV's data structures.
3585 auto EjectBlock = [&](MachineBasicBlock &MBB) -> void {
3586 unsigned BBNum = MBB.getNumber();
3587 AllTheVLocs[BBNum].clear();
3588
3589 // Prime the transfer-tracker, and then step through all the block
3590 // instructions, installing transfers.
3591 MTracker->reset();
3592 MTracker->loadFromArray(Locs&: MInLocs[MBB], NewCurBB: BBNum);
3593 TTracker->loadInlocs(MBB, MLocs&: MInLocs[MBB], DbgOpStore, VLocs: Output[BBNum], NumLocs);
3594
3595 CurBB = BBNum;
3596 CurInst = 1;
3597 for (auto &MI : MBB) {
3598 process(MI, MLiveOuts: &MOutLocs, MLiveIns: &MInLocs);
3599 TTracker->checkInstForNewValues(Inst: CurInst, pos: MI.getIterator());
3600 ++CurInst;
3601 }
3602
3603 // Free machine-location tables for this block.
3604 MInLocs.ejectTableForBlock(MBB);
3605 MOutLocs.ejectTableForBlock(MBB);
3606 // We don't need live-in variable values for this block either.
3607 Output[BBNum].clear();
3608 AllTheVLocs[BBNum].clear();
3609 };
3610
3611 SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore;
3612 SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack;
3613 WorkStack.push_back(Elt: {LS.getCurrentFunctionScope(), 0});
3614 unsigned HighestDFSIn = 0;
3615
3616 // Proceed to explore in depth first order.
3617 while (!WorkStack.empty()) {
3618 auto &ScopePosition = WorkStack.back();
3619 LexicalScope *WS = ScopePosition.first;
3620 ssize_t ChildNum = ScopePosition.second++;
3621
3622 // We obesrve scopes with children twice here, once descending in, once
3623 // ascending out of the scope nest. Use HighestDFSIn as a ratchet to ensure
3624 // we don't process a scope twice. Additionally, ignore scopes that don't
3625 // have a DILocation -- by proxy, this means we never tracked any variable
3626 // assignments in that scope.
3627 auto DILocIt = ScopeToDILocation.find(Val: WS);
3628 if (HighestDFSIn <= WS->getDFSIn() && DILocIt != ScopeToDILocation.end()) {
3629 const DILocation *DILoc = DILocIt->second;
3630 auto &VarsWeCareAbout = ScopeToVars.find(Val: WS)->second;
3631 auto &BlocksInScope = ScopeToAssignBlocks.find(Val: WS)->second;
3632
3633 buildVLocValueMap(DILoc, VarsWeCareAbout, AssignBlocks&: BlocksInScope, Output, MOutLocs,
3634 MInLocs, AllTheVLocs);
3635 }
3636
3637 HighestDFSIn = std::max(a: HighestDFSIn, b: WS->getDFSIn());
3638
3639 // Descend into any scope nests.
3640 const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();
3641 if (ChildNum < (ssize_t)Children.size()) {
3642 // There are children to explore -- push onto stack and continue.
3643 auto &ChildScope = Children[ChildNum];
3644 WorkStack.push_back(Elt: std::make_pair(x: ChildScope, y: 0));
3645 } else {
3646 WorkStack.pop_back();
3647
3648 // We've explored a leaf, or have explored all the children of a scope.
3649 // Try to eject any blocks where this is the last scope it's relevant to.
3650 auto DILocationIt = ScopeToDILocation.find(Val: WS);
3651 if (DILocationIt == ScopeToDILocation.end())
3652 continue;
3653
3654 getBlocksForScope(DILoc: DILocationIt->second, BlocksToExplore,
3655 AssignBlocks: ScopeToAssignBlocks.find(Val: WS)->second);
3656 for (const auto *MBB : BlocksToExplore)
3657 if (WS->getDFSOut() == EjectionMap[MBB->getNumber()])
3658 EjectBlock(const_cast<MachineBasicBlock &>(*MBB));
3659
3660 BlocksToExplore.clear();
3661 }
3662 }
3663
3664 // Some artificial blocks may not have been ejected, meaning they're not
3665 // connected to an actual legitimate scope. This can technically happen
3666 // with things like the entry block. In theory, we shouldn't need to do
3667 // anything for such out-of-scope blocks, but for the sake of being similar
3668 // to VarLocBasedLDV, eject these too.
3669 for (auto *MBB : ArtificialBlocks)
3670 if (MInLocs.hasTableFor(MBB&: *MBB))
3671 EjectBlock(*MBB);
3672
3673 return emitTransfers();
3674}
3675
3676bool InstrRefBasedLDV::emitTransfers() {
3677 // Go through all the transfers recorded in the TransferTracker -- this is
3678 // both the live-ins to a block, and any movements of values that happen
3679 // in the middle.
3680 for (auto &P : TTracker->Transfers) {
3681 // We have to insert DBG_VALUEs in a consistent order, otherwise they
3682 // appear in DWARF in different orders. Use the order that they appear
3683 // when walking through each block / each instruction, stored in
3684 // DVMap.
3685 llvm::sort(C&: P.Insts, Comp: llvm::less_first());
3686
3687 // Insert either before or after the designated point...
3688 if (P.MBB) {
3689 MachineBasicBlock &MBB = *P.MBB;
3690 for (const auto &Pair : P.Insts)
3691 MBB.insert(I: P.Pos, M: Pair.second);
3692 } else {
3693 // Terminators, like tail calls, can clobber things. Don't try and place
3694 // transfers after them.
3695 if (P.Pos->isTerminator())
3696 continue;
3697
3698 MachineBasicBlock &MBB = *P.Pos->getParent();
3699 for (const auto &Pair : P.Insts)
3700 MBB.insertAfterBundle(I: P.Pos, MI: Pair.second);
3701 }
3702 }
3703
3704 return TTracker->Transfers.size() != 0;
3705}
3706
3707/// Calculate the liveness information for the given machine function and
3708/// extend ranges across basic blocks.
3709bool InstrRefBasedLDV::ExtendRanges(MachineFunction &MF,
3710 MachineDominatorTree *DomTree,
3711 bool ShouldEmitDebugEntryValues,
3712 unsigned InputBBLimit,
3713 unsigned InputDbgValLimit) {
3714 // No subprogram means this function contains no debuginfo.
3715 if (!MF.getFunction().getSubprogram())
3716 return false;
3717
3718 LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
3719
3720 this->DomTree = DomTree;
3721 TRI = MF.getSubtarget().getRegisterInfo();
3722 MRI = &MF.getRegInfo();
3723 TII = MF.getSubtarget().getInstrInfo();
3724 TFI = MF.getSubtarget().getFrameLowering();
3725 TFI->getCalleeSaves(MF, SavedRegs&: CalleeSavedRegs);
3726 MFI = &MF.getFrameInfo();
3727 LS.scanFunction(MF);
3728
3729 const auto &STI = MF.getSubtarget();
3730 AdjustsStackInCalls = MFI->adjustsStack() &&
3731 STI.getFrameLowering()->stackProbeFunctionModifiesSP();
3732 if (AdjustsStackInCalls)
3733 StackProbeSymbolName = STI.getTargetLowering()->getStackProbeSymbolName(MF);
3734
3735 MTracker =
3736 new MLocTracker(MF, *TII, *TRI, *MF.getSubtarget().getTargetLowering());
3737 VTracker = nullptr;
3738 TTracker = nullptr;
3739
3740 SmallVector<MLocTransferMap, 32> MLocTransfer;
3741 SmallVector<VLocTracker, 8> vlocs;
3742 LiveInsT SavedLiveIns;
3743
3744 int MaxNumBlocks = -1;
3745 for (auto &MBB : MF)
3746 MaxNumBlocks = std::max(a: MBB.getNumber(), b: MaxNumBlocks);
3747 assert(MaxNumBlocks >= 0);
3748 ++MaxNumBlocks;
3749
3750 initialSetup(MF);
3751
3752 MLocTransfer.resize(N: MaxNumBlocks);
3753 vlocs.resize(N: MaxNumBlocks, NV: VLocTracker(DVMap, OverlapFragments, EmptyExpr));
3754 SavedLiveIns.resize(N: MaxNumBlocks);
3755
3756 produceMLocTransferFunction(MF, MLocTransfer, MaxNumBlocks);
3757
3758 // Allocate and initialize two array-of-arrays for the live-in and live-out
3759 // machine values. The outer dimension is the block number; while the inner
3760 // dimension is a LocIdx from MLocTracker.
3761 unsigned NumLocs = MTracker->getNumLocs();
3762 FuncValueTable MOutLocs(MaxNumBlocks, NumLocs);
3763 FuncValueTable MInLocs(MaxNumBlocks, NumLocs);
3764
3765 // Solve the machine value dataflow problem using the MLocTransfer function,
3766 // storing the computed live-ins / live-outs into the array-of-arrays. We use
3767 // both live-ins and live-outs for decision making in the variable value
3768 // dataflow problem.
3769 buildMLocValueMap(MF, MInLocs, MOutLocs, MLocTransfer);
3770
3771 // Patch up debug phi numbers, turning unknown block-live-in values into
3772 // either live-through machine values, or PHIs.
3773 for (auto &DBG_PHI : DebugPHINumToValue) {
3774 // Identify unresolved block-live-ins.
3775 if (!DBG_PHI.ValueRead)
3776 continue;
3777
3778 ValueIDNum &Num = *DBG_PHI.ValueRead;
3779 if (!Num.isPHI())
3780 continue;
3781
3782 unsigned BlockNo = Num.getBlock();
3783 LocIdx LocNo = Num.getLoc();
3784 ValueIDNum ResolvedValue = MInLocs[BlockNo][LocNo.asU64()];
3785 // If there is no resolved value for this live-in then it is not directly
3786 // reachable from the entry block -- model it as a PHI on entry to this
3787 // block, which means we leave the ValueIDNum unchanged.
3788 if (ResolvedValue != ValueIDNum::EmptyValue)
3789 Num = ResolvedValue;
3790 }
3791 // Later, we'll be looking up ranges of instruction numbers.
3792 llvm::sort(C&: DebugPHINumToValue);
3793
3794 // Walk back through each block / instruction, collecting DBG_VALUE
3795 // instructions and recording what machine value their operands refer to.
3796 for (MachineBasicBlock *MBB : OrderToBB) {
3797 CurBB = MBB->getNumber();
3798 VTracker = &vlocs[CurBB];
3799 VTracker->MBB = MBB;
3800 MTracker->loadFromArray(Locs&: MInLocs[*MBB], NewCurBB: CurBB);
3801 CurInst = 1;
3802 for (auto &MI : *MBB) {
3803 process(MI, MLiveOuts: &MOutLocs, MLiveIns: &MInLocs);
3804 ++CurInst;
3805 }
3806 MTracker->reset();
3807 }
3808
3809 // Map from one LexicalScope to all the variables in that scope.
3810 ScopeToVarsT ScopeToVars;
3811
3812 // Map from One lexical scope to all blocks where assignments happen for
3813 // that scope.
3814 ScopeToAssignBlocksT ScopeToAssignBlocks;
3815
3816 // Store map of DILocations that describes scopes.
3817 ScopeToDILocT ScopeToDILocation;
3818
3819 // To mirror old LiveDebugValues, enumerate variables in RPOT order. Otherwise
3820 // the order is unimportant, it just has to be stable.
3821 unsigned VarAssignCount = 0;
3822 for (MachineBasicBlock *MBB : OrderToBB) {
3823 auto *VTracker = &vlocs[MBB->getNumber()];
3824 // Collect each variable with a DBG_VALUE in this block.
3825 for (auto &idx : VTracker->Vars) {
3826 DebugVariableID VarID = idx.first;
3827 const DILocation *ScopeLoc = VTracker->Scopes[VarID];
3828 assert(ScopeLoc != nullptr);
3829 auto *Scope = LS.findLexicalScope(DL: ScopeLoc);
3830
3831 // No insts in scope -> shouldn't have been recorded.
3832 assert(Scope != nullptr);
3833
3834 ScopeToVars[Scope].insert(V: VarID);
3835 ScopeToAssignBlocks[Scope].insert(Ptr: VTracker->MBB);
3836 ScopeToDILocation[Scope] = ScopeLoc;
3837 ++VarAssignCount;
3838 }
3839 }
3840
3841 bool Changed = false;
3842
3843 // If we have an extremely large number of variable assignments and blocks,
3844 // bail out at this point. We've burnt some time doing analysis already,
3845 // however we should cut our losses.
3846 if ((unsigned)MaxNumBlocks > InputBBLimit &&
3847 VarAssignCount > InputDbgValLimit) {
3848 LLVM_DEBUG(dbgs() << "Disabling InstrRefBasedLDV: " << MF.getName()
3849 << " has " << MaxNumBlocks << " basic blocks and "
3850 << VarAssignCount
3851 << " variable assignments, exceeding limits.\n");
3852 } else {
3853 // Optionally, solve the variable value problem and emit to blocks by using
3854 // a lexical-scope-depth search. It should be functionally identical to
3855 // the "else" block of this condition.
3856 Changed = depthFirstVLocAndEmit(
3857 MaxNumBlocks, ScopeToDILocation, ScopeToVars, ScopeToAssignBlocks,
3858 Output&: SavedLiveIns, MOutLocs, MInLocs, AllTheVLocs&: vlocs, MF, ShouldEmitDebugEntryValues);
3859 }
3860
3861 delete MTracker;
3862 delete TTracker;
3863 MTracker = nullptr;
3864 VTracker = nullptr;
3865 TTracker = nullptr;
3866
3867 ArtificialBlocks.clear();
3868 OrderToBB.clear();
3869 BBToOrder.clear();
3870 BBNumToRPO.clear();
3871 DebugInstrNumToInstr.clear();
3872 DebugPHINumToValue.clear();
3873 OverlapFragments.clear();
3874 SeenFragments.clear();
3875 SeenDbgPHIs.clear();
3876 DbgOpStore.clear();
3877 DVMap.clear();
3878
3879 return Changed;
3880}
3881
3882LDVImpl *llvm::makeInstrRefBasedLiveDebugValues() {
3883 return new InstrRefBasedLDV();
3884}
3885
3886namespace {
3887class LDVSSABlock;
3888class LDVSSAUpdater;
3889
3890// Pick a type to identify incoming block values as we construct SSA. We
3891// can't use anything more robust than an integer unfortunately, as SSAUpdater
3892// expects to zero-initialize the type.
3893typedef uint64_t BlockValueNum;
3894
3895/// Represents an SSA PHI node for the SSA updater class. Contains the block
3896/// this PHI is in, the value number it would have, and the expected incoming
3897/// values from parent blocks.
3898class LDVSSAPhi {
3899public:
3900 SmallVector<std::pair<LDVSSABlock *, BlockValueNum>, 4> IncomingValues;
3901 LDVSSABlock *ParentBlock;
3902 BlockValueNum PHIValNum;
3903 LDVSSAPhi(BlockValueNum PHIValNum, LDVSSABlock *ParentBlock)
3904 : ParentBlock(ParentBlock), PHIValNum(PHIValNum) {}
3905
3906 LDVSSABlock *getParent() { return ParentBlock; }
3907};
3908
3909/// Thin wrapper around a block predecessor iterator. Only difference from a
3910/// normal block iterator is that it dereferences to an LDVSSABlock.
3911class LDVSSABlockIterator {
3912public:
3913 MachineBasicBlock::pred_iterator PredIt;
3914 LDVSSAUpdater &Updater;
3915
3916 LDVSSABlockIterator(MachineBasicBlock::pred_iterator PredIt,
3917 LDVSSAUpdater &Updater)
3918 : PredIt(PredIt), Updater(Updater) {}
3919
3920 bool operator!=(const LDVSSABlockIterator &OtherIt) const {
3921 return OtherIt.PredIt != PredIt;
3922 }
3923
3924 LDVSSABlockIterator &operator++() {
3925 ++PredIt;
3926 return *this;
3927 }
3928
3929 LDVSSABlock *operator*();
3930};
3931
3932/// Thin wrapper around a block for SSA Updater interface. Necessary because
3933/// we need to track the PHI value(s) that we may have observed as necessary
3934/// in this block.
3935class LDVSSABlock {
3936public:
3937 MachineBasicBlock &BB;
3938 LDVSSAUpdater &Updater;
3939 using PHIListT = SmallVector<LDVSSAPhi, 1>;
3940 /// List of PHIs in this block. There should only ever be one.
3941 PHIListT PHIList;
3942
3943 LDVSSABlock(MachineBasicBlock &BB, LDVSSAUpdater &Updater)
3944 : BB(BB), Updater(Updater) {}
3945
3946 LDVSSABlockIterator succ_begin() {
3947 return LDVSSABlockIterator(BB.succ_begin(), Updater);
3948 }
3949
3950 LDVSSABlockIterator succ_end() {
3951 return LDVSSABlockIterator(BB.succ_end(), Updater);
3952 }
3953
3954 /// SSAUpdater has requested a PHI: create that within this block record.
3955 LDVSSAPhi *newPHI(BlockValueNum Value) {
3956 PHIList.emplace_back(Args&: Value, Args: this);
3957 return &PHIList.back();
3958 }
3959
3960 /// SSAUpdater wishes to know what PHIs already exist in this block.
3961 PHIListT &phis() { return PHIList; }
3962};
3963
3964/// Utility class for the SSAUpdater interface: tracks blocks, PHIs and values
3965/// while SSAUpdater is exploring the CFG. It's passed as a handle / baton to
3966// SSAUpdaterTraits<LDVSSAUpdater>.
3967class LDVSSAUpdater {
3968public:
3969 /// Map of value numbers to PHI records.
3970 DenseMap<BlockValueNum, LDVSSAPhi *> PHIs;
3971 /// Map of which blocks generate Undef values -- blocks that are not
3972 /// dominated by any Def.
3973 DenseMap<MachineBasicBlock *, BlockValueNum> PoisonMap;
3974 /// Map of machine blocks to our own records of them.
3975 DenseMap<MachineBasicBlock *, LDVSSABlock *> BlockMap;
3976 /// Machine location where any PHI must occur.
3977 LocIdx Loc;
3978 /// Table of live-in machine value numbers for blocks / locations.
3979 const FuncValueTable &MLiveIns;
3980
3981 LDVSSAUpdater(LocIdx L, const FuncValueTable &MLiveIns)
3982 : Loc(L), MLiveIns(MLiveIns) {}
3983
3984 void reset() {
3985 for (auto &Block : BlockMap)
3986 delete Block.second;
3987
3988 PHIs.clear();
3989 PoisonMap.clear();
3990 BlockMap.clear();
3991 }
3992
3993 ~LDVSSAUpdater() { reset(); }
3994
3995 /// For a given MBB, create a wrapper block for it. Stores it in the
3996 /// LDVSSAUpdater block map.
3997 LDVSSABlock *getSSALDVBlock(MachineBasicBlock *BB) {
3998 auto [It, Inserted] = BlockMap.try_emplace(Key: BB);
3999 if (Inserted)
4000 It->second = new LDVSSABlock(*BB, *this);
4001 return It->second;
4002 }
4003
4004 /// Find the live-in value number for the given block. Looks up the value at
4005 /// the PHI location on entry.
4006 BlockValueNum getValue(LDVSSABlock *LDVBB) {
4007 return MLiveIns[LDVBB->BB][Loc.asU64()].asU64();
4008 }
4009};
4010
4011LDVSSABlock *LDVSSABlockIterator::operator*() {
4012 return Updater.getSSALDVBlock(BB: *PredIt);
4013}
4014
4015#ifndef NDEBUG
4016
4017raw_ostream &operator<<(raw_ostream &out, const LDVSSAPhi &PHI) {
4018 out << "SSALDVPHI " << PHI.PHIValNum;
4019 return out;
4020}
4021
4022#endif
4023
4024} // namespace
4025
4026namespace llvm {
4027
4028/// Template specialization to give SSAUpdater access to CFG and value
4029/// information. SSAUpdater calls methods in these traits, passing in the
4030/// LDVSSAUpdater object, to learn about blocks and the values they define.
4031/// It also provides methods to create PHI nodes and track them.
4032template <> class SSAUpdaterTraits<LDVSSAUpdater> {
4033public:
4034 using BlkT = LDVSSABlock;
4035 using ValT = BlockValueNum;
4036 using PhiT = LDVSSAPhi;
4037 using BlkSucc_iterator = LDVSSABlockIterator;
4038
4039 // Methods to access block successors -- dereferencing to our wrapper class.
4040 static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); }
4041 static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); }
4042
4043 /// Iterator for PHI operands.
4044 class PHI_iterator {
4045 private:
4046 LDVSSAPhi *PHI;
4047 unsigned Idx;
4048
4049 public:
4050 explicit PHI_iterator(LDVSSAPhi *P) // begin iterator
4051 : PHI(P), Idx(0) {}
4052 PHI_iterator(LDVSSAPhi *P, bool) // end iterator
4053 : PHI(P), Idx(PHI->IncomingValues.size()) {}
4054
4055 PHI_iterator &operator++() {
4056 Idx++;
4057 return *this;
4058 }
4059 bool operator==(const PHI_iterator &X) const { return Idx == X.Idx; }
4060 bool operator!=(const PHI_iterator &X) const { return !operator==(X); }
4061
4062 BlockValueNum getIncomingValue() { return PHI->IncomingValues[Idx].second; }
4063
4064 LDVSSABlock *getIncomingBlock() { return PHI->IncomingValues[Idx].first; }
4065 };
4066
4067 static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
4068
4069 static inline PHI_iterator PHI_end(PhiT *PHI) {
4070 return PHI_iterator(PHI, true);
4071 }
4072
4073 /// FindPredecessorBlocks - Put the predecessors of BB into the Preds
4074 /// vector.
4075 static void FindPredecessorBlocks(LDVSSABlock *BB,
4076 SmallVectorImpl<LDVSSABlock *> *Preds) {
4077 for (MachineBasicBlock *Pred : BB->BB.predecessors())
4078 Preds->push_back(Elt: BB->Updater.getSSALDVBlock(BB: Pred));
4079 }
4080
4081 /// GetPoisonVal - Normally creates an IMPLICIT_DEF instruction with a new
4082 /// register. For LiveDebugValues, represents a block identified as not having
4083 /// any DBG_PHI predecessors.
4084 static BlockValueNum GetPoisonVal(LDVSSABlock *BB, LDVSSAUpdater *Updater) {
4085 // Create a value number for this block -- it needs to be unique and in the
4086 // "poison" collection, so that we know it's not real. Use a number
4087 // representing a PHI into this block.
4088 BlockValueNum Num = ValueIDNum(BB->BB.getNumber(), 0, Updater->Loc).asU64();
4089 Updater->PoisonMap[&BB->BB] = Num;
4090 return Num;
4091 }
4092
4093 /// CreateEmptyPHI - Create a (representation of a) PHI in the given block.
4094 /// SSAUpdater will populate it with information about incoming values. The
4095 /// value number of this PHI is whatever the machine value number problem
4096 /// solution determined it to be. This includes non-phi values if SSAUpdater
4097 /// tries to create a PHI where the incoming values are identical.
4098 static BlockValueNum CreateEmptyPHI(LDVSSABlock *BB, unsigned NumPreds,
4099 LDVSSAUpdater *Updater) {
4100 BlockValueNum PHIValNum = Updater->getValue(LDVBB: BB);
4101 LDVSSAPhi *PHI = BB->newPHI(Value: PHIValNum);
4102 Updater->PHIs[PHIValNum] = PHI;
4103 return PHIValNum;
4104 }
4105
4106 /// AddPHIOperand - Add the specified value as an operand of the PHI for
4107 /// the specified predecessor block.
4108 static void AddPHIOperand(LDVSSAPhi *PHI, BlockValueNum Val, LDVSSABlock *Pred) {
4109 PHI->IncomingValues.push_back(Elt: std::make_pair(x&: Pred, y&: Val));
4110 }
4111
4112 /// ValueIsPHI - Check if the instruction that defines the specified value
4113 /// is a PHI instruction.
4114 static LDVSSAPhi *ValueIsPHI(BlockValueNum Val, LDVSSAUpdater *Updater) {
4115 return Updater->PHIs.lookup(Val);
4116 }
4117
4118 /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
4119 /// operands, i.e., it was just added.
4120 static LDVSSAPhi *ValueIsNewPHI(BlockValueNum Val, LDVSSAUpdater *Updater) {
4121 LDVSSAPhi *PHI = ValueIsPHI(Val, Updater);
4122 if (PHI && PHI->IncomingValues.size() == 0)
4123 return PHI;
4124 return nullptr;
4125 }
4126
4127 /// GetPHIValue - For the specified PHI instruction, return the value
4128 /// that it defines.
4129 static BlockValueNum GetPHIValue(LDVSSAPhi *PHI) { return PHI->PHIValNum; }
4130};
4131
4132} // end namespace llvm
4133
4134std::optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIs(
4135 MachineFunction &MF, const FuncValueTable &MLiveOuts,
4136 const FuncValueTable &MLiveIns, MachineInstr &Here, uint64_t InstrNum) {
4137 // This function will be called twice per DBG_INSTR_REF, and might end up
4138 // computing lots of SSA information: memoize it.
4139 auto SeenDbgPHIIt = SeenDbgPHIs.find(Val: std::make_pair(x: &Here, y&: InstrNum));
4140 if (SeenDbgPHIIt != SeenDbgPHIs.end())
4141 return SeenDbgPHIIt->second;
4142
4143 std::optional<ValueIDNum> Result =
4144 resolveDbgPHIsImpl(MF, MLiveOuts, MLiveIns, Here, InstrNum);
4145 SeenDbgPHIs.insert(KV: {std::make_pair(x: &Here, y&: InstrNum), Result});
4146 return Result;
4147}
4148
4149std::optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIsImpl(
4150 MachineFunction &MF, const FuncValueTable &MLiveOuts,
4151 const FuncValueTable &MLiveIns, MachineInstr &Here, uint64_t InstrNum) {
4152 // Pick out records of DBG_PHI instructions that have been observed. If there
4153 // are none, then we cannot compute a value number.
4154 auto RangePair = std::equal_range(first: DebugPHINumToValue.begin(),
4155 last: DebugPHINumToValue.end(), val: InstrNum);
4156 auto LowerIt = RangePair.first;
4157 auto UpperIt = RangePair.second;
4158
4159 // No DBG_PHI means there can be no location.
4160 if (LowerIt == UpperIt)
4161 return std::nullopt;
4162
4163 // If any DBG_PHIs referred to a location we didn't understand, don't try to
4164 // compute a value. There might be scenarios where we could recover a value
4165 // for some range of DBG_INSTR_REFs, but at this point we can have high
4166 // confidence that we've seen a bug.
4167 auto DBGPHIRange = make_range(x: LowerIt, y: UpperIt);
4168 for (const DebugPHIRecord &DBG_PHI : DBGPHIRange)
4169 if (!DBG_PHI.ValueRead)
4170 return std::nullopt;
4171
4172 // If there's only one DBG_PHI, then that is our value number.
4173 if (std::distance(first: LowerIt, last: UpperIt) == 1)
4174 return *LowerIt->ValueRead;
4175
4176 // Pick out the location (physreg, slot) where any PHIs must occur. It's
4177 // technically possible for us to merge values in different registers in each
4178 // block, but highly unlikely that LLVM will generate such code after register
4179 // allocation.
4180 LocIdx Loc = *LowerIt->ReadLoc;
4181
4182 // We have several DBG_PHIs, and a use position (the Here inst). All each
4183 // DBG_PHI does is identify a value at a program position. We can treat each
4184 // DBG_PHI like it's a Def of a value, and the use position is a Use of a
4185 // value, just like SSA. We use the bulk-standard LLVM SSA updater class to
4186 // determine which Def is used at the Use, and any PHIs that happen along
4187 // the way.
4188 // Adapted LLVM SSA Updater:
4189 LDVSSAUpdater Updater(Loc, MLiveIns);
4190 // Map of which Def or PHI is the current value in each block.
4191 DenseMap<LDVSSABlock *, BlockValueNum> AvailableValues;
4192 // Set of PHIs that we have created along the way.
4193 SmallVector<LDVSSAPhi *, 8> CreatedPHIs;
4194
4195 // Each existing DBG_PHI is a Def'd value under this model. Record these Defs
4196 // for the SSAUpdater.
4197 for (const auto &DBG_PHI : DBGPHIRange) {
4198 LDVSSABlock *Block = Updater.getSSALDVBlock(BB: DBG_PHI.MBB);
4199 const ValueIDNum &Num = *DBG_PHI.ValueRead;
4200 AvailableValues.insert(KV: std::make_pair(x&: Block, y: Num.asU64()));
4201 }
4202
4203 LDVSSABlock *HereBlock = Updater.getSSALDVBlock(BB: Here.getParent());
4204 const auto &AvailIt = AvailableValues.find(Val: HereBlock);
4205 if (AvailIt != AvailableValues.end()) {
4206 // Actually, we already know what the value is -- the Use is in the same
4207 // block as the Def.
4208 return ValueIDNum::fromU64(v: AvailIt->second);
4209 }
4210
4211 // Otherwise, we must use the SSA Updater. It will identify the value number
4212 // that we are to use, and the PHIs that must happen along the way.
4213 SSAUpdaterImpl<LDVSSAUpdater> Impl(&Updater, &AvailableValues, &CreatedPHIs);
4214 BlockValueNum ResultInt = Impl.GetValue(BB: Updater.getSSALDVBlock(BB: Here.getParent()));
4215 ValueIDNum Result = ValueIDNum::fromU64(v: ResultInt);
4216
4217 // We have the number for a PHI, or possibly live-through value, to be used
4218 // at this Use. There are a number of things we have to check about it though:
4219 // * Does any PHI use an 'Undef' (like an IMPLICIT_DEF) value? If so, this
4220 // Use was not completely dominated by DBG_PHIs and we should abort.
4221 // * Are the Defs or PHIs clobbered in a block? SSAUpdater isn't aware that
4222 // we've left SSA form. Validate that the inputs to each PHI are the
4223 // expected values.
4224 // * Is a PHI we've created actually a merging of values, or are all the
4225 // predecessor values the same, leading to a non-PHI machine value number?
4226 // (SSAUpdater doesn't know that either). Remap validated PHIs into the
4227 // the ValidatedValues collection below to sort this out.
4228 DenseMap<LDVSSABlock *, ValueIDNum> ValidatedValues;
4229
4230 // Define all the input DBG_PHI values in ValidatedValues.
4231 for (const auto &DBG_PHI : DBGPHIRange) {
4232 LDVSSABlock *Block = Updater.getSSALDVBlock(BB: DBG_PHI.MBB);
4233 const ValueIDNum &Num = *DBG_PHI.ValueRead;
4234 ValidatedValues.insert(KV: std::make_pair(x&: Block, y: Num));
4235 }
4236
4237 // Sort PHIs to validate into RPO-order.
4238 SmallVector<LDVSSAPhi *, 8> SortedPHIs(CreatedPHIs);
4239
4240 llvm::sort(C&: SortedPHIs, Comp: [&](LDVSSAPhi *A, LDVSSAPhi *B) {
4241 return BBToOrder[&A->getParent()->BB] < BBToOrder[&B->getParent()->BB];
4242 });
4243
4244 for (auto &PHI : SortedPHIs) {
4245 ValueIDNum ThisBlockValueNum = MLiveIns[PHI->ParentBlock->BB][Loc.asU64()];
4246
4247 // Are all these things actually defined?
4248 for (auto &PHIIt : PHI->IncomingValues) {
4249 // Any undef input means DBG_PHIs didn't dominate the use point.
4250 if (Updater.PoisonMap.contains(Val: &PHIIt.first->BB))
4251 return std::nullopt;
4252
4253 ValueIDNum ValueToCheck;
4254 const ValueTable &BlockLiveOuts = MLiveOuts[PHIIt.first->BB];
4255
4256 auto VVal = ValidatedValues.find(Val: PHIIt.first);
4257 if (VVal == ValidatedValues.end()) {
4258 // We cross a loop, and this is a backedge. LLVMs tail duplication
4259 // happens so late that DBG_PHI instructions should not be able to
4260 // migrate into loops -- meaning we can only be live-through this
4261 // loop.
4262 ValueToCheck = ThisBlockValueNum;
4263 } else {
4264 // Does the block have as a live-out, in the location we're examining,
4265 // the value that we expect? If not, it's been moved or clobbered.
4266 ValueToCheck = VVal->second;
4267 }
4268
4269 if (BlockLiveOuts[Loc.asU64()] != ValueToCheck)
4270 return std::nullopt;
4271 }
4272
4273 // Record this value as validated.
4274 ValidatedValues.insert(KV: {PHI->ParentBlock, ThisBlockValueNum});
4275 }
4276
4277 // All the PHIs are valid: we can return what the SSAUpdater said our value
4278 // number was.
4279 return Result;
4280}
4281