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