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