LLVM  10.0.0
LiveDebugValues.cpp
Go to the documentation of this file.
1 //===- LiveDebugValues.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 ///
9 /// This pass implements a data flow analysis that propagates debug location
10 /// information by inserting additional DBG_VALUE insts into the machine
11 /// instruction stream. Before running, each DBG_VALUE inst corresponds to a
12 /// source assignment of a variable. Afterwards, a DBG_VALUE inst specifies a
13 /// variable location for the current basic block (see SourceLevelDebugging.rst).
14 ///
15 /// This is a separate pass from DbgValueHistoryCalculator to facilitate
16 /// testing and improve modularity.
17 ///
18 /// Each variable location is represented by a VarLoc object that identifies the
19 /// source variable, its current machine-location, and the DBG_VALUE inst that
20 /// specifies the location. Each VarLoc is indexed in the (function-scope)
21 /// VarLocMap, giving each VarLoc a unique index. Rather than operate directly
22 /// on machine locations, the dataflow analysis in this pass identifies
23 /// locations by their index in the VarLocMap, meaning all the variable
24 /// locations in a block can be described by a sparse vector of VarLocMap
25 /// indexes.
26 ///
27 //===----------------------------------------------------------------------===//
28 
29 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/UniqueVector.h"
54 #include "llvm/Config/llvm-config.h"
55 #include "llvm/IR/DIBuilder.h"
57 #include "llvm/IR/DebugLoc.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/IR/Module.h"
60 #include "llvm/InitializePasses.h"
61 #include "llvm/MC/MCRegisterInfo.h"
62 #include "llvm/Pass.h"
63 #include "llvm/Support/Casting.h"
64 #include "llvm/Support/Compiler.h"
65 #include "llvm/Support/Debug.h"
67 #include <algorithm>
68 #include <cassert>
69 #include <cstdint>
70 #include <functional>
71 #include <queue>
72 #include <tuple>
73 #include <utility>
74 #include <vector>
75 
76 using namespace llvm;
77 
78 #define DEBUG_TYPE "livedebugvalues"
79 
80 STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted");
81 STATISTIC(NumRemoved, "Number of DBG_VALUE instructions removed");
82 
83 // If @MI is a DBG_VALUE with debug value described by a defined
84 // register, returns the number of this register. In the other case, returns 0.
86  assert(MI.isDebugValue() && "expected a DBG_VALUE");
87  assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
88  // If location of variable is described using a register (directly
89  // or indirectly), this register is always a first operand.
90  return MI.getOperand(0).isReg() ? MI.getOperand(0).getReg() : Register();
91 }
92 
93 /// If \p Op is a stack or frame register return true, otherwise return false.
94 /// This is used to avoid basing the debug entry values on the registers, since
95 /// we do not support it at the moment.
97  const MachineInstr &MI,
98  const TargetRegisterInfo *TRI) {
99  if (!Op.isReg())
100  return false;
101 
102  const MachineFunction *MF = MI.getParent()->getParent();
103  const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
104  unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
105  Register FP = TRI->getFrameRegister(*MF);
106  Register Reg = Op.getReg();
107 
108  return Reg && Reg != SP && Reg != FP;
109 }
110 
111 namespace {
112 
113 using DefinedRegsSet = SmallSet<Register, 32>;
114 
115 class LiveDebugValues : public MachineFunctionPass {
116 private:
117  const TargetRegisterInfo *TRI;
118  const TargetInstrInfo *TII;
119  const TargetFrameLowering *TFI;
120  BitVector CalleeSavedRegs;
122 
123  enum struct TransferKind { TransferCopy, TransferSpill, TransferRestore };
124 
125  /// Keeps track of lexical scopes associated with a user value's source
126  /// location.
127  class UserValueScopes {
128  DebugLoc DL;
129  LexicalScopes &LS;
131 
132  public:
133  UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(std::move(D)), LS(L) {}
134 
135  /// Return true if current scope dominates at least one machine
136  /// instruction in a given machine basic block.
137  bool dominates(MachineBasicBlock *MBB) {
138  if (LBlocks.empty())
139  LS.getMachineBasicBlocks(DL, LBlocks);
140  return LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB);
141  }
142  };
143 
144  using FragmentInfo = DIExpression::FragmentInfo;
145  using OptFragmentInfo = Optional<DIExpression::FragmentInfo>;
146 
147  /// A pair of debug variable and value location.
148  struct VarLoc {
149  // The location at which a spilled variable resides. It consists of a
150  // register and an offset.
151  struct SpillLoc {
152  unsigned SpillBase;
153  int SpillOffset;
154  bool operator==(const SpillLoc &Other) const {
155  return SpillBase == Other.SpillBase && SpillOffset == Other.SpillOffset;
156  }
157  };
158 
159  /// Identity of the variable at this location.
160  const DebugVariable Var;
161 
162  /// The expression applied to this location.
163  const DIExpression *Expr;
164 
165  /// DBG_VALUE to clone var/expr information from if this location
166  /// is moved.
167  const MachineInstr &MI;
168 
169  mutable UserValueScopes UVS;
170  enum VarLocKind {
171  InvalidKind = 0,
172  RegisterKind,
173  SpillLocKind,
174  ImmediateKind,
175  EntryValueKind,
176  EntryValueBackupKind,
177  EntryValueCopyBackupKind
178  } Kind = InvalidKind;
179 
180  /// The value location. Stored separately to avoid repeatedly
181  /// extracting it from MI.
182  union {
183  uint64_t RegNo;
184  SpillLoc SpillLocation;
185  uint64_t Hash;
186  int64_t Immediate;
187  const ConstantFP *FPImm;
188  const ConstantInt *CImm;
189  } Loc;
190 
191  VarLoc(const MachineInstr &MI, LexicalScopes &LS)
192  : Var(MI.getDebugVariable(), MI.getDebugExpression(),
193  MI.getDebugLoc()->getInlinedAt()),
194  Expr(MI.getDebugExpression()), MI(MI), UVS(MI.getDebugLoc(), LS) {
195  static_assert((sizeof(Loc) == sizeof(uint64_t)),
196  "hash does not cover all members of Loc");
197  assert(MI.isDebugValue() && "not a DBG_VALUE");
198  assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE");
199  if (int RegNo = isDbgValueDescribedByReg(MI)) {
200  Kind = RegisterKind;
201  Loc.RegNo = RegNo;
202  } else if (MI.getOperand(0).isImm()) {
203  Kind = ImmediateKind;
204  Loc.Immediate = MI.getOperand(0).getImm();
205  } else if (MI.getOperand(0).isFPImm()) {
206  Kind = ImmediateKind;
207  Loc.FPImm = MI.getOperand(0).getFPImm();
208  } else if (MI.getOperand(0).isCImm()) {
209  Kind = ImmediateKind;
210  Loc.CImm = MI.getOperand(0).getCImm();
211  }
212 
213  // We create the debug entry values from the factory functions rather than
214  // from this ctor.
215  assert(Kind != EntryValueKind && !isEntryBackupLoc());
216  }
217 
218  /// Take the variable and machine-location in DBG_VALUE MI, and build an
219  /// entry location using the given expression.
220  static VarLoc CreateEntryLoc(const MachineInstr &MI, LexicalScopes &LS,
221  const DIExpression *EntryExpr, unsigned Reg) {
222  VarLoc VL(MI, LS);
223  assert(VL.Kind == RegisterKind);
224  VL.Kind = EntryValueKind;
225  VL.Expr = EntryExpr;
226  VL.Loc.RegNo = Reg;
227  return VL;
228  }
229 
230  /// Take the variable and machine-location from the DBG_VALUE (from the
231  /// function entry), and build an entry value backup location. The backup
232  /// location will turn into the normal location if the backup is valid at
233  /// the time of the primary location clobbering.
234  static VarLoc CreateEntryBackupLoc(const MachineInstr &MI,
235  LexicalScopes &LS,
236  const DIExpression *EntryExpr) {
237  VarLoc VL(MI, LS);
238  assert(VL.Kind == RegisterKind);
239  VL.Kind = EntryValueBackupKind;
240  VL.Expr = EntryExpr;
241  return VL;
242  }
243 
244  /// Take the variable and machine-location from the DBG_VALUE (from the
245  /// function entry), and build a copy of an entry value backup location by
246  /// setting the register location to NewReg.
247  static VarLoc CreateEntryCopyBackupLoc(const MachineInstr &MI,
248  LexicalScopes &LS,
249  const DIExpression *EntryExpr,
250  unsigned NewReg) {
251  VarLoc VL(MI, LS);
252  assert(VL.Kind == RegisterKind);
253  VL.Kind = EntryValueCopyBackupKind;
254  VL.Expr = EntryExpr;
255  VL.Loc.RegNo = NewReg;
256  return VL;
257  }
258 
259  /// Copy the register location in DBG_VALUE MI, updating the register to
260  /// be NewReg.
261  static VarLoc CreateCopyLoc(const MachineInstr &MI, LexicalScopes &LS,
262  unsigned NewReg) {
263  VarLoc VL(MI, LS);
264  assert(VL.Kind == RegisterKind);
265  VL.Loc.RegNo = NewReg;
266  return VL;
267  }
268 
269  /// Take the variable described by DBG_VALUE MI, and create a VarLoc
270  /// locating it in the specified spill location.
271  static VarLoc CreateSpillLoc(const MachineInstr &MI, unsigned SpillBase,
272  int SpillOffset, LexicalScopes &LS) {
273  VarLoc VL(MI, LS);
274  assert(VL.Kind == RegisterKind);
275  VL.Kind = SpillLocKind;
276  VL.Loc.SpillLocation = {SpillBase, SpillOffset};
277  return VL;
278  }
279 
280  /// Create a DBG_VALUE representing this VarLoc in the given function.
281  /// Copies variable-specific information such as DILocalVariable and
282  /// inlining information from the original DBG_VALUE instruction, which may
283  /// have been several transfers ago.
284  MachineInstr *BuildDbgValue(MachineFunction &MF) const {
285  const DebugLoc &DbgLoc = MI.getDebugLoc();
286  bool Indirect = MI.isIndirectDebugValue();
287  const auto &IID = MI.getDesc();
288  const DILocalVariable *Var = MI.getDebugVariable();
289  const DIExpression *DIExpr = MI.getDebugExpression();
290 
291  switch (Kind) {
292  case EntryValueKind:
293  // An entry value is a register location -- but with an updated
294  // expression. The register location of such DBG_VALUE is always the one
295  // from the entry DBG_VALUE, it does not matter if the entry value was
296  // copied in to another register due to some optimizations.
297  return BuildMI(MF, DbgLoc, IID, Indirect, MI.getOperand(0).getReg(),
298  Var, Expr);
299  case RegisterKind:
300  // Register locations are like the source DBG_VALUE, but with the
301  // register number from this VarLoc.
302  return BuildMI(MF, DbgLoc, IID, Indirect, Loc.RegNo, Var, DIExpr);
303  case SpillLocKind: {
304  // Spills are indirect DBG_VALUEs, with a base register and offset.
305  // Use the original DBG_VALUEs expression to build the spilt location
306  // on top of. FIXME: spill locations created before this pass runs
307  // are not recognized, and not handled here.
308  auto *SpillExpr = DIExpression::prepend(
309  DIExpr, DIExpression::ApplyOffset, Loc.SpillLocation.SpillOffset);
310  unsigned Base = Loc.SpillLocation.SpillBase;
311  return BuildMI(MF, DbgLoc, IID, true, Base, Var, SpillExpr);
312  }
313  case ImmediateKind: {
314  MachineOperand MO = MI.getOperand(0);
315  return BuildMI(MF, DbgLoc, IID, Indirect, MO, Var, DIExpr);
316  }
317  case EntryValueBackupKind:
318  case EntryValueCopyBackupKind:
319  case InvalidKind:
321  "Tried to produce DBG_VALUE for invalid or backup VarLoc");
322  }
323  llvm_unreachable("Unrecognized LiveDebugValues.VarLoc.Kind enum");
324  }
325 
326  /// Is the Loc field a constant or constant object?
327  bool isConstant() const { return Kind == ImmediateKind; }
328 
329  /// Check if the Loc field is an entry backup location.
330  bool isEntryBackupLoc() const {
331  return Kind == EntryValueBackupKind || Kind == EntryValueCopyBackupKind;
332  }
333 
334  /// If this variable is described by a register holding the entry value,
335  /// return it, otherwise return 0.
336  unsigned getEntryValueBackupReg() const {
337  if (Kind == EntryValueBackupKind)
338  return Loc.RegNo;
339  return 0;
340  }
341 
342  /// If this variable is described by a register holding the copy of the
343  /// entry value, return it, otherwise return 0.
344  unsigned getEntryValueCopyBackupReg() const {
345  if (Kind == EntryValueCopyBackupKind)
346  return Loc.RegNo;
347  return 0;
348  }
349 
350  /// If this variable is described by a register, return it,
351  /// otherwise return 0.
352  unsigned isDescribedByReg() const {
353  if (Kind == RegisterKind)
354  return Loc.RegNo;
355  return 0;
356  }
357 
358  /// Determine whether the lexical scope of this value's debug location
359  /// dominates MBB.
360  bool dominates(MachineBasicBlock &MBB) const { return UVS.dominates(&MBB); }
361 
362 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
363  // TRI can be null.
364  void dump(const TargetRegisterInfo *TRI, raw_ostream &Out = dbgs()) const {
365  dbgs() << "VarLoc(";
366  switch (Kind) {
367  case RegisterKind:
368  case EntryValueKind:
369  case EntryValueBackupKind:
370  case EntryValueCopyBackupKind:
371  dbgs() << printReg(Loc.RegNo, TRI);
372  break;
373  case SpillLocKind:
374  dbgs() << printReg(Loc.SpillLocation.SpillBase, TRI);
375  dbgs() << "[" << Loc.SpillLocation.SpillOffset << "]";
376  break;
377  case ImmediateKind:
378  dbgs() << Loc.Immediate;
379  break;
380  case InvalidKind:
381  llvm_unreachable("Invalid VarLoc in dump method");
382  }
383 
384  dbgs() << ", \"" << Var.getVariable()->getName() << "\", " << *Expr
385  << ", ";
386  if (Var.getInlinedAt())
387  dbgs() << "!" << Var.getInlinedAt()->getMetadataID() << ")\n";
388  else
389  dbgs() << "(null))";
390 
391  if (isEntryBackupLoc())
392  dbgs() << " (backup loc)\n";
393  else
394  dbgs() << "\n";
395  }
396 #endif
397 
398  bool operator==(const VarLoc &Other) const {
399  return Kind == Other.Kind && Var == Other.Var &&
400  Loc.Hash == Other.Loc.Hash && Expr == Other.Expr;
401  }
402 
403  /// This operator guarantees that VarLocs are sorted by Variable first.
404  bool operator<(const VarLoc &Other) const {
405  return std::tie(Var, Kind, Loc.Hash, Expr) <
406  std::tie(Other.Var, Other.Kind, Other.Loc.Hash, Other.Expr);
407  }
408  };
409 
410  using VarLocMap = UniqueVector<VarLoc>;
411  using VarLocSet = SparseBitVector<>;
413  struct TransferDebugPair {
414  MachineInstr *TransferInst; /// Instruction where this transfer occurs.
415  unsigned LocationID; /// Location number for the transfer dest.
416  };
417  using TransferMap = SmallVector<TransferDebugPair, 4>;
418 
419  // Types for recording sets of variable fragments that overlap. For a given
420  // local variable, we record all other fragments of that variable that could
421  // overlap it, to reduce search time.
422  using FragmentOfVar =
423  std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
424  using OverlapMap =
426 
427  // Helper while building OverlapMap, a map of all fragments seen for a given
428  // DILocalVariable.
429  using VarToFragments =
431 
432  /// This holds the working set of currently open ranges. For fast
433  /// access, this is done both as a set of VarLocIDs, and a map of
434  /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
435  /// previous open ranges for the same variable. In addition, we keep
436  /// two different maps (Vars/EntryValuesBackupVars), so erase/insert
437  /// methods act differently depending on whether a VarLoc is primary
438  /// location or backup one. In the case the VarLoc is backup location
439  /// we will erase/insert from the EntryValuesBackupVars map, otherwise
440  /// we perform the operation on the Vars.
441  class OpenRangesSet {
442  VarLocSet VarLocs;
443  // Map the DebugVariable to recent primary location ID.
445  // Map the DebugVariable to recent backup location ID.
446  SmallDenseMap<DebugVariable, unsigned, 8> EntryValuesBackupVars;
447  OverlapMap &OverlappingFragments;
448 
449  public:
450  OpenRangesSet(OverlapMap &_OLapMap) : OverlappingFragments(_OLapMap) {}
451 
452  const VarLocSet &getVarLocs() const { return VarLocs; }
453 
454  /// Terminate all open ranges for VL.Var by removing it from the set.
455  void erase(const VarLoc &VL);
456 
457  /// Terminate all open ranges listed in \c KillSet by removing
458  /// them from the set.
459  void erase(const VarLocSet &KillSet, const VarLocMap &VarLocIDs);
460 
461  /// Insert a new range into the set.
462  void insert(unsigned VarLocID, const VarLoc &VL);
463 
464  /// Insert a set of ranges.
465  void insertFromLocSet(const VarLocSet &ToLoad, const VarLocMap &Map) {
466  for (unsigned Id : ToLoad) {
467  const VarLoc &VarL = Map[Id];
468  insert(Id, VarL);
469  }
470  }
471 
472  llvm::Optional<unsigned> getEntryValueBackup(DebugVariable Var);
473 
474  /// Empty the set.
475  void clear() {
476  VarLocs.clear();
477  Vars.clear();
478  EntryValuesBackupVars.clear();
479  }
480 
481  /// Return whether the set is empty or not.
482  bool empty() const {
483  assert(Vars.empty() == EntryValuesBackupVars.empty() &&
484  Vars.empty() == VarLocs.empty() &&
485  "open ranges are inconsistent");
486  return VarLocs.empty();
487  }
488  };
489 
490  /// Tests whether this instruction is a spill to a stack location.
491  bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF);
492 
493  /// Decide if @MI is a spill instruction and return true if it is. We use 2
494  /// criteria to make this decision:
495  /// - Is this instruction a store to a spill slot?
496  /// - Is there a register operand that is both used and killed?
497  /// TODO: Store optimization can fold spills into other stores (including
498  /// other spills). We do not handle this yet (more than one memory operand).
499  bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF,
500  unsigned &Reg);
501 
502  /// Returns true if the given machine instruction is a debug value which we
503  /// can emit entry values for.
504  ///
505  /// Currently, we generate debug entry values only for parameters that are
506  /// unmodified throughout the function and located in a register.
507  bool isEntryValueCandidate(const MachineInstr &MI,
508  const DefinedRegsSet &Regs) const;
509 
510  /// If a given instruction is identified as a spill, return the spill location
511  /// and set \p Reg to the spilled register.
512  Optional<VarLoc::SpillLoc> isRestoreInstruction(const MachineInstr &MI,
513  MachineFunction *MF,
514  unsigned &Reg);
515  /// Given a spill instruction, extract the register and offset used to
516  /// address the spill location in a target independent way.
517  VarLoc::SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI);
518  void insertTransferDebugPair(MachineInstr &MI, OpenRangesSet &OpenRanges,
519  TransferMap &Transfers, VarLocMap &VarLocIDs,
520  unsigned OldVarID, TransferKind Kind,
521  unsigned NewReg = 0);
522 
523  void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
524  VarLocMap &VarLocIDs);
525  void transferSpillOrRestoreInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
526  VarLocMap &VarLocIDs, TransferMap &Transfers);
527  bool removeEntryValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
528  VarLocMap &VarLocIDs, const VarLoc &EntryVL);
529  void emitEntryValues(MachineInstr &MI, OpenRangesSet &OpenRanges,
530  VarLocMap &VarLocIDs, TransferMap &Transfers,
531  SparseBitVector<> &KillSet);
532  void recordEntryValue(const MachineInstr &MI,
533  const DefinedRegsSet &DefinedRegs,
534  OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs);
535  void transferRegisterCopy(MachineInstr &MI, OpenRangesSet &OpenRanges,
536  VarLocMap &VarLocIDs, TransferMap &Transfers);
537  void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
538  VarLocMap &VarLocIDs, TransferMap &Transfers);
539  bool transferTerminator(MachineBasicBlock *MBB, OpenRangesSet &OpenRanges,
540  VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
541 
542  void process(MachineInstr &MI, OpenRangesSet &OpenRanges,
543  VarLocMap &VarLocIDs, TransferMap &Transfers);
544 
545  void accumulateFragmentMap(MachineInstr &MI, VarToFragments &SeenFragments,
546  OverlapMap &OLapMap);
547 
548  bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
549  const VarLocMap &VarLocIDs,
552  VarLocInMBB &PendingInLocs);
553 
554  /// Create DBG_VALUE insts for inlocs that have been propagated but
555  /// had their instruction creation deferred.
556  void flushPendingLocs(VarLocInMBB &PendingInLocs, VarLocMap &VarLocIDs);
557 
558  bool ExtendRanges(MachineFunction &MF);
559 
560 public:
561  static char ID;
562 
563  /// Default construct and initialize the pass.
564  LiveDebugValues();
565 
566  /// Tell the pass manager which passes we depend on and what
567  /// information we preserve.
568  void getAnalysisUsage(AnalysisUsage &AU) const override;
569 
570  MachineFunctionProperties getRequiredProperties() const override {
573  }
574 
575  /// Print to ostream with a message.
576  void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
577  const VarLocMap &VarLocIDs, const char *msg,
578  raw_ostream &Out) const;
579 
580  /// Calculate the liveness information for the given machine function.
581  bool runOnMachineFunction(MachineFunction &MF) override;
582 };
583 
584 } // end anonymous namespace
585 
586 //===----------------------------------------------------------------------===//
587 // Implementation
588 //===----------------------------------------------------------------------===//
589 
590 char LiveDebugValues::ID = 0;
591 
593 
594 INITIALIZE_PASS(LiveDebugValues, DEBUG_TYPE, "Live DEBUG_VALUE analysis",
595  false, false)
596 
597 /// Default construct and initialize the pass.
598 LiveDebugValues::LiveDebugValues() : MachineFunctionPass(ID) {
600 }
601 
602 /// Tell the pass manager which passes we depend on and what information we
603 /// preserve.
604 void LiveDebugValues::getAnalysisUsage(AnalysisUsage &AU) const {
605  AU.setPreservesCFG();
607 }
608 
609 /// Erase a variable from the set of open ranges, and additionally erase any
610 /// fragments that may overlap it. If the VarLoc is a buckup location, erase
611 /// the variable from the EntryValuesBackupVars set, indicating we should stop
612 /// tracking its backup entry location. Otherwise, if the VarLoc is primary
613 /// location, erase the variable from the Vars set.
614 void LiveDebugValues::OpenRangesSet::erase(const VarLoc &VL) {
615  // Erasure helper.
616  auto DoErase = [VL, this](DebugVariable VarToErase) {
617  auto *EraseFrom = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
618  auto It = EraseFrom->find(VarToErase);
619  if (It != EraseFrom->end()) {
620  unsigned ID = It->second;
621  VarLocs.reset(ID);
622  EraseFrom->erase(It);
623  }
624  };
625 
626  DebugVariable Var = VL.Var;
627 
628  // Erase the variable/fragment that ends here.
629  DoErase(Var);
630 
631  // Extract the fragment. Interpret an empty fragment as one that covers all
632  // possible bits.
633  FragmentInfo ThisFragment = Var.getFragmentOrDefault();
634 
635  // There may be fragments that overlap the designated fragment. Look them up
636  // in the pre-computed overlap map, and erase them too.
637  auto MapIt = OverlappingFragments.find({Var.getVariable(), ThisFragment});
638  if (MapIt != OverlappingFragments.end()) {
639  for (auto Fragment : MapIt->second) {
640  LiveDebugValues::OptFragmentInfo FragmentHolder;
641  if (!DebugVariable::isDefaultFragment(Fragment))
642  FragmentHolder = LiveDebugValues::OptFragmentInfo(Fragment);
643  DoErase({Var.getVariable(), FragmentHolder, Var.getInlinedAt()});
644  }
645  }
646 }
647 
648 void LiveDebugValues::OpenRangesSet::erase(const VarLocSet &KillSet,
649  const VarLocMap &VarLocIDs) {
650  VarLocs.intersectWithComplement(KillSet);
651  for (unsigned ID : KillSet) {
652  const VarLoc *VL = &VarLocIDs[ID];
653  auto *EraseFrom = VL->isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
654  EraseFrom->erase(VL->Var);
655  }
656 }
657 
658 void LiveDebugValues::OpenRangesSet::insert(unsigned VarLocID,
659  const VarLoc &VL) {
660  auto *InsertInto = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
661  VarLocs.set(VarLocID);
662  InsertInto->insert({VL.Var, VarLocID});
663 }
664 
665 /// Return the Loc ID of an entry value backup location, if it exists for the
666 /// variable.
668 LiveDebugValues::OpenRangesSet::getEntryValueBackup(DebugVariable Var) {
669  auto It = EntryValuesBackupVars.find(Var);
670  if (It != EntryValuesBackupVars.end())
671  return It->second;
672 
673  return llvm::None;
674 }
675 
676 //===----------------------------------------------------------------------===//
677 // Debug Range Extension Implementation
678 //===----------------------------------------------------------------------===//
679 
680 #ifndef NDEBUG
681 void LiveDebugValues::printVarLocInMBB(const MachineFunction &MF,
682  const VarLocInMBB &V,
683  const VarLocMap &VarLocIDs,
684  const char *msg,
685  raw_ostream &Out) const {
686  Out << '\n' << msg << '\n';
687  for (const MachineBasicBlock &BB : MF) {
688  const VarLocSet &L = V.lookup(&BB);
689  if (L.empty())
690  continue;
691  Out << "MBB: " << BB.getNumber() << ":\n";
692  for (unsigned VLL : L) {
693  const VarLoc &VL = VarLocIDs[VLL];
694  Out << " Var: " << VL.Var.getVariable()->getName();
695  Out << " MI: ";
696  VL.dump(TRI, Out);
697  }
698  }
699  Out << "\n";
700 }
701 #endif
702 
703 LiveDebugValues::VarLoc::SpillLoc
704 LiveDebugValues::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
705  assert(MI.hasOneMemOperand() &&
706  "Spill instruction does not have exactly one memory operand?");
707  auto MMOI = MI.memoperands_begin();
708  const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
710  "Inconsistent memory operand in spill instruction");
711  int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
712  const MachineBasicBlock *MBB = MI.getParent();
713  unsigned Reg;
714  int Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
715  return {Reg, Offset};
716 }
717 
718 /// Try to salvage the debug entry value if we encounter a new debug value
719 /// describing the same parameter, otherwise stop tracking the value. Return
720 /// true if we should stop tracking the entry value, otherwise return false.
721 bool LiveDebugValues::removeEntryValue(const MachineInstr &MI,
722  OpenRangesSet &OpenRanges,
723  VarLocMap &VarLocIDs,
724  const VarLoc &EntryVL) {
725  // Skip the DBG_VALUE which is the debug entry value itself.
726  if (MI.isIdenticalTo(EntryVL.MI))
727  return false;
728 
729  // If the parameter's location is not register location, we can not track
730  // the entry value any more. In addition, if the debug expression from the
731  // DBG_VALUE is not empty, we can assume the parameter's value has changed
732  // indicating that we should stop tracking its entry value as well.
733  if (!MI.getOperand(0).isReg() ||
734  MI.getDebugExpression()->getNumElements() != 0)
735  return true;
736 
737  // If the DBG_VALUE comes from a copy instruction that copies the entry value,
738  // it means the parameter's value has not changed and we should be able to use
739  // its entry value.
740  bool TrySalvageEntryValue = false;
741  Register Reg = MI.getOperand(0).getReg();
742  auto I = std::next(MI.getReverseIterator());
743  const MachineOperand *SrcRegOp, *DestRegOp;
744  if (I != MI.getParent()->rend()) {
745  // TODO: Try to keep tracking of an entry value if we encounter a propagated
746  // DBG_VALUE describing the copy of the entry value. (Propagated entry value
747  // does not indicate the parameter modification.)
748  auto DestSrc = TII->isCopyInstr(*I);
749  if (!DestSrc)
750  return true;
751 
752  SrcRegOp = DestSrc->Source;
753  DestRegOp = DestSrc->Destination;
754  if (Reg != DestRegOp->getReg())
755  return true;
756  TrySalvageEntryValue = true;
757  }
758 
759  if (TrySalvageEntryValue) {
760  for (unsigned ID : OpenRanges.getVarLocs()) {
761  const VarLoc &VL = VarLocIDs[ID];
762  if (!VL.isEntryBackupLoc())
763  continue;
764 
765  if (VL.getEntryValueCopyBackupReg() == Reg &&
766  VL.MI.getOperand(0).getReg() == SrcRegOp->getReg())
767  return false;
768  }
769  }
770 
771  return true;
772 }
773 
774 /// End all previous ranges related to @MI and start a new range from @MI
775 /// if it is a DBG_VALUE instr.
776 void LiveDebugValues::transferDebugValue(const MachineInstr &MI,
777  OpenRangesSet &OpenRanges,
778  VarLocMap &VarLocIDs) {
779  if (!MI.isDebugValue())
780  return;
781  const DILocalVariable *Var = MI.getDebugVariable();
782  const DIExpression *Expr = MI.getDebugExpression();
783  const DILocation *DebugLoc = MI.getDebugLoc();
784  const DILocation *InlinedAt = DebugLoc->getInlinedAt();
785  assert(Var->isValidLocationForIntrinsic(DebugLoc) &&
786  "Expected inlined-at fields to agree");
787 
788  DebugVariable V(Var, Expr, InlinedAt);
789 
790  // Check if this DBG_VALUE indicates a parameter's value changing.
791  // If that is the case, we should stop tracking its entry value.
792  auto EntryValBackupID = OpenRanges.getEntryValueBackup(V);
793  if (Var->isParameter() && EntryValBackupID) {
794  const VarLoc &EntryVL = VarLocIDs[*EntryValBackupID];
795  if (removeEntryValue(MI, OpenRanges, VarLocIDs, EntryVL)) {
796  LLVM_DEBUG(dbgs() << "Deleting a DBG entry value because of: ";
797  MI.print(dbgs(), /*IsStandalone*/ false,
798  /*SkipOpers*/ false, /*SkipDebugLoc*/ false,
799  /*AddNewLine*/ true, TII));
800  OpenRanges.erase(EntryVL);
801  }
802  }
803 
804  unsigned ID;
805  if (isDbgValueDescribedByReg(MI) || MI.getOperand(0).isImm() ||
806  MI.getOperand(0).isFPImm() || MI.getOperand(0).isCImm()) {
807  // Use normal VarLoc constructor for registers and immediates.
808  VarLoc VL(MI, LS);
809  // End all previous ranges of VL.Var.
810  OpenRanges.erase(VL);
811 
812  ID = VarLocIDs.insert(VL);
813  // Add the VarLoc to OpenRanges from this DBG_VALUE.
814  OpenRanges.insert(ID, VL);
815  } else if (MI.hasOneMemOperand()) {
816  llvm_unreachable("DBG_VALUE with mem operand encountered after regalloc?");
817  } else {
818  // This must be an undefined location. We should leave OpenRanges closed.
819  assert(MI.getOperand(0).isReg() && MI.getOperand(0).getReg() == 0 &&
820  "Unexpected non-undef DBG_VALUE encountered");
821  }
822 }
823 
824 /// Turn the entry value backup locations into primary locations.
825 void LiveDebugValues::emitEntryValues(MachineInstr &MI,
826  OpenRangesSet &OpenRanges,
827  VarLocMap &VarLocIDs,
828  TransferMap &Transfers,
829  SparseBitVector<> &KillSet) {
830  for (unsigned ID : KillSet) {
831  if (!VarLocIDs[ID].Var.getVariable()->isParameter())
832  continue;
833 
834  auto DebugVar = VarLocIDs[ID].Var;
835  auto EntryValBackupID = OpenRanges.getEntryValueBackup(DebugVar);
836 
837  // If the parameter has the entry value backup, it means we should
838  // be able to use its entry value.
839  if (!EntryValBackupID)
840  continue;
841 
842  const VarLoc &EntryVL = VarLocIDs[*EntryValBackupID];
843  VarLoc EntryLoc =
844  VarLoc::CreateEntryLoc(EntryVL.MI, LS, EntryVL.Expr, EntryVL.Loc.RegNo);
845  unsigned EntryValueID = VarLocIDs.insert(EntryLoc);
846  Transfers.push_back({&MI, EntryValueID});
847  OpenRanges.insert(EntryValueID, EntryLoc);
848  }
849 }
850 
851 /// Create new TransferDebugPair and insert it in \p Transfers. The VarLoc
852 /// with \p OldVarID should be deleted form \p OpenRanges and replaced with
853 /// new VarLoc. If \p NewReg is different than default zero value then the
854 /// new location will be register location created by the copy like instruction,
855 /// otherwise it is variable's location on the stack.
856 void LiveDebugValues::insertTransferDebugPair(
857  MachineInstr &MI, OpenRangesSet &OpenRanges, TransferMap &Transfers,
858  VarLocMap &VarLocIDs, unsigned OldVarID, TransferKind Kind,
859  unsigned NewReg) {
860  const MachineInstr *DebugInstr = &VarLocIDs[OldVarID].MI;
861 
862  auto ProcessVarLoc = [&MI, &OpenRanges, &Transfers, &VarLocIDs](VarLoc &VL) {
863  unsigned LocId = VarLocIDs.insert(VL);
864 
865  // Close this variable's previous location range.
866  OpenRanges.erase(VL);
867 
868  // Record the new location as an open range, and a postponed transfer
869  // inserting a DBG_VALUE for this location.
870  OpenRanges.insert(LocId, VL);
871  TransferDebugPair MIP = {&MI, LocId};
872  Transfers.push_back(MIP);
873  };
874 
875  // End all previous ranges of VL.Var.
876  OpenRanges.erase(VarLocIDs[OldVarID]);
877  switch (Kind) {
878  case TransferKind::TransferCopy: {
879  assert(NewReg &&
880  "No register supplied when handling a copy of a debug value");
881  // Create a DBG_VALUE instruction to describe the Var in its new
882  // register location.
883  VarLoc VL = VarLoc::CreateCopyLoc(*DebugInstr, LS, NewReg);
884  ProcessVarLoc(VL);
885  LLVM_DEBUG({
886  dbgs() << "Creating VarLoc for register copy:";
887  VL.dump(TRI);
888  });
889  return;
890  }
891  case TransferKind::TransferSpill: {
892  // Create a DBG_VALUE instruction to describe the Var in its spilled
893  // location.
894  VarLoc::SpillLoc SpillLocation = extractSpillBaseRegAndOffset(MI);
895  VarLoc VL = VarLoc::CreateSpillLoc(*DebugInstr, SpillLocation.SpillBase,
896  SpillLocation.SpillOffset, LS);
897  ProcessVarLoc(VL);
898  LLVM_DEBUG({
899  dbgs() << "Creating VarLoc for spill:";
900  VL.dump(TRI);
901  });
902  return;
903  }
904  case TransferKind::TransferRestore: {
905  assert(NewReg &&
906  "No register supplied when handling a restore of a debug value");
907  // DebugInstr refers to the pre-spill location, therefore we can reuse
908  // its expression.
909  VarLoc VL = VarLoc::CreateCopyLoc(*DebugInstr, LS, NewReg);
910  ProcessVarLoc(VL);
911  LLVM_DEBUG({
912  dbgs() << "Creating VarLoc for restore:";
913  VL.dump(TRI);
914  });
915  return;
916  }
917  }
918  llvm_unreachable("Invalid transfer kind");
919 }
920 
921 /// A definition of a register may mark the end of a range.
922 void LiveDebugValues::transferRegisterDef(
923  MachineInstr &MI, OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs,
924  TransferMap &Transfers) {
925  MachineFunction *MF = MI.getMF();
926  const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
927  unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
928  SparseBitVector<> KillSet;
929  for (const MachineOperand &MO : MI.operands()) {
930  // Determine whether the operand is a register def. Assume that call
931  // instructions never clobber SP, because some backends (e.g., AArch64)
932  // never list SP in the regmask.
933  if (MO.isReg() && MO.isDef() && MO.getReg() &&
934  Register::isPhysicalRegister(MO.getReg()) &&
935  !(MI.isCall() && MO.getReg() == SP)) {
936  // Remove ranges of all aliased registers.
937  for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
938  for (unsigned ID : OpenRanges.getVarLocs())
939  if (VarLocIDs[ID].isDescribedByReg() == *RAI)
940  KillSet.set(ID);
941  } else if (MO.isRegMask()) {
942  // Remove ranges of all clobbered registers. Register masks don't usually
943  // list SP as preserved. While the debug info may be off for an
944  // instruction or two around callee-cleanup calls, transferring the
945  // DEBUG_VALUE across the call is still a better user experience.
946  for (unsigned ID : OpenRanges.getVarLocs()) {
947  unsigned Reg = VarLocIDs[ID].isDescribedByReg();
948  if (Reg && Reg != SP && MO.clobbersPhysReg(Reg))
949  KillSet.set(ID);
950  }
951  }
952  }
953  OpenRanges.erase(KillSet, VarLocIDs);
954 
955  if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
956  auto &TM = TPC->getTM<TargetMachine>();
957  if (TM.Options.EnableDebugEntryValues)
958  emitEntryValues(MI, OpenRanges, VarLocIDs, Transfers, KillSet);
959  }
960 }
961 
962 bool LiveDebugValues::isSpillInstruction(const MachineInstr &MI,
963  MachineFunction *MF) {
964  // TODO: Handle multiple stores folded into one.
965  if (!MI.hasOneMemOperand())
966  return false;
967 
968  if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
969  return false; // This is not a spill instruction, since no valid size was
970  // returned from either function.
971 
972  return true;
973 }
974 
975 bool LiveDebugValues::isLocationSpill(const MachineInstr &MI,
976  MachineFunction *MF, unsigned &Reg) {
977  if (!isSpillInstruction(MI, MF))
978  return false;
979 
980  auto isKilledReg = [&](const MachineOperand MO, unsigned &Reg) {
981  if (!MO.isReg() || !MO.isUse()) {
982  Reg = 0;
983  return false;
984  }
985  Reg = MO.getReg();
986  return MO.isKill();
987  };
988 
989  for (const MachineOperand &MO : MI.operands()) {
990  // In a spill instruction generated by the InlineSpiller the spilled
991  // register has its kill flag set.
992  if (isKilledReg(MO, Reg))
993  return true;
994  if (Reg != 0) {
995  // Check whether next instruction kills the spilled register.
996  // FIXME: Current solution does not cover search for killed register in
997  // bundles and instructions further down the chain.
998  auto NextI = std::next(MI.getIterator());
999  // Skip next instruction that points to basic block end iterator.
1000  if (MI.getParent()->end() == NextI)
1001  continue;
1002  unsigned RegNext;
1003  for (const MachineOperand &MONext : NextI->operands()) {
1004  // Return true if we came across the register from the
1005  // previous spill instruction that is killed in NextI.
1006  if (isKilledReg(MONext, RegNext) && RegNext == Reg)
1007  return true;
1008  }
1009  }
1010  }
1011  // Return false if we didn't find spilled register.
1012  return false;
1013 }
1014 
1016 LiveDebugValues::isRestoreInstruction(const MachineInstr &MI,
1017  MachineFunction *MF, unsigned &Reg) {
1018  if (!MI.hasOneMemOperand())
1019  return None;
1020 
1021  // FIXME: Handle folded restore instructions with more than one memory
1022  // operand.
1023  if (MI.getRestoreSize(TII)) {
1024  Reg = MI.getOperand(0).getReg();
1025  return extractSpillBaseRegAndOffset(MI);
1026  }
1027  return None;
1028 }
1029 
1030 /// A spilled register may indicate that we have to end the current range of
1031 /// a variable and create a new one for the spill location.
1032 /// A restored register may indicate the reverse situation.
1033 /// We don't want to insert any instructions in process(), so we just create
1034 /// the DBG_VALUE without inserting it and keep track of it in \p Transfers.
1035 /// It will be inserted into the BB when we're done iterating over the
1036 /// instructions.
1037 void LiveDebugValues::transferSpillOrRestoreInst(MachineInstr &MI,
1038  OpenRangesSet &OpenRanges,
1039  VarLocMap &VarLocIDs,
1040  TransferMap &Transfers) {
1041  MachineFunction *MF = MI.getMF();
1042  TransferKind TKind;
1043  unsigned Reg;
1045 
1046  LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump(););
1047 
1048  // First, if there are any DBG_VALUEs pointing at a spill slot that is
1049  // written to, then close the variable location. The value in memory
1050  // will have changed.
1051  VarLocSet KillSet;
1052  if (isSpillInstruction(MI, MF)) {
1053  Loc = extractSpillBaseRegAndOffset(MI);
1054  for (unsigned ID : OpenRanges.getVarLocs()) {
1055  const VarLoc &VL = VarLocIDs[ID];
1056  if (VL.Kind == VarLoc::SpillLocKind && VL.Loc.SpillLocation == *Loc) {
1057  // This location is overwritten by the current instruction -- terminate
1058  // the open range, and insert an explicit DBG_VALUE $noreg.
1059  //
1060  // Doing this at a later stage would require re-interpreting all
1061  // DBG_VALUes and DIExpressions to identify whether they point at
1062  // memory, and then analysing all memory writes to see if they
1063  // overwrite that memory, which is expensive.
1064  //
1065  // At this stage, we already know which DBG_VALUEs are for spills and
1066  // where they are located; it's best to fix handle overwrites now.
1067  KillSet.set(ID);
1068  VarLoc UndefVL = VarLoc::CreateCopyLoc(VL.MI, LS, 0);
1069  unsigned UndefLocID = VarLocIDs.insert(UndefVL);
1070  Transfers.push_back({&MI, UndefLocID});
1071  }
1072  }
1073  OpenRanges.erase(KillSet, VarLocIDs);
1074  }
1075 
1076  // Try to recognise spill and restore instructions that may create a new
1077  // variable location.
1078  if (isLocationSpill(MI, MF, Reg)) {
1079  TKind = TransferKind::TransferSpill;
1080  LLVM_DEBUG(dbgs() << "Recognized as spill: "; MI.dump(););
1081  LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
1082  << "\n");
1083  } else {
1084  if (!(Loc = isRestoreInstruction(MI, MF, Reg)))
1085  return;
1086  TKind = TransferKind::TransferRestore;
1087  LLVM_DEBUG(dbgs() << "Recognized as restore: "; MI.dump(););
1088  LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)
1089  << "\n");
1090  }
1091  // Check if the register or spill location is the location of a debug value.
1092  for (unsigned ID : OpenRanges.getVarLocs()) {
1093  if (TKind == TransferKind::TransferSpill &&
1094  VarLocIDs[ID].isDescribedByReg() == Reg) {
1095  LLVM_DEBUG(dbgs() << "Spilling Register " << printReg(Reg, TRI) << '('
1096  << VarLocIDs[ID].Var.getVariable()->getName() << ")\n");
1097  } else if (TKind == TransferKind::TransferRestore &&
1098  VarLocIDs[ID].Kind == VarLoc::SpillLocKind &&
1099  VarLocIDs[ID].Loc.SpillLocation == *Loc) {
1100  LLVM_DEBUG(dbgs() << "Restoring Register " << printReg(Reg, TRI) << '('
1101  << VarLocIDs[ID].Var.getVariable()->getName() << ")\n");
1102  } else
1103  continue;
1104  insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID, TKind,
1105  Reg);
1106  return;
1107  }
1108 }
1109 
1110 /// If \p MI is a register copy instruction, that copies a previously tracked
1111 /// value from one register to another register that is callee saved, we
1112 /// create new DBG_VALUE instruction described with copy destination register.
1113 void LiveDebugValues::transferRegisterCopy(MachineInstr &MI,
1114  OpenRangesSet &OpenRanges,
1115  VarLocMap &VarLocIDs,
1116  TransferMap &Transfers) {
1117  auto DestSrc = TII->isCopyInstr(MI);
1118  if (!DestSrc)
1119  return;
1120 
1121  const MachineOperand *DestRegOp = DestSrc->Destination;
1122  const MachineOperand *SrcRegOp = DestSrc->Source;
1123 
1124  if (!DestRegOp->isDef())
1125  return;
1126 
1127  auto isCalleeSavedReg = [&](unsigned Reg) {
1128  for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1129  if (CalleeSavedRegs.test(*RAI))
1130  return true;
1131  return false;
1132  };
1133 
1134  Register SrcReg = SrcRegOp->getReg();
1135  Register DestReg = DestRegOp->getReg();
1136 
1137  // We want to recognize instructions where destination register is callee
1138  // saved register. If register that could be clobbered by the call is
1139  // included, there would be a great chance that it is going to be clobbered
1140  // soon. It is more likely that previous register location, which is callee
1141  // saved, is going to stay unclobbered longer, even if it is killed.
1142  if (!isCalleeSavedReg(DestReg))
1143  return;
1144 
1145  // Remember an entry value movement. If we encounter a new debug value of
1146  // a parameter describing only a moving of the value around, rather then
1147  // modifying it, we are still able to use the entry value if needed.
1148  if (isRegOtherThanSPAndFP(*DestRegOp, MI, TRI)) {
1149  for (unsigned ID : OpenRanges.getVarLocs()) {
1150  if (VarLocIDs[ID].getEntryValueBackupReg() == SrcReg) {
1151  LLVM_DEBUG(dbgs() << "Copy of the entry value: "; MI.dump(););
1152  VarLoc EntryValLocCopyBackup = VarLoc::CreateEntryCopyBackupLoc(
1153  VarLocIDs[ID].MI, LS, VarLocIDs[ID].Expr, DestReg);
1154 
1155  // Stop tracking the original entry value.
1156  OpenRanges.erase(VarLocIDs[ID]);
1157 
1158  // Start tracking the entry value copy.
1159  unsigned EntryValCopyLocID = VarLocIDs.insert(EntryValLocCopyBackup);
1160  OpenRanges.insert(EntryValCopyLocID, EntryValLocCopyBackup);
1161  break;
1162  }
1163  }
1164  }
1165 
1166  if (!SrcRegOp->isKill())
1167  return;
1168 
1169  for (unsigned ID : OpenRanges.getVarLocs()) {
1170  if (VarLocIDs[ID].isDescribedByReg() == SrcReg) {
1171  insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, ID,
1172  TransferKind::TransferCopy, DestReg);
1173  return;
1174  }
1175  }
1176 }
1177 
1178 /// Terminate all open ranges at the end of the current basic block.
1179 bool LiveDebugValues::transferTerminator(MachineBasicBlock *CurMBB,
1180  OpenRangesSet &OpenRanges,
1181  VarLocInMBB &OutLocs,
1182  const VarLocMap &VarLocIDs) {
1183  bool Changed = false;
1184 
1185  LLVM_DEBUG(for (unsigned ID
1186  : OpenRanges.getVarLocs()) {
1187  // Copy OpenRanges to OutLocs, if not already present.
1188  dbgs() << "Add to OutLocs in MBB #" << CurMBB->getNumber() << ": ";
1189  VarLocIDs[ID].dump(TRI);
1190  });
1191  VarLocSet &VLS = OutLocs[CurMBB];
1192  Changed = VLS != OpenRanges.getVarLocs();
1193  // New OutLocs set may be different due to spill, restore or register
1194  // copy instruction processing.
1195  if (Changed)
1196  VLS = OpenRanges.getVarLocs();
1197  OpenRanges.clear();
1198  return Changed;
1199 }
1200 
1201 /// Accumulate a mapping between each DILocalVariable fragment and other
1202 /// fragments of that DILocalVariable which overlap. This reduces work during
1203 /// the data-flow stage from "Find any overlapping fragments" to "Check if the
1204 /// known-to-overlap fragments are present".
1205 /// \param MI A previously unprocessed DEBUG_VALUE instruction to analyze for
1206 /// fragment usage.
1207 /// \param SeenFragments Map from DILocalVariable to all fragments of that
1208 /// Variable which are known to exist.
1209 /// \param OverlappingFragments The overlap map being constructed, from one
1210 /// Var/Fragment pair to a vector of fragments known to overlap.
1211 void LiveDebugValues::accumulateFragmentMap(MachineInstr &MI,
1212  VarToFragments &SeenFragments,
1213  OverlapMap &OverlappingFragments) {
1215  MI.getDebugLoc()->getInlinedAt());
1216  FragmentInfo ThisFragment = MIVar.getFragmentOrDefault();
1217 
1218  // If this is the first sighting of this variable, then we are guaranteed
1219  // there are currently no overlapping fragments either. Initialize the set
1220  // of seen fragments, record no overlaps for the current one, and return.
1221  auto SeenIt = SeenFragments.find(MIVar.getVariable());
1222  if (SeenIt == SeenFragments.end()) {
1223  SmallSet<FragmentInfo, 4> OneFragment;
1224  OneFragment.insert(ThisFragment);
1225  SeenFragments.insert({MIVar.getVariable(), OneFragment});
1226 
1227  OverlappingFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
1228  return;
1229  }
1230 
1231  // If this particular Variable/Fragment pair already exists in the overlap
1232  // map, it has already been accounted for.
1233  auto IsInOLapMap =
1234  OverlappingFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
1235  if (!IsInOLapMap.second)
1236  return;
1237 
1238  auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
1239  auto &AllSeenFragments = SeenIt->second;
1240 
1241  // Otherwise, examine all other seen fragments for this variable, with "this"
1242  // fragment being a previously unseen fragment. Record any pair of
1243  // overlapping fragments.
1244  for (auto &ASeenFragment : AllSeenFragments) {
1245  // Does this previously seen fragment overlap?
1246  if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
1247  // Yes: Mark the current fragment as being overlapped.
1248  ThisFragmentsOverlaps.push_back(ASeenFragment);
1249  // Mark the previously seen fragment as being overlapped by the current
1250  // one.
1251  auto ASeenFragmentsOverlaps =
1252  OverlappingFragments.find({MIVar.getVariable(), ASeenFragment});
1253  assert(ASeenFragmentsOverlaps != OverlappingFragments.end() &&
1254  "Previously seen var fragment has no vector of overlaps");
1255  ASeenFragmentsOverlaps->second.push_back(ThisFragment);
1256  }
1257  }
1258 
1259  AllSeenFragments.insert(ThisFragment);
1260 }
1261 
1262 /// This routine creates OpenRanges.
1263 void LiveDebugValues::process(MachineInstr &MI, OpenRangesSet &OpenRanges,
1264  VarLocMap &VarLocIDs, TransferMap &Transfers) {
1265  transferDebugValue(MI, OpenRanges, VarLocIDs);
1266  transferRegisterDef(MI, OpenRanges, VarLocIDs, Transfers);
1267  transferRegisterCopy(MI, OpenRanges, VarLocIDs, Transfers);
1268  transferSpillOrRestoreInst(MI, OpenRanges, VarLocIDs, Transfers);
1269 }
1270 
1271 /// This routine joins the analysis results of all incoming edges in @MBB by
1272 /// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
1273 /// source variable in all the predecessors of @MBB reside in the same location.
1275  MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
1276  const VarLocMap &VarLocIDs,
1279  VarLocInMBB &PendingInLocs) {
1280  LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n");
1281  bool Changed = false;
1282 
1283  VarLocSet InLocsT; // Temporary incoming locations.
1284 
1285  // For all predecessors of this MBB, find the set of VarLocs that
1286  // can be joined.
1287  int NumVisited = 0;
1288  for (auto p : MBB.predecessors()) {
1289  // Ignore backedges if we have not visited the predecessor yet. As the
1290  // predecessor hasn't yet had locations propagated into it, most locations
1291  // will not yet be valid, so treat them as all being uninitialized and
1292  // potentially valid. If a location guessed to be correct here is
1293  // invalidated later, we will remove it when we revisit this block.
1294  if (!Visited.count(p)) {
1295  LLVM_DEBUG(dbgs() << " ignoring unvisited pred MBB: " << p->getNumber()
1296  << "\n");
1297  continue;
1298  }
1299  auto OL = OutLocs.find(p);
1300  // Join is null in case of empty OutLocs from any of the pred.
1301  if (OL == OutLocs.end())
1302  return false;
1303 
1304  // Just copy over the Out locs to incoming locs for the first visited
1305  // predecessor, and for all other predecessors join the Out locs.
1306  if (!NumVisited)
1307  InLocsT = OL->second;
1308  else
1309  InLocsT &= OL->second;
1310 
1311  LLVM_DEBUG({
1312  if (!InLocsT.empty()) {
1313  for (auto ID : InLocsT)
1314  dbgs() << " gathered candidate incoming var: "
1315  << VarLocIDs[ID].Var.getVariable()->getName() << "\n";
1316  }
1317  });
1318 
1319  NumVisited++;
1320  }
1321 
1322  // Filter out DBG_VALUES that are out of scope.
1323  VarLocSet KillSet;
1324  bool IsArtificial = ArtificialBlocks.count(&MBB);
1325  if (!IsArtificial) {
1326  for (auto ID : InLocsT) {
1327  if (!VarLocIDs[ID].dominates(MBB)) {
1328  KillSet.set(ID);
1329  LLVM_DEBUG({
1330  auto Name = VarLocIDs[ID].Var.getVariable()->getName();
1331  dbgs() << " killing " << Name << ", it doesn't dominate MBB\n";
1332  });
1333  }
1334  }
1335  }
1336  InLocsT.intersectWithComplement(KillSet);
1337 
1338  // As we are processing blocks in reverse post-order we
1339  // should have processed at least one predecessor, unless it
1340  // is the entry block which has no predecessor.
1341  assert((NumVisited || MBB.pred_empty()) &&
1342  "Should have processed at least one predecessor");
1343 
1344  VarLocSet &ILS = InLocs[&MBB];
1345  VarLocSet &Pending = PendingInLocs[&MBB];
1346 
1347  // New locations will have DBG_VALUE insts inserted at the start of the
1348  // block, after location propagation has finished. Record the insertions
1349  // that we need to perform in the Pending set.
1350  VarLocSet Diff = InLocsT;
1351  Diff.intersectWithComplement(ILS);
1352  for (auto ID : Diff) {
1353  Pending.set(ID);
1354  ILS.set(ID);
1355  ++NumInserted;
1356  Changed = true;
1357  }
1358 
1359  // We may have lost locations by learning about a predecessor that either
1360  // loses or moves a variable. Find any locations in ILS that are not in the
1361  // new in-locations, and delete those.
1362  VarLocSet Removed = ILS;
1363  Removed.intersectWithComplement(InLocsT);
1364  for (auto ID : Removed) {
1365  Pending.reset(ID);
1366  ILS.reset(ID);
1367  ++NumRemoved;
1368  Changed = true;
1369  }
1370 
1371  return Changed;
1372 }
1373 
1374 void LiveDebugValues::flushPendingLocs(VarLocInMBB &PendingInLocs,
1375  VarLocMap &VarLocIDs) {
1376  // PendingInLocs records all locations propagated into blocks, which have
1377  // not had DBG_VALUE insts created. Go through and create those insts now.
1378  for (auto &Iter : PendingInLocs) {
1379  // Map is keyed on a constant pointer, unwrap it so we can insert insts.
1380  auto &MBB = const_cast<MachineBasicBlock &>(*Iter.first);
1381  VarLocSet &Pending = Iter.second;
1382 
1383  for (unsigned ID : Pending) {
1384  // The ID location is live-in to MBB -- work out what kind of machine
1385  // location it is and create a DBG_VALUE.
1386  const VarLoc &DiffIt = VarLocIDs[ID];
1387  if (DiffIt.isEntryBackupLoc())
1388  continue;
1389  MachineInstr *MI = DiffIt.BuildDbgValue(*MBB.getParent());
1390  MBB.insert(MBB.instr_begin(), MI);
1391 
1392  (void)MI;
1393  LLVM_DEBUG(dbgs() << "Inserted: "; MI->dump(););
1394  }
1395  }
1396 }
1397 
1398 bool LiveDebugValues::isEntryValueCandidate(
1399  const MachineInstr &MI, const DefinedRegsSet &DefinedRegs) const {
1400  assert(MI.isDebugValue() && "This must be DBG_VALUE.");
1401 
1402  // TODO: Add support for local variables that are expressed in terms of
1403  // parameters entry values.
1404  // TODO: Add support for modified arguments that can be expressed
1405  // by using its entry value.
1406  auto *DIVar = MI.getDebugVariable();
1407  if (!DIVar->isParameter())
1408  return false;
1409 
1410  // Do not consider parameters that belong to an inlined function.
1411  if (MI.getDebugLoc()->getInlinedAt())
1412  return false;
1413 
1414  // Do not consider indirect debug values (TODO: explain why).
1415  if (MI.isIndirectDebugValue())
1416  return false;
1417 
1418  // Only consider parameters that are described using registers. Parameters
1419  // that are passed on the stack are not yet supported, so ignore debug
1420  // values that are described by the frame or stack pointer.
1421  if (!isRegOtherThanSPAndFP(MI.getOperand(0), MI, TRI))
1422  return false;
1423 
1424  // If a parameter's value has been propagated from the caller, then the
1425  // parameter's DBG_VALUE may be described using a register defined by some
1426  // instruction in the entry block, in which case we shouldn't create an
1427  // entry value.
1428  if (DefinedRegs.count(MI.getOperand(0).getReg()))
1429  return false;
1430 
1431  // TODO: Add support for parameters that have a pre-existing debug expressions
1432  // (e.g. fragments, or indirect parameters using DW_OP_deref).
1433  if (MI.getDebugExpression()->getNumElements() > 0)
1434  return false;
1435 
1436  return true;
1437 }
1438 
1439 /// Collect all register defines (including aliases) for the given instruction.
1440 static void collectRegDefs(const MachineInstr &MI, DefinedRegsSet &Regs,
1441  const TargetRegisterInfo *TRI) {
1442  for (const MachineOperand &MO : MI.operands())
1443  if (MO.isReg() && MO.isDef() && MO.getReg())
1444  for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
1445  Regs.insert(*AI);
1446 }
1447 
1448 /// This routine records the entry values of function parameters. The values
1449 /// could be used as backup values. If we loose the track of some unmodified
1450 /// parameters, the backup values will be used as a primary locations.
1451 void LiveDebugValues::recordEntryValue(const MachineInstr &MI,
1452  const DefinedRegsSet &DefinedRegs,
1453  OpenRangesSet &OpenRanges,
1454  VarLocMap &VarLocIDs) {
1455  if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
1456  auto &TM = TPC->getTM<TargetMachine>();
1457  if (!TM.Options.EnableDebugEntryValues)
1458  return;
1459  }
1460 
1462  MI.getDebugLoc()->getInlinedAt());
1463 
1464  if (!isEntryValueCandidate(MI, DefinedRegs) ||
1465  OpenRanges.getEntryValueBackup(V))
1466  return;
1467 
1468  LLVM_DEBUG(dbgs() << "Creating the backup entry location: "; MI.dump(););
1469 
1470  // Create the entry value and use it as a backup location until it is
1471  // valid. It is valid until a parameter is not changed.
1474  VarLoc EntryValLocAsBackup = VarLoc::CreateEntryBackupLoc(MI, LS, NewExpr);
1475  unsigned EntryValLocID = VarLocIDs.insert(EntryValLocAsBackup);
1476  OpenRanges.insert(EntryValLocID, EntryValLocAsBackup);
1477 }
1478 
1479 /// Calculate the liveness information for the given machine function and
1480 /// extend ranges across basic blocks.
1481 bool LiveDebugValues::ExtendRanges(MachineFunction &MF) {
1482  LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n");
1483 
1484  bool Changed = false;
1485  bool OLChanged = false;
1486  bool MBBJoined = false;
1487 
1488  VarLocMap VarLocIDs; // Map VarLoc<>unique ID for use in bitvectors.
1489  OverlapMap OverlapFragments; // Map of overlapping variable fragments.
1490  OpenRangesSet OpenRanges(OverlapFragments);
1491  // Ranges that are open until end of bb.
1492  VarLocInMBB OutLocs; // Ranges that exist beyond bb.
1493  VarLocInMBB InLocs; // Ranges that are incoming after joining.
1494  TransferMap Transfers; // DBG_VALUEs associated with transfers (such as
1495  // spills, copies and restores).
1496  VarLocInMBB PendingInLocs; // Ranges that are incoming after joining, but
1497  // that we have deferred creating DBG_VALUE insts
1498  // for immediately.
1499 
1500  VarToFragments SeenFragments;
1501 
1502  // Blocks which are artificial, i.e. blocks which exclusively contain
1503  // instructions without locations, or with line 0 locations.
1505 
1508  std::priority_queue<unsigned int, std::vector<unsigned int>,
1509  std::greater<unsigned int>>
1510  Worklist;
1511  std::priority_queue<unsigned int, std::vector<unsigned int>,
1512  std::greater<unsigned int>>
1513  Pending;
1514 
1515  // Set of register defines that are seen when traversing the entry block
1516  // looking for debug entry value candidates.
1517  DefinedRegsSet DefinedRegs;
1518 
1519  // Only in the case of entry MBB collect DBG_VALUEs representing
1520  // function parameters in order to generate debug entry values for them.
1521  MachineBasicBlock &First_MBB = *(MF.begin());
1522  for (auto &MI : First_MBB) {
1523  collectRegDefs(MI, DefinedRegs, TRI);
1524  if (MI.isDebugValue())
1525  recordEntryValue(MI, DefinedRegs, OpenRanges, VarLocIDs);
1526  }
1527 
1528  // Initialize per-block structures and scan for fragment overlaps.
1529  for (auto &MBB : MF) {
1530  PendingInLocs[&MBB] = VarLocSet();
1531 
1532  for (auto &MI : MBB) {
1533  if (MI.isDebugValue())
1534  accumulateFragmentMap(MI, SeenFragments, OverlapFragments);
1535  }
1536  }
1537 
1538  auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
1539  if (const DebugLoc &DL = MI.getDebugLoc())
1540  return DL.getLine() != 0;
1541  return false;
1542  };
1543  for (auto &MBB : MF)
1544  if (none_of(MBB.instrs(), hasNonArtificialLocation))
1545  ArtificialBlocks.insert(&MBB);
1546 
1547  LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
1548  "OutLocs after initialization", dbgs()));
1549 
1551  unsigned int RPONumber = 0;
1552  for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) {
1553  OrderToBB[RPONumber] = *RI;
1554  BBToOrder[*RI] = RPONumber;
1555  Worklist.push(RPONumber);
1556  ++RPONumber;
1557  }
1558  // This is a standard "union of predecessor outs" dataflow problem.
1559  // To solve it, we perform join() and process() using the two worklist method
1560  // until the ranges converge.
1561  // Ranges have converged when both worklists are empty.
1563  while (!Worklist.empty() || !Pending.empty()) {
1564  // We track what is on the pending worklist to avoid inserting the same
1565  // thing twice. We could avoid this with a custom priority queue, but this
1566  // is probably not worth it.
1568  LLVM_DEBUG(dbgs() << "Processing Worklist\n");
1569  while (!Worklist.empty()) {
1570  MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
1571  Worklist.pop();
1572  MBBJoined = join(*MBB, OutLocs, InLocs, VarLocIDs, Visited,
1573  ArtificialBlocks, PendingInLocs);
1574  MBBJoined |= Visited.insert(MBB).second;
1575  if (MBBJoined) {
1576  MBBJoined = false;
1577  Changed = true;
1578  // Now that we have started to extend ranges across BBs we need to
1579  // examine spill, copy and restore instructions to see whether they
1580  // operate with registers that correspond to user variables.
1581  // First load any pending inlocs.
1582  OpenRanges.insertFromLocSet(PendingInLocs[MBB], VarLocIDs);
1583  for (auto &MI : *MBB)
1584  process(MI, OpenRanges, VarLocIDs, Transfers);
1585  OLChanged |= transferTerminator(MBB, OpenRanges, OutLocs, VarLocIDs);
1586 
1587  LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,
1588  "OutLocs after propagating", dbgs()));
1589  LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,
1590  "InLocs after propagating", dbgs()));
1591 
1592  if (OLChanged) {
1593  OLChanged = false;
1594  for (auto s : MBB->successors())
1595  if (OnPending.insert(s).second) {
1596  Pending.push(BBToOrder[s]);
1597  }
1598  }
1599  }
1600  }
1601  Worklist.swap(Pending);
1602  // At this point, pending must be empty, since it was just the empty
1603  // worklist
1604  assert(Pending.empty() && "Pending should be empty");
1605  }
1606 
1607  // Add any DBG_VALUE instructions created by location transfers.
1608  for (auto &TR : Transfers) {
1609  MachineBasicBlock *MBB = TR.TransferInst->getParent();
1610  const VarLoc &VL = VarLocIDs[TR.LocationID];
1611  MachineInstr *MI = VL.BuildDbgValue(MF);
1612  MBB->insertAfterBundle(TR.TransferInst->getIterator(), MI);
1613  }
1614  Transfers.clear();
1615 
1616  // Deferred inlocs will not have had any DBG_VALUE insts created; do
1617  // that now.
1618  flushPendingLocs(PendingInLocs, VarLocIDs);
1619 
1620  LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()));
1621  LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()));
1622  return Changed;
1623 }
1624 
1625 bool LiveDebugValues::runOnMachineFunction(MachineFunction &MF) {
1626  if (!MF.getFunction().getSubprogram())
1627  // LiveDebugValues will already have removed all DBG_VALUEs.
1628  return false;
1629 
1630  // Skip functions from NoDebug compilation units.
1631  if (MF.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
1633  return false;
1634 
1635  TRI = MF.getSubtarget().getRegisterInfo();
1636  TII = MF.getSubtarget().getInstrInfo();
1637  TFI = MF.getSubtarget().getFrameLowering();
1638  TFI->getCalleeSaves(MF, CalleeSavedRegs);
1639  LS.initialize(MF);
1640 
1641  bool Changed = ExtendRanges(MF);
1642  return Changed;
1643 }
const FragmentInfo getFragmentOrDefault() const
static bool isConstant(const MachineInstr &MI)
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
instr_iterator instr_begin()
bool isCall(QueryType Type=AnyInBundle) const
Definition: MachineInstr.h:682
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, otherwise insert MI immediately after I.
static bool fragmentsOverlap(const FragmentInfo &A, const FragmentInfo &B)
Check if fragments overlap between a pair of FragmentInfos.
const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
void set(unsigned Idx)
bool dominates(const DILocation *DL, MachineBasicBlock *MBB)
dominates - Return true if DebugLoc&#39;s lexical scope dominates at least one machine instruction&#39;s lexi...
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:400
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
Definition: Register.h:63
unsigned Reg
virtual const TargetLowering * getTargetLowering() const
STATISTIC(NumFunctions, "Total number of functions")
unsigned const TargetRegisterInfo * TRI
A debug info location.
Definition: DebugLoc.h:33
Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
iterator_range< mop_iterator > operands()
Definition: MachineInstr.h:492
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
static Register isDescribedByReg(const MachineInstr &MI)
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 ...
Identifies a unique instance of a variable.
StringRef getName() const
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
RegisterKind
const ConstantFP * getFPImm() const
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:429
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:1196
static Register isDbgValueDescribedByReg(const MachineInstr &MI)
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
Definition: StringExtras.h:370
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:423
Holds the characteristics of one fragment of a larger variable.
Optional< unsigned > getRestoreSize(const TargetInstrInfo *TII) const
Return a valid size if the instruction is a restore instruction.
unsigned getMetadataID() const
Definition: Metadata.h:100
INITIALIZE_PASS(LiveDebugValues, DEBUG_TYPE, "Live DEBUG_VALUE analysis", false, false) LiveDebugValues
Default construct and initialize the pass.
bool isFPImm() const
isFPImm - Tests if this is a MO_FPImmediate operand.
const DILocation * getInlinedAt() const
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they&#39;re not in a MachineFuncti...
virtual const TargetInstrInfo * getInstrInfo() const
Debug location.
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
reverse_iterator rend()
void initializeLiveDebugValuesPass(PassRegistry &)
TargetInstrInfo - Interface to description of machine instruction set.
Optional< unsigned > getSpillSize(const TargetInstrInfo *TII) const
Return a valid size if the instruction is a spill instruction.
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
#define DEBUG_TYPE
This file declares the machine register scavenger class.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1525
LLVM_NODISCARD bool empty() const
Definition: SmallPtrSet.h:91
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:134
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:263
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:370
bool isCImm() const
isCImm - Test if this is a MO_CImmediate operand.
bool isValidLocationForIntrinsic(const DILocation *DL) const
Check that a location is valid for this variable.
MCRegAliasIterator enumerates all registers aliasing Reg.
Represent the analysis usage information of a pass.
bool hasOneMemOperand() const
Return true if this instruction has exactly one MachineMemOperand.
Definition: MachineInstr.h:582
char & LiveDebugValuesID
LiveDebugValues pass.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:381
self_iterator getIterator()
Definition: ilist_node.h:81
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn&#39;t already there.
Definition: SmallSet.h:180
iterator_range< pred_iterator > predecessors()
void print(raw_ostream &OS, bool IsStandalone=true, bool SkipOpers=false, bool SkipDebugLoc=false, bool AddNewLine=true, const TargetInstrInfo *TII=nullptr) const
Print this MI to OS.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Optional< unsigned > getFoldedSpillSize(const TargetInstrInfo *TII) const
Return a valid size if the instruction is a folded spill instruction.
void getMachineBasicBlocks(const DILocation *DL, SmallPtrSetImpl< const MachineBasicBlock *> &MBBs)
getMachineBasicBlocks - Populate given set using machine basic blocks which have machine instructions...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const DIExpression * getDebugExpression() const
Return the complex address expression referenced by this DBG_VALUE instruction.
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
Definition: STLExtras.h:192
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:443
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
Definition: MachineInstr.h:567
bool isDebugValue() const
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
Module.h This file contains the declarations for the Module class.
virtual Register getFrameRegister(const MachineFunction &MF) const =0
Debug information queries.
Information about stack frame layout on the target.
Promote Memory to Register
Definition: Mem2Reg.cpp:110
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:256
int64_t getImm() const
DWARF expression.
const Function & getFunction() const
Return the LLVM function that this machine code represents.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
static bool isRegOtherThanSPAndFP(const MachineOperand &Op, const MachineInstr &MI, const TargetRegisterInfo *TRI)
If Op is a stack or frame register return true, otherwise return false.
Special value supplied for machine level alias analysis.
static void clear(coro::Shape &Shape)
Definition: Coroutines.cpp:226
unsigned getNumElements() const
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:271
MachineFunctionProperties & set(Property P)
Representation of each machine instruction.
Definition: MachineInstr.h:63
virtual void getCalleeSaves(const MachineFunction &MF, BitVector &SavedRegs) const
Returns the callee-saved registers as computed by determineCalleeSaves in the BitVector SavedRegs...
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
reverse_self_iterator getReverseIterator()
Definition: ilist_node.h:84
LexicalScopes - This class provides interface to collect and use lexical scoping information from mac...
#define I(x, y, z)
Definition: MD5.cpp:58
virtual const TargetFrameLowering * getFrameLowering() const
static void collectRegDefs(const MachineInstr &MI, DefinedRegsSet &Regs, const TargetRegisterInfo *TRI)
Collect all register defines (including aliases) for the given instruction.
const DILocalVariable * getVariable() const
static bool isCalleeSavedReg(const MCPhysReg *CSRegs, MCPhysReg Reg)
bool isReg() const
isReg - Tests if this is a MO_Register operand.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isIdenticalTo(const MachineInstr &Other, MICheckType Check=CheckDefs) const
Return true if this instruction is identical to Other.
bool operator<(int64_t V1, const APSInt &V2)
Definition: APSInt.h:343
unsigned getStackPointerRegisterToSaveRestore() const
If a physical register, this specifies the register that llvm.savestack/llvm.restorestack should save...
const DILocalVariable * getDebugVariable() const
Return the debug variable referenced by this DBG_VALUE instruction.
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:65
IRTranslator LLVM IR MI
bool operator==(uint64_t V1, const APInt &V2)
Definition: APInt.h:2024
Register getReg() const
getReg - Returns the register number.
#define LLVM_DEBUG(X)
Definition: Debug.h:122
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:431
const ConstantInt * getCImm() const
bool isIndirectDebugValue() const
A DBG_VALUE is indirect iff the first operand is a register and the second operand is an immediate...
UniqueVector - This class produces a sequential ID number (base 1) for each unique entry that is adde...
Definition: UniqueVector.h:24
static bool isDefaultFragment(const FragmentInfo F)
Properties which a MachineFunction may have at a given point in time.
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
This file describes how to lower LLVM code to machine code.