Bug Summary

File:llvm/lib/CodeGen/LiveDebugValues.cpp
Warning:line 1752, column 9
Value stored to 'MBBJoined' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name LiveDebugValues.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp
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/CoalescingBitVector.h"
30#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/PostOrderIterator.h"
32#include "llvm/ADT/SmallPtrSet.h"
33#include "llvm/ADT/SmallSet.h"
34#include "llvm/ADT/SmallVector.h"
35#include "llvm/ADT/Statistic.h"
36#include "llvm/ADT/UniqueVector.h"
37#include "llvm/CodeGen/LexicalScopes.h"
38#include "llvm/CodeGen/MachineBasicBlock.h"
39#include "llvm/CodeGen/MachineFrameInfo.h"
40#include "llvm/CodeGen/MachineFunction.h"
41#include "llvm/CodeGen/MachineFunctionPass.h"
42#include "llvm/CodeGen/MachineInstr.h"
43#include "llvm/CodeGen/MachineInstrBuilder.h"
44#include "llvm/CodeGen/MachineMemOperand.h"
45#include "llvm/CodeGen/MachineOperand.h"
46#include "llvm/CodeGen/PseudoSourceValue.h"
47#include "llvm/CodeGen/RegisterScavenging.h"
48#include "llvm/CodeGen/TargetFrameLowering.h"
49#include "llvm/CodeGen/TargetInstrInfo.h"
50#include "llvm/CodeGen/TargetLowering.h"
51#include "llvm/CodeGen/TargetPassConfig.h"
52#include "llvm/CodeGen/TargetRegisterInfo.h"
53#include "llvm/CodeGen/TargetSubtargetInfo.h"
54#include "llvm/Config/llvm-config.h"
55#include "llvm/IR/DIBuilder.h"
56#include "llvm/IR/DebugInfoMetadata.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"
66#include "llvm/Support/raw_ostream.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
76using namespace llvm;
77
78#define DEBUG_TYPE"livedebugvalues" "livedebugvalues"
79
80STATISTIC(NumInserted, "Number of DBG_VALUE instructions inserted")static llvm::Statistic NumInserted = {"livedebugvalues", "NumInserted"
, "Number of DBG_VALUE instructions inserted"}
;
81STATISTIC(NumRemoved, "Number of DBG_VALUE instructions removed")static llvm::Statistic NumRemoved = {"livedebugvalues", "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.
85static Register isDbgValueDescribedByReg(const MachineInstr &MI) {
86 assert(MI.isDebugValue() && "expected a DBG_VALUE")((MI.isDebugValue() && "expected a DBG_VALUE") ? static_cast
<void> (0) : __assert_fail ("MI.isDebugValue() && \"expected a DBG_VALUE\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 86, __PRETTY_FUNCTION__))
;
87 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE")((MI.getNumOperands() == 4 && "malformed DBG_VALUE") ?
static_cast<void> (0) : __assert_fail ("MI.getNumOperands() == 4 && \"malformed DBG_VALUE\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 87, __PRETTY_FUNCTION__))
;
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.
96static bool isRegOtherThanSPAndFP(const MachineOperand &Op,
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
111namespace {
112
113using DefinedRegsSet = SmallSet<Register, 32>;
114using VarLocSet = CoalescingBitVector<uint64_t>;
115
116/// A type-checked pair of {Register Location (or 0), Index}, used to index
117/// into a \ref VarLocMap. This can be efficiently converted to a 64-bit int
118/// for insertion into a \ref VarLocSet, and efficiently converted back. The
119/// type-checker helps ensure that the conversions aren't lossy.
120///
121/// Why encode a location /into/ the VarLocMap index? This makes it possible
122/// to find the open VarLocs killed by a register def very quickly. This is a
123/// performance-critical operation for LiveDebugValues.
124///
125/// TODO: Consider adding reserved intervals for kinds of VarLocs other than
126/// RegisterKind, like SpillLocKind or EntryValueKind, to optimize iteration
127/// over open locations.
128struct LocIndex {
129 uint32_t Location; // Physical registers live in the range [1;2^30) (see
130 // \ref MCRegister), so we have plenty of range left here
131 // to encode non-register locations.
132 uint32_t Index;
133
134 LocIndex(uint32_t Location, uint32_t Index)
135 : Location(Location), Index(Index) {}
136
137 uint64_t getAsRawInteger() const {
138 return (static_cast<uint64_t>(Location) << 32) | Index;
139 }
140
141 template<typename IntT> static LocIndex fromRawInteger(IntT ID) {
142 static_assert(std::is_unsigned<IntT>::value &&
143 sizeof(ID) == sizeof(uint64_t),
144 "Cannot convert raw integer to LocIndex");
145 return {static_cast<uint32_t>(ID >> 32), static_cast<uint32_t>(ID)};
146 }
147
148 /// Get the start of the interval reserved for VarLocs of kind RegisterKind
149 /// which reside in \p Reg. The end is at rawIndexForReg(Reg+1)-1.
150 static uint64_t rawIndexForReg(uint32_t Reg) {
151 return LocIndex(Reg, 0).getAsRawInteger();
152 }
153};
154
155class LiveDebugValues : public MachineFunctionPass {
156private:
157 const TargetRegisterInfo *TRI;
158 const TargetInstrInfo *TII;
159 const TargetFrameLowering *TFI;
160 BitVector CalleeSavedRegs;
161 LexicalScopes LS;
162 VarLocSet::Allocator Alloc;
163
164 enum struct TransferKind { TransferCopy, TransferSpill, TransferRestore };
165
166 /// Keeps track of lexical scopes associated with a user value's source
167 /// location.
168 class UserValueScopes {
169 DebugLoc DL;
170 LexicalScopes &LS;
171 SmallPtrSet<const MachineBasicBlock *, 4> LBlocks;
172
173 public:
174 UserValueScopes(DebugLoc D, LexicalScopes &L) : DL(std::move(D)), LS(L) {}
175
176 /// Return true if current scope dominates at least one machine
177 /// instruction in a given machine basic block.
178 bool dominates(MachineBasicBlock *MBB) {
179 if (LBlocks.empty())
180 LS.getMachineBasicBlocks(DL, LBlocks);
181 return LBlocks.count(MBB) != 0 || LS.dominates(DL, MBB);
182 }
183 };
184
185 using FragmentInfo = DIExpression::FragmentInfo;
186 using OptFragmentInfo = Optional<DIExpression::FragmentInfo>;
187
188 /// A pair of debug variable and value location.
189 struct VarLoc {
190 // The location at which a spilled variable resides. It consists of a
191 // register and an offset.
192 struct SpillLoc {
193 unsigned SpillBase;
194 int SpillOffset;
195 bool operator==(const SpillLoc &Other) const {
196 return SpillBase == Other.SpillBase && SpillOffset == Other.SpillOffset;
197 }
198 };
199
200 /// Identity of the variable at this location.
201 const DebugVariable Var;
202
203 /// The expression applied to this location.
204 const DIExpression *Expr;
205
206 /// DBG_VALUE to clone var/expr information from if this location
207 /// is moved.
208 const MachineInstr &MI;
209
210 mutable UserValueScopes UVS;
211 enum VarLocKind {
212 InvalidKind = 0,
213 RegisterKind,
214 SpillLocKind,
215 ImmediateKind,
216 EntryValueKind,
217 EntryValueBackupKind,
218 EntryValueCopyBackupKind
219 } Kind = InvalidKind;
220
221 /// The value location. Stored separately to avoid repeatedly
222 /// extracting it from MI.
223 union {
224 uint64_t RegNo;
225 SpillLoc SpillLocation;
226 uint64_t Hash;
227 int64_t Immediate;
228 const ConstantFP *FPImm;
229 const ConstantInt *CImm;
230 } Loc;
231
232 VarLoc(const MachineInstr &MI, LexicalScopes &LS)
233 : Var(MI.getDebugVariable(), MI.getDebugExpression(),
234 MI.getDebugLoc()->getInlinedAt()),
235 Expr(MI.getDebugExpression()), MI(MI), UVS(MI.getDebugLoc(), LS) {
236 static_assert((sizeof(Loc) == sizeof(uint64_t)),
237 "hash does not cover all members of Loc");
238 assert(MI.isDebugValue() && "not a DBG_VALUE")((MI.isDebugValue() && "not a DBG_VALUE") ? static_cast
<void> (0) : __assert_fail ("MI.isDebugValue() && \"not a DBG_VALUE\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 238, __PRETTY_FUNCTION__))
;
239 assert(MI.getNumOperands() == 4 && "malformed DBG_VALUE")((MI.getNumOperands() == 4 && "malformed DBG_VALUE") ?
static_cast<void> (0) : __assert_fail ("MI.getNumOperands() == 4 && \"malformed DBG_VALUE\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 239, __PRETTY_FUNCTION__))
;
240 if (int RegNo = isDbgValueDescribedByReg(MI)) {
241 Kind = RegisterKind;
242 Loc.RegNo = RegNo;
243 } else if (MI.getOperand(0).isImm()) {
244 Kind = ImmediateKind;
245 Loc.Immediate = MI.getOperand(0).getImm();
246 } else if (MI.getOperand(0).isFPImm()) {
247 Kind = ImmediateKind;
248 Loc.FPImm = MI.getOperand(0).getFPImm();
249 } else if (MI.getOperand(0).isCImm()) {
250 Kind = ImmediateKind;
251 Loc.CImm = MI.getOperand(0).getCImm();
252 }
253
254 // We create the debug entry values from the factory functions rather than
255 // from this ctor.
256 assert(Kind != EntryValueKind && !isEntryBackupLoc())((Kind != EntryValueKind && !isEntryBackupLoc()) ? static_cast
<void> (0) : __assert_fail ("Kind != EntryValueKind && !isEntryBackupLoc()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 256, __PRETTY_FUNCTION__))
;
257 }
258
259 /// Take the variable and machine-location in DBG_VALUE MI, and build an
260 /// entry location using the given expression.
261 static VarLoc CreateEntryLoc(const MachineInstr &MI, LexicalScopes &LS,
262 const DIExpression *EntryExpr, unsigned Reg) {
263 VarLoc VL(MI, LS);
264 assert(VL.Kind == RegisterKind)((VL.Kind == RegisterKind) ? static_cast<void> (0) : __assert_fail
("VL.Kind == RegisterKind", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 264, __PRETTY_FUNCTION__))
;
265 VL.Kind = EntryValueKind;
266 VL.Expr = EntryExpr;
267 VL.Loc.RegNo = Reg;
268 return VL;
269 }
270
271 /// Take the variable and machine-location from the DBG_VALUE (from the
272 /// function entry), and build an entry value backup location. The backup
273 /// location will turn into the normal location if the backup is valid at
274 /// the time of the primary location clobbering.
275 static VarLoc CreateEntryBackupLoc(const MachineInstr &MI,
276 LexicalScopes &LS,
277 const DIExpression *EntryExpr) {
278 VarLoc VL(MI, LS);
279 assert(VL.Kind == RegisterKind)((VL.Kind == RegisterKind) ? static_cast<void> (0) : __assert_fail
("VL.Kind == RegisterKind", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 279, __PRETTY_FUNCTION__))
;
280 VL.Kind = EntryValueBackupKind;
281 VL.Expr = EntryExpr;
282 return VL;
283 }
284
285 /// Take the variable and machine-location from the DBG_VALUE (from the
286 /// function entry), and build a copy of an entry value backup location by
287 /// setting the register location to NewReg.
288 static VarLoc CreateEntryCopyBackupLoc(const MachineInstr &MI,
289 LexicalScopes &LS,
290 const DIExpression *EntryExpr,
291 unsigned NewReg) {
292 VarLoc VL(MI, LS);
293 assert(VL.Kind == RegisterKind)((VL.Kind == RegisterKind) ? static_cast<void> (0) : __assert_fail
("VL.Kind == RegisterKind", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 293, __PRETTY_FUNCTION__))
;
294 VL.Kind = EntryValueCopyBackupKind;
295 VL.Expr = EntryExpr;
296 VL.Loc.RegNo = NewReg;
297 return VL;
298 }
299
300 /// Copy the register location in DBG_VALUE MI, updating the register to
301 /// be NewReg.
302 static VarLoc CreateCopyLoc(const MachineInstr &MI, LexicalScopes &LS,
303 unsigned NewReg) {
304 VarLoc VL(MI, LS);
305 assert(VL.Kind == RegisterKind)((VL.Kind == RegisterKind) ? static_cast<void> (0) : __assert_fail
("VL.Kind == RegisterKind", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 305, __PRETTY_FUNCTION__))
;
306 VL.Loc.RegNo = NewReg;
307 return VL;
308 }
309
310 /// Take the variable described by DBG_VALUE MI, and create a VarLoc
311 /// locating it in the specified spill location.
312 static VarLoc CreateSpillLoc(const MachineInstr &MI, unsigned SpillBase,
313 int SpillOffset, LexicalScopes &LS) {
314 VarLoc VL(MI, LS);
315 assert(VL.Kind == RegisterKind)((VL.Kind == RegisterKind) ? static_cast<void> (0) : __assert_fail
("VL.Kind == RegisterKind", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 315, __PRETTY_FUNCTION__))
;
316 VL.Kind = SpillLocKind;
317 VL.Loc.SpillLocation = {SpillBase, SpillOffset};
318 return VL;
319 }
320
321 /// Create a DBG_VALUE representing this VarLoc in the given function.
322 /// Copies variable-specific information such as DILocalVariable and
323 /// inlining information from the original DBG_VALUE instruction, which may
324 /// have been several transfers ago.
325 MachineInstr *BuildDbgValue(MachineFunction &MF) const {
326 const DebugLoc &DbgLoc = MI.getDebugLoc();
327 bool Indirect = MI.isIndirectDebugValue();
328 const auto &IID = MI.getDesc();
329 const DILocalVariable *Var = MI.getDebugVariable();
330 const DIExpression *DIExpr = MI.getDebugExpression();
331
332 switch (Kind) {
333 case EntryValueKind:
334 // An entry value is a register location -- but with an updated
335 // expression. The register location of such DBG_VALUE is always the one
336 // from the entry DBG_VALUE, it does not matter if the entry value was
337 // copied in to another register due to some optimizations.
338 return BuildMI(MF, DbgLoc, IID, Indirect, MI.getOperand(0).getReg(),
339 Var, Expr);
340 case RegisterKind:
341 // Register locations are like the source DBG_VALUE, but with the
342 // register number from this VarLoc.
343 return BuildMI(MF, DbgLoc, IID, Indirect, Loc.RegNo, Var, DIExpr);
344 case SpillLocKind: {
345 // Spills are indirect DBG_VALUEs, with a base register and offset.
346 // Use the original DBG_VALUEs expression to build the spilt location
347 // on top of. FIXME: spill locations created before this pass runs
348 // are not recognized, and not handled here.
349 auto *SpillExpr = DIExpression::prepend(
350 DIExpr, DIExpression::ApplyOffset, Loc.SpillLocation.SpillOffset);
351 unsigned Base = Loc.SpillLocation.SpillBase;
352 return BuildMI(MF, DbgLoc, IID, true, Base, Var, SpillExpr);
353 }
354 case ImmediateKind: {
355 MachineOperand MO = MI.getOperand(0);
356 return BuildMI(MF, DbgLoc, IID, Indirect, MO, Var, DIExpr);
357 }
358 case EntryValueBackupKind:
359 case EntryValueCopyBackupKind:
360 case InvalidKind:
361 llvm_unreachable(::llvm::llvm_unreachable_internal("Tried to produce DBG_VALUE for invalid or backup VarLoc"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 362)
362 "Tried to produce DBG_VALUE for invalid or backup VarLoc")::llvm::llvm_unreachable_internal("Tried to produce DBG_VALUE for invalid or backup VarLoc"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 362)
;
363 }
364 llvm_unreachable("Unrecognized LiveDebugValues.VarLoc.Kind enum")::llvm::llvm_unreachable_internal("Unrecognized LiveDebugValues.VarLoc.Kind enum"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 364)
;
365 }
366
367 /// Is the Loc field a constant or constant object?
368 bool isConstant() const { return Kind == ImmediateKind; }
369
370 /// Check if the Loc field is an entry backup location.
371 bool isEntryBackupLoc() const {
372 return Kind == EntryValueBackupKind || Kind == EntryValueCopyBackupKind;
373 }
374
375 /// If this variable is described by a register holding the entry value,
376 /// return it, otherwise return 0.
377 unsigned getEntryValueBackupReg() const {
378 if (Kind == EntryValueBackupKind)
379 return Loc.RegNo;
380 return 0;
381 }
382
383 /// If this variable is described by a register holding the copy of the
384 /// entry value, return it, otherwise return 0.
385 unsigned getEntryValueCopyBackupReg() const {
386 if (Kind == EntryValueCopyBackupKind)
387 return Loc.RegNo;
388 return 0;
389 }
390
391 /// If this variable is described by a register, return it,
392 /// otherwise return 0.
393 unsigned isDescribedByReg() const {
394 if (Kind == RegisterKind)
395 return Loc.RegNo;
396 return 0;
397 }
398
399 /// Determine whether the lexical scope of this value's debug location
400 /// dominates MBB.
401 bool dominates(MachineBasicBlock &MBB) const { return UVS.dominates(&MBB); }
402
403#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
404 // TRI can be null.
405 void dump(const TargetRegisterInfo *TRI, raw_ostream &Out = dbgs()) const {
406 dbgs() << "VarLoc(";
407 switch (Kind) {
408 case RegisterKind:
409 case EntryValueKind:
410 case EntryValueBackupKind:
411 case EntryValueCopyBackupKind:
412 dbgs() << printReg(Loc.RegNo, TRI);
413 break;
414 case SpillLocKind:
415 dbgs() << printReg(Loc.SpillLocation.SpillBase, TRI);
416 dbgs() << "[" << Loc.SpillLocation.SpillOffset << "]";
417 break;
418 case ImmediateKind:
419 dbgs() << Loc.Immediate;
420 break;
421 case InvalidKind:
422 llvm_unreachable("Invalid VarLoc in dump method")::llvm::llvm_unreachable_internal("Invalid VarLoc in dump method"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 422)
;
423 }
424
425 dbgs() << ", \"" << Var.getVariable()->getName() << "\", " << *Expr
426 << ", ";
427 if (Var.getInlinedAt())
428 dbgs() << "!" << Var.getInlinedAt()->getMetadataID() << ")\n";
429 else
430 dbgs() << "(null))";
431
432 if (isEntryBackupLoc())
433 dbgs() << " (backup loc)\n";
434 else
435 dbgs() << "\n";
436 }
437#endif
438
439 bool operator==(const VarLoc &Other) const {
440 return Kind == Other.Kind && Var == Other.Var &&
441 Loc.Hash == Other.Loc.Hash && Expr == Other.Expr;
442 }
443
444 /// This operator guarantees that VarLocs are sorted by Variable first.
445 bool operator<(const VarLoc &Other) const {
446 return std::tie(Var, Kind, Loc.Hash, Expr) <
447 std::tie(Other.Var, Other.Kind, Other.Loc.Hash, Other.Expr);
448 }
449 };
450
451 /// VarLocMap is used for two things:
452 /// 1) Assigning a unique LocIndex to a VarLoc. This LocIndex can be used to
453 /// virtually insert a VarLoc into a VarLocSet.
454 /// 2) Given a LocIndex, look up the unique associated VarLoc.
455 class VarLocMap {
456 /// Map a VarLoc to an index within the vector reserved for its location
457 /// within Loc2Vars.
458 std::map<VarLoc, uint32_t> Var2Index;
459
460 /// Map a location to a vector which holds VarLocs which live in that
461 /// location.
462 SmallDenseMap<uint32_t, std::vector<VarLoc>> Loc2Vars;
463
464 public:
465 /// Retrieve a unique LocIndex for \p VL.
466 LocIndex insert(const VarLoc &VL) {
467 uint32_t Location = VL.isDescribedByReg();
468 uint32_t &Index = Var2Index[VL];
469 if (!Index) {
470 auto &Vars = Loc2Vars[Location];
471 Vars.push_back(VL);
472 Index = Vars.size();
473 }
474 return {Location, Index - 1};
475 }
476
477 /// Retrieve the unique VarLoc associated with \p ID.
478 const VarLoc &operator[](LocIndex ID) const {
479 auto LocIt = Loc2Vars.find(ID.Location);
480 assert(LocIt != Loc2Vars.end() && "Location not tracked")((LocIt != Loc2Vars.end() && "Location not tracked") ?
static_cast<void> (0) : __assert_fail ("LocIt != Loc2Vars.end() && \"Location not tracked\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 480, __PRETTY_FUNCTION__))
;
481 return LocIt->second[ID.Index];
482 }
483 };
484
485 using VarLocInMBB = SmallDenseMap<const MachineBasicBlock *, VarLocSet>;
486 struct TransferDebugPair {
487 MachineInstr *TransferInst; ///< Instruction where this transfer occurs.
488 LocIndex LocationID; ///< Location number for the transfer dest.
489 };
490 using TransferMap = SmallVector<TransferDebugPair, 4>;
491
492 // Types for recording sets of variable fragments that overlap. For a given
493 // local variable, we record all other fragments of that variable that could
494 // overlap it, to reduce search time.
495 using FragmentOfVar =
496 std::pair<const DILocalVariable *, DIExpression::FragmentInfo>;
497 using OverlapMap =
498 DenseMap<FragmentOfVar, SmallVector<DIExpression::FragmentInfo, 1>>;
499
500 // Helper while building OverlapMap, a map of all fragments seen for a given
501 // DILocalVariable.
502 using VarToFragments =
503 DenseMap<const DILocalVariable *, SmallSet<FragmentInfo, 4>>;
504
505 /// This holds the working set of currently open ranges. For fast
506 /// access, this is done both as a set of VarLocIDs, and a map of
507 /// DebugVariable to recent VarLocID. Note that a DBG_VALUE ends all
508 /// previous open ranges for the same variable. In addition, we keep
509 /// two different maps (Vars/EntryValuesBackupVars), so erase/insert
510 /// methods act differently depending on whether a VarLoc is primary
511 /// location or backup one. In the case the VarLoc is backup location
512 /// we will erase/insert from the EntryValuesBackupVars map, otherwise
513 /// we perform the operation on the Vars.
514 class OpenRangesSet {
515 VarLocSet VarLocs;
516 // Map the DebugVariable to recent primary location ID.
517 SmallDenseMap<DebugVariable, LocIndex, 8> Vars;
518 // Map the DebugVariable to recent backup location ID.
519 SmallDenseMap<DebugVariable, LocIndex, 8> EntryValuesBackupVars;
520 OverlapMap &OverlappingFragments;
521
522 public:
523 OpenRangesSet(VarLocSet::Allocator &Alloc, OverlapMap &_OLapMap)
524 : VarLocs(Alloc), OverlappingFragments(_OLapMap) {}
525
526 const VarLocSet &getVarLocs() const { return VarLocs; }
527
528 /// Terminate all open ranges for VL.Var by removing it from the set.
529 void erase(const VarLoc &VL);
530
531 /// Terminate all open ranges listed in \c KillSet by removing
532 /// them from the set.
533 void erase(const VarLocSet &KillSet, const VarLocMap &VarLocIDs);
534
535 /// Insert a new range into the set.
536 void insert(LocIndex VarLocID, const VarLoc &VL);
537
538 /// Insert a set of ranges.
539 void insertFromLocSet(const VarLocSet &ToLoad, const VarLocMap &Map) {
540 for (uint64_t ID : ToLoad) {
541 LocIndex Idx = LocIndex::fromRawInteger(ID);
542 const VarLoc &VarL = Map[Idx];
543 insert(Idx, VarL);
544 }
545 }
546
547 llvm::Optional<LocIndex> getEntryValueBackup(DebugVariable Var);
548
549 /// Empty the set.
550 void clear() {
551 VarLocs.clear();
552 Vars.clear();
553 EntryValuesBackupVars.clear();
554 }
555
556 /// Return whether the set is empty or not.
557 bool empty() const {
558 assert(Vars.empty() == EntryValuesBackupVars.empty() &&((Vars.empty() == EntryValuesBackupVars.empty() && Vars
.empty() == VarLocs.empty() && "open ranges are inconsistent"
) ? static_cast<void> (0) : __assert_fail ("Vars.empty() == EntryValuesBackupVars.empty() && Vars.empty() == VarLocs.empty() && \"open ranges are inconsistent\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 560, __PRETTY_FUNCTION__))
559 Vars.empty() == VarLocs.empty() &&((Vars.empty() == EntryValuesBackupVars.empty() && Vars
.empty() == VarLocs.empty() && "open ranges are inconsistent"
) ? static_cast<void> (0) : __assert_fail ("Vars.empty() == EntryValuesBackupVars.empty() && Vars.empty() == VarLocs.empty() && \"open ranges are inconsistent\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 560, __PRETTY_FUNCTION__))
560 "open ranges are inconsistent")((Vars.empty() == EntryValuesBackupVars.empty() && Vars
.empty() == VarLocs.empty() && "open ranges are inconsistent"
) ? static_cast<void> (0) : __assert_fail ("Vars.empty() == EntryValuesBackupVars.empty() && Vars.empty() == VarLocs.empty() && \"open ranges are inconsistent\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 560, __PRETTY_FUNCTION__))
;
561 return VarLocs.empty();
562 }
563 };
564
565 /// Collect all VarLoc IDs from \p CollectFrom for VarLocs which are located
566 /// in \p Reg, of kind RegisterKind. Insert collected IDs in \p Collected.
567 void collectIDsForReg(VarLocSet &Collected, uint32_t Reg,
568 const VarLocSet &CollectFrom) const;
569
570 /// Get the registers which are used by VarLocs of kind RegisterKind tracked
571 /// by \p CollectFrom.
572 void getUsedRegs(const VarLocSet &CollectFrom,
573 SmallVectorImpl<uint32_t> &UsedRegs) const;
574
575 VarLocSet &getVarLocsInMBB(const MachineBasicBlock *MBB, VarLocInMBB &Locs) {
576 auto Result = Locs.try_emplace(MBB, Alloc);
577 return Result.first->second;
578 }
579
580 const VarLocSet &getVarLocsInMBB(const MachineBasicBlock *MBB,
581 const VarLocInMBB &Locs) const {
582 auto It = Locs.find(MBB);
583 assert(It != Locs.end() && "MBB not in map")((It != Locs.end() && "MBB not in map") ? static_cast
<void> (0) : __assert_fail ("It != Locs.end() && \"MBB not in map\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 583, __PRETTY_FUNCTION__))
;
584 return It->second;
585 }
586
587 /// Tests whether this instruction is a spill to a stack location.
588 bool isSpillInstruction(const MachineInstr &MI, MachineFunction *MF);
589
590 /// Decide if @MI is a spill instruction and return true if it is. We use 2
591 /// criteria to make this decision:
592 /// - Is this instruction a store to a spill slot?
593 /// - Is there a register operand that is both used and killed?
594 /// TODO: Store optimization can fold spills into other stores (including
595 /// other spills). We do not handle this yet (more than one memory operand).
596 bool isLocationSpill(const MachineInstr &MI, MachineFunction *MF,
597 unsigned &Reg);
598
599 /// Returns true if the given machine instruction is a debug value which we
600 /// can emit entry values for.
601 ///
602 /// Currently, we generate debug entry values only for parameters that are
603 /// unmodified throughout the function and located in a register.
604 bool isEntryValueCandidate(const MachineInstr &MI,
605 const DefinedRegsSet &Regs) const;
606
607 /// If a given instruction is identified as a spill, return the spill location
608 /// and set \p Reg to the spilled register.
609 Optional<VarLoc::SpillLoc> isRestoreInstruction(const MachineInstr &MI,
610 MachineFunction *MF,
611 unsigned &Reg);
612 /// Given a spill instruction, extract the register and offset used to
613 /// address the spill location in a target independent way.
614 VarLoc::SpillLoc extractSpillBaseRegAndOffset(const MachineInstr &MI);
615 void insertTransferDebugPair(MachineInstr &MI, OpenRangesSet &OpenRanges,
616 TransferMap &Transfers, VarLocMap &VarLocIDs,
617 LocIndex OldVarID, TransferKind Kind,
618 unsigned NewReg = 0);
619
620 void transferDebugValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
621 VarLocMap &VarLocIDs);
622 void transferSpillOrRestoreInst(MachineInstr &MI, OpenRangesSet &OpenRanges,
623 VarLocMap &VarLocIDs, TransferMap &Transfers);
624 bool removeEntryValue(const MachineInstr &MI, OpenRangesSet &OpenRanges,
625 VarLocMap &VarLocIDs, const VarLoc &EntryVL);
626 void emitEntryValues(MachineInstr &MI, OpenRangesSet &OpenRanges,
627 VarLocMap &VarLocIDs, TransferMap &Transfers,
628 VarLocSet &KillSet);
629 void recordEntryValue(const MachineInstr &MI,
630 const DefinedRegsSet &DefinedRegs,
631 OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs);
632 void transferRegisterCopy(MachineInstr &MI, OpenRangesSet &OpenRanges,
633 VarLocMap &VarLocIDs, TransferMap &Transfers);
634 void transferRegisterDef(MachineInstr &MI, OpenRangesSet &OpenRanges,
635 VarLocMap &VarLocIDs, TransferMap &Transfers);
636 bool transferTerminator(MachineBasicBlock *MBB, OpenRangesSet &OpenRanges,
637 VarLocInMBB &OutLocs, const VarLocMap &VarLocIDs);
638
639 void process(MachineInstr &MI, OpenRangesSet &OpenRanges,
640 VarLocMap &VarLocIDs, TransferMap &Transfers);
641
642 void accumulateFragmentMap(MachineInstr &MI, VarToFragments &SeenFragments,
643 OverlapMap &OLapMap);
644
645 bool join(MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
646 const VarLocMap &VarLocIDs,
647 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
648 SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks,
649 VarLocInMBB &PendingInLocs);
650
651 /// Create DBG_VALUE insts for inlocs that have been propagated but
652 /// had their instruction creation deferred.
653 void flushPendingLocs(VarLocInMBB &PendingInLocs, VarLocMap &VarLocIDs);
654
655 bool ExtendRanges(MachineFunction &MF);
656
657public:
658 static char ID;
659
660 /// Default construct and initialize the pass.
661 LiveDebugValues();
662
663 /// Tell the pass manager which passes we depend on and what
664 /// information we preserve.
665 void getAnalysisUsage(AnalysisUsage &AU) const override;
666
667 MachineFunctionProperties getRequiredProperties() const override {
668 return MachineFunctionProperties().set(
669 MachineFunctionProperties::Property::NoVRegs);
670 }
671
672 /// Print to ostream with a message.
673 void printVarLocInMBB(const MachineFunction &MF, const VarLocInMBB &V,
674 const VarLocMap &VarLocIDs, const char *msg,
675 raw_ostream &Out) const;
676
677 /// Calculate the liveness information for the given machine function.
678 bool runOnMachineFunction(MachineFunction &MF) override;
679};
680
681} // end anonymous namespace
682
683//===----------------------------------------------------------------------===//
684// Implementation
685//===----------------------------------------------------------------------===//
686
687char LiveDebugValues::ID = 0;
688
689char &llvm::LiveDebugValuesID = LiveDebugValues::ID;
690
691INITIALIZE_PASS(LiveDebugValues, DEBUG_TYPE, "Live DEBUG_VALUE analysis",static void *initializeLiveDebugValuesPassOnce(PassRegistry &
Registry) { PassInfo *PI = new PassInfo( "Live DEBUG_VALUE analysis"
, "livedebugvalues", &LiveDebugValues::ID, PassInfo::NormalCtor_t
(callDefaultCtor<LiveDebugValues>), false, false); Registry
.registerPass(*PI, true); return PI; } static llvm::once_flag
InitializeLiveDebugValuesPassFlag; void llvm::initializeLiveDebugValuesPass
(PassRegistry &Registry) { llvm::call_once(InitializeLiveDebugValuesPassFlag
, initializeLiveDebugValuesPassOnce, std::ref(Registry)); }
692 false, false)static void *initializeLiveDebugValuesPassOnce(PassRegistry &
Registry) { PassInfo *PI = new PassInfo( "Live DEBUG_VALUE analysis"
, "livedebugvalues", &LiveDebugValues::ID, PassInfo::NormalCtor_t
(callDefaultCtor<LiveDebugValues>), false, false); Registry
.registerPass(*PI, true); return PI; } static llvm::once_flag
InitializeLiveDebugValuesPassFlag; void llvm::initializeLiveDebugValuesPass
(PassRegistry &Registry) { llvm::call_once(InitializeLiveDebugValuesPassFlag
, initializeLiveDebugValuesPassOnce, std::ref(Registry)); }
693
694/// Default construct and initialize the pass.
695LiveDebugValues::LiveDebugValues() : MachineFunctionPass(ID) {
696 initializeLiveDebugValuesPass(*PassRegistry::getPassRegistry());
697}
698
699/// Tell the pass manager which passes we depend on and what information we
700/// preserve.
701void LiveDebugValues::getAnalysisUsage(AnalysisUsage &AU) const {
702 AU.setPreservesCFG();
703 MachineFunctionPass::getAnalysisUsage(AU);
704}
705
706/// Erase a variable from the set of open ranges, and additionally erase any
707/// fragments that may overlap it. If the VarLoc is a buckup location, erase
708/// the variable from the EntryValuesBackupVars set, indicating we should stop
709/// tracking its backup entry location. Otherwise, if the VarLoc is primary
710/// location, erase the variable from the Vars set.
711void LiveDebugValues::OpenRangesSet::erase(const VarLoc &VL) {
712 // Erasure helper.
713 auto DoErase = [VL, this](DebugVariable VarToErase) {
714 auto *EraseFrom = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
715 auto It = EraseFrom->find(VarToErase);
716 if (It != EraseFrom->end()) {
717 LocIndex ID = It->second;
718 VarLocs.reset(ID.getAsRawInteger());
719 EraseFrom->erase(It);
720 }
721 };
722
723 DebugVariable Var = VL.Var;
724
725 // Erase the variable/fragment that ends here.
726 DoErase(Var);
727
728 // Extract the fragment. Interpret an empty fragment as one that covers all
729 // possible bits.
730 FragmentInfo ThisFragment = Var.getFragmentOrDefault();
731
732 // There may be fragments that overlap the designated fragment. Look them up
733 // in the pre-computed overlap map, and erase them too.
734 auto MapIt = OverlappingFragments.find({Var.getVariable(), ThisFragment});
735 if (MapIt != OverlappingFragments.end()) {
736 for (auto Fragment : MapIt->second) {
737 LiveDebugValues::OptFragmentInfo FragmentHolder;
738 if (!DebugVariable::isDefaultFragment(Fragment))
739 FragmentHolder = LiveDebugValues::OptFragmentInfo(Fragment);
740 DoErase({Var.getVariable(), FragmentHolder, Var.getInlinedAt()});
741 }
742 }
743}
744
745void LiveDebugValues::OpenRangesSet::erase(const VarLocSet &KillSet,
746 const VarLocMap &VarLocIDs) {
747 VarLocs.intersectWithComplement(KillSet);
748 for (uint64_t ID : KillSet) {
749 const VarLoc *VL = &VarLocIDs[LocIndex::fromRawInteger(ID)];
750 auto *EraseFrom = VL->isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
751 EraseFrom->erase(VL->Var);
752 }
753}
754
755void LiveDebugValues::OpenRangesSet::insert(LocIndex VarLocID,
756 const VarLoc &VL) {
757 auto *InsertInto = VL.isEntryBackupLoc() ? &EntryValuesBackupVars : &Vars;
758 VarLocs.set(VarLocID.getAsRawInteger());
759 InsertInto->insert({VL.Var, VarLocID});
760}
761
762/// Return the Loc ID of an entry value backup location, if it exists for the
763/// variable.
764llvm::Optional<LocIndex>
765LiveDebugValues::OpenRangesSet::getEntryValueBackup(DebugVariable Var) {
766 auto It = EntryValuesBackupVars.find(Var);
767 if (It != EntryValuesBackupVars.end())
768 return It->second;
769
770 return llvm::None;
771}
772
773void LiveDebugValues::collectIDsForReg(VarLocSet &Collected, uint32_t Reg,
774 const VarLocSet &CollectFrom) const {
775 // The half-open interval [FirstIndexForReg, FirstInvalidIndex) contains all
776 // possible VarLoc IDs for VarLocs of kind RegisterKind which live in Reg.
777 uint64_t FirstIndexForReg = LocIndex::rawIndexForReg(Reg);
778 uint64_t FirstInvalidIndex = LocIndex::rawIndexForReg(Reg + 1);
779 // Iterate through that half-open interval and collect all the set IDs.
780 for (auto It = CollectFrom.find(FirstIndexForReg), End = CollectFrom.end();
781 It != End && *It < FirstInvalidIndex; ++It)
782 Collected.set(*It);
783}
784
785void LiveDebugValues::getUsedRegs(const VarLocSet &CollectFrom,
786 SmallVectorImpl<uint32_t> &UsedRegs) const {
787 // All register-based VarLocs are assigned indices greater than or equal to
788 // FirstRegIndex.
789 uint64_t FirstRegIndex = LocIndex::rawIndexForReg(1);
790 for (auto It = CollectFrom.find(FirstRegIndex), End = CollectFrom.end();
791 It != End;) {
792 // We found a VarLoc ID for a VarLoc that lives in a register. Figure out
793 // which register and add it to UsedRegs.
794 uint32_t FoundReg = LocIndex::fromRawInteger(*It).Location;
795 assert((UsedRegs.empty() || FoundReg != UsedRegs.back()) &&(((UsedRegs.empty() || FoundReg != UsedRegs.back()) &&
"Duplicate used reg") ? static_cast<void> (0) : __assert_fail
("(UsedRegs.empty() || FoundReg != UsedRegs.back()) && \"Duplicate used reg\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 796, __PRETTY_FUNCTION__))
796 "Duplicate used reg")(((UsedRegs.empty() || FoundReg != UsedRegs.back()) &&
"Duplicate used reg") ? static_cast<void> (0) : __assert_fail
("(UsedRegs.empty() || FoundReg != UsedRegs.back()) && \"Duplicate used reg\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 796, __PRETTY_FUNCTION__))
;
797 UsedRegs.push_back(FoundReg);
798
799 // Skip to the next /set/ register. Note that this finds a lower bound, so
800 // even if there aren't any VarLocs living in `FoundReg+1`, we're still
801 // guaranteed to move on to the next register (or to end()).
802 uint64_t NextRegIndex = LocIndex::rawIndexForReg(FoundReg + 1);
803 It = CollectFrom.find(NextRegIndex);
804 }
805}
806
807//===----------------------------------------------------------------------===//
808// Debug Range Extension Implementation
809//===----------------------------------------------------------------------===//
810
811#ifndef NDEBUG
812void LiveDebugValues::printVarLocInMBB(const MachineFunction &MF,
813 const VarLocInMBB &V,
814 const VarLocMap &VarLocIDs,
815 const char *msg,
816 raw_ostream &Out) const {
817 Out << '\n' << msg << '\n';
818 for (const MachineBasicBlock &BB : MF) {
819 if (!V.count(&BB))
820 continue;
821 const VarLocSet &L = getVarLocsInMBB(&BB, V);
822 if (L.empty())
823 continue;
824 Out << "MBB: " << BB.getNumber() << ":\n";
825 for (uint64_t VLL : L) {
826 const VarLoc &VL = VarLocIDs[LocIndex::fromRawInteger(VLL)];
827 Out << " Var: " << VL.Var.getVariable()->getName();
828 Out << " MI: ";
829 VL.dump(TRI, Out);
830 }
831 }
832 Out << "\n";
833}
834#endif
835
836LiveDebugValues::VarLoc::SpillLoc
837LiveDebugValues::extractSpillBaseRegAndOffset(const MachineInstr &MI) {
838 assert(MI.hasOneMemOperand() &&((MI.hasOneMemOperand() && "Spill instruction does not have exactly one memory operand?"
) ? static_cast<void> (0) : __assert_fail ("MI.hasOneMemOperand() && \"Spill instruction does not have exactly one memory operand?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 839, __PRETTY_FUNCTION__))
839 "Spill instruction does not have exactly one memory operand?")((MI.hasOneMemOperand() && "Spill instruction does not have exactly one memory operand?"
) ? static_cast<void> (0) : __assert_fail ("MI.hasOneMemOperand() && \"Spill instruction does not have exactly one memory operand?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 839, __PRETTY_FUNCTION__))
;
840 auto MMOI = MI.memoperands_begin();
841 const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue();
842 assert(PVal->kind() == PseudoSourceValue::FixedStack &&((PVal->kind() == PseudoSourceValue::FixedStack &&
"Inconsistent memory operand in spill instruction") ? static_cast
<void> (0) : __assert_fail ("PVal->kind() == PseudoSourceValue::FixedStack && \"Inconsistent memory operand in spill instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 843, __PRETTY_FUNCTION__))
843 "Inconsistent memory operand in spill instruction")((PVal->kind() == PseudoSourceValue::FixedStack &&
"Inconsistent memory operand in spill instruction") ? static_cast
<void> (0) : __assert_fail ("PVal->kind() == PseudoSourceValue::FixedStack && \"Inconsistent memory operand in spill instruction\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 843, __PRETTY_FUNCTION__))
;
844 int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
845 const MachineBasicBlock *MBB = MI.getParent();
846 unsigned Reg;
847 int Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg);
848 return {Reg, Offset};
849}
850
851/// Try to salvage the debug entry value if we encounter a new debug value
852/// describing the same parameter, otherwise stop tracking the value. Return
853/// true if we should stop tracking the entry value, otherwise return false.
854bool LiveDebugValues::removeEntryValue(const MachineInstr &MI,
855 OpenRangesSet &OpenRanges,
856 VarLocMap &VarLocIDs,
857 const VarLoc &EntryVL) {
858 // Skip the DBG_VALUE which is the debug entry value itself.
859 if (MI.isIdenticalTo(EntryVL.MI))
860 return false;
861
862 // If the parameter's location is not register location, we can not track
863 // the entry value any more. In addition, if the debug expression from the
864 // DBG_VALUE is not empty, we can assume the parameter's value has changed
865 // indicating that we should stop tracking its entry value as well.
866 if (!MI.getOperand(0).isReg() ||
867 MI.getDebugExpression()->getNumElements() != 0)
868 return true;
869
870 // If the DBG_VALUE comes from a copy instruction that copies the entry value,
871 // it means the parameter's value has not changed and we should be able to use
872 // its entry value.
873 bool TrySalvageEntryValue = false;
874 Register Reg = MI.getOperand(0).getReg();
875 auto I = std::next(MI.getReverseIterator());
876 const MachineOperand *SrcRegOp, *DestRegOp;
877 if (I != MI.getParent()->rend()) {
878 // TODO: Try to keep tracking of an entry value if we encounter a propagated
879 // DBG_VALUE describing the copy of the entry value. (Propagated entry value
880 // does not indicate the parameter modification.)
881 auto DestSrc = TII->isCopyInstr(*I);
882 if (!DestSrc)
883 return true;
884
885 SrcRegOp = DestSrc->Source;
886 DestRegOp = DestSrc->Destination;
887 if (Reg != DestRegOp->getReg())
888 return true;
889 TrySalvageEntryValue = true;
890 }
891
892 if (TrySalvageEntryValue) {
893 for (uint64_t ID : OpenRanges.getVarLocs()) {
894 const VarLoc &VL = VarLocIDs[LocIndex::fromRawInteger(ID)];
895 if (!VL.isEntryBackupLoc())
896 continue;
897
898 if (VL.getEntryValueCopyBackupReg() == Reg &&
899 VL.MI.getOperand(0).getReg() == SrcRegOp->getReg())
900 return false;
901 }
902 }
903
904 return true;
905}
906
907/// End all previous ranges related to @MI and start a new range from @MI
908/// if it is a DBG_VALUE instr.
909void LiveDebugValues::transferDebugValue(const MachineInstr &MI,
910 OpenRangesSet &OpenRanges,
911 VarLocMap &VarLocIDs) {
912 if (!MI.isDebugValue())
913 return;
914 const DILocalVariable *Var = MI.getDebugVariable();
915 const DIExpression *Expr = MI.getDebugExpression();
916 const DILocation *DebugLoc = MI.getDebugLoc();
917 const DILocation *InlinedAt = DebugLoc->getInlinedAt();
918 assert(Var->isValidLocationForIntrinsic(DebugLoc) &&((Var->isValidLocationForIntrinsic(DebugLoc) && "Expected inlined-at fields to agree"
) ? static_cast<void> (0) : __assert_fail ("Var->isValidLocationForIntrinsic(DebugLoc) && \"Expected inlined-at fields to agree\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 919, __PRETTY_FUNCTION__))
919 "Expected inlined-at fields to agree")((Var->isValidLocationForIntrinsic(DebugLoc) && "Expected inlined-at fields to agree"
) ? static_cast<void> (0) : __assert_fail ("Var->isValidLocationForIntrinsic(DebugLoc) && \"Expected inlined-at fields to agree\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 919, __PRETTY_FUNCTION__))
;
920
921 DebugVariable V(Var, Expr, InlinedAt);
922
923 // Check if this DBG_VALUE indicates a parameter's value changing.
924 // If that is the case, we should stop tracking its entry value.
925 auto EntryValBackupID = OpenRanges.getEntryValueBackup(V);
926 if (Var->isParameter() && EntryValBackupID) {
927 const VarLoc &EntryVL = VarLocIDs[*EntryValBackupID];
928 if (removeEntryValue(MI, OpenRanges, VarLocIDs, EntryVL)) {
929 LLVM_DEBUG(dbgs() << "Deleting a DBG entry value because of: ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { dbgs() << "Deleting a DBG entry value because of: "
; MI.print(dbgs(), false, false, false, true, TII); } } while
(false)
930 MI.print(dbgs(), /*IsStandalone*/ false,do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { dbgs() << "Deleting a DBG entry value because of: "
; MI.print(dbgs(), false, false, false, true, TII); } } while
(false)
931 /*SkipOpers*/ false, /*SkipDebugLoc*/ false,do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { dbgs() << "Deleting a DBG entry value because of: "
; MI.print(dbgs(), false, false, false, true, TII); } } while
(false)
932 /*AddNewLine*/ true, TII))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { dbgs() << "Deleting a DBG entry value because of: "
; MI.print(dbgs(), false, false, false, true, TII); } } while
(false)
;
933 OpenRanges.erase(EntryVL);
934 }
935 }
936
937 if (isDbgValueDescribedByReg(MI) || MI.getOperand(0).isImm() ||
938 MI.getOperand(0).isFPImm() || MI.getOperand(0).isCImm()) {
939 // Use normal VarLoc constructor for registers and immediates.
940 VarLoc VL(MI, LS);
941 // End all previous ranges of VL.Var.
942 OpenRanges.erase(VL);
943
944 LocIndex ID = VarLocIDs.insert(VL);
945 // Add the VarLoc to OpenRanges from this DBG_VALUE.
946 OpenRanges.insert(ID, VL);
947 } else if (MI.hasOneMemOperand()) {
948 llvm_unreachable("DBG_VALUE with mem operand encountered after regalloc?")::llvm::llvm_unreachable_internal("DBG_VALUE with mem operand encountered after regalloc?"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 948)
;
949 } else {
950 // This must be an undefined location. We should leave OpenRanges closed.
951 assert(MI.getOperand(0).isReg() && MI.getOperand(0).getReg() == 0 &&((MI.getOperand(0).isReg() && MI.getOperand(0).getReg
() == 0 && "Unexpected non-undef DBG_VALUE encountered"
) ? static_cast<void> (0) : __assert_fail ("MI.getOperand(0).isReg() && MI.getOperand(0).getReg() == 0 && \"Unexpected non-undef DBG_VALUE encountered\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 952, __PRETTY_FUNCTION__))
952 "Unexpected non-undef DBG_VALUE encountered")((MI.getOperand(0).isReg() && MI.getOperand(0).getReg
() == 0 && "Unexpected non-undef DBG_VALUE encountered"
) ? static_cast<void> (0) : __assert_fail ("MI.getOperand(0).isReg() && MI.getOperand(0).getReg() == 0 && \"Unexpected non-undef DBG_VALUE encountered\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 952, __PRETTY_FUNCTION__))
;
953 }
954}
955
956/// Turn the entry value backup locations into primary locations.
957void LiveDebugValues::emitEntryValues(MachineInstr &MI,
958 OpenRangesSet &OpenRanges,
959 VarLocMap &VarLocIDs,
960 TransferMap &Transfers,
961 VarLocSet &KillSet) {
962 // Do not insert entry value locations after a terminator.
963 if (MI.isTerminator())
964 return;
965
966 for (uint64_t ID : KillSet) {
967 LocIndex Idx = LocIndex::fromRawInteger(ID);
968 const VarLoc &VL = VarLocIDs[Idx];
969 if (!VL.Var.getVariable()->isParameter())
970 continue;
971
972 auto DebugVar = VL.Var;
973 Optional<LocIndex> EntryValBackupID =
974 OpenRanges.getEntryValueBackup(DebugVar);
975
976 // If the parameter has the entry value backup, it means we should
977 // be able to use its entry value.
978 if (!EntryValBackupID)
979 continue;
980
981 const VarLoc &EntryVL = VarLocIDs[*EntryValBackupID];
982 VarLoc EntryLoc =
983 VarLoc::CreateEntryLoc(EntryVL.MI, LS, EntryVL.Expr, EntryVL.Loc.RegNo);
984 LocIndex EntryValueID = VarLocIDs.insert(EntryLoc);
985 Transfers.push_back({&MI, EntryValueID});
986 OpenRanges.insert(EntryValueID, EntryLoc);
987 }
988}
989
990/// Create new TransferDebugPair and insert it in \p Transfers. The VarLoc
991/// with \p OldVarID should be deleted form \p OpenRanges and replaced with
992/// new VarLoc. If \p NewReg is different than default zero value then the
993/// new location will be register location created by the copy like instruction,
994/// otherwise it is variable's location on the stack.
995void LiveDebugValues::insertTransferDebugPair(
996 MachineInstr &MI, OpenRangesSet &OpenRanges, TransferMap &Transfers,
997 VarLocMap &VarLocIDs, LocIndex OldVarID, TransferKind Kind,
998 unsigned NewReg) {
999 const MachineInstr *DebugInstr = &VarLocIDs[OldVarID].MI;
1000
1001 auto ProcessVarLoc = [&MI, &OpenRanges, &Transfers, &VarLocIDs](VarLoc &VL) {
1002 LocIndex LocId = VarLocIDs.insert(VL);
1003
1004 // Close this variable's previous location range.
1005 OpenRanges.erase(VL);
1006
1007 // Record the new location as an open range, and a postponed transfer
1008 // inserting a DBG_VALUE for this location.
1009 OpenRanges.insert(LocId, VL);
1010 assert(!MI.isTerminator() && "Cannot insert DBG_VALUE after terminator")((!MI.isTerminator() && "Cannot insert DBG_VALUE after terminator"
) ? static_cast<void> (0) : __assert_fail ("!MI.isTerminator() && \"Cannot insert DBG_VALUE after terminator\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 1010, __PRETTY_FUNCTION__))
;
1011 TransferDebugPair MIP = {&MI, LocId};
1012 Transfers.push_back(MIP);
1013 };
1014
1015 // End all previous ranges of VL.Var.
1016 OpenRanges.erase(VarLocIDs[OldVarID]);
1017 switch (Kind) {
1018 case TransferKind::TransferCopy: {
1019 assert(NewReg &&((NewReg && "No register supplied when handling a copy of a debug value"
) ? static_cast<void> (0) : __assert_fail ("NewReg && \"No register supplied when handling a copy of a debug value\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 1020, __PRETTY_FUNCTION__))
1020 "No register supplied when handling a copy of a debug value")((NewReg && "No register supplied when handling a copy of a debug value"
) ? static_cast<void> (0) : __assert_fail ("NewReg && \"No register supplied when handling a copy of a debug value\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 1020, __PRETTY_FUNCTION__))
;
1021 // Create a DBG_VALUE instruction to describe the Var in its new
1022 // register location.
1023 VarLoc VL = VarLoc::CreateCopyLoc(*DebugInstr, LS, NewReg);
1024 ProcessVarLoc(VL);
1025 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { dbgs() << "Creating VarLoc for register copy:"
; VL.dump(TRI); }; } } while (false)
1026 dbgs() << "Creating VarLoc for register copy:";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { dbgs() << "Creating VarLoc for register copy:"
; VL.dump(TRI); }; } } while (false)
1027 VL.dump(TRI);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { dbgs() << "Creating VarLoc for register copy:"
; VL.dump(TRI); }; } } while (false)
1028 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { dbgs() << "Creating VarLoc for register copy:"
; VL.dump(TRI); }; } } while (false)
;
1029 return;
1030 }
1031 case TransferKind::TransferSpill: {
1032 // Create a DBG_VALUE instruction to describe the Var in its spilled
1033 // location.
1034 VarLoc::SpillLoc SpillLocation = extractSpillBaseRegAndOffset(MI);
1035 VarLoc VL = VarLoc::CreateSpillLoc(*DebugInstr, SpillLocation.SpillBase,
1036 SpillLocation.SpillOffset, LS);
1037 ProcessVarLoc(VL);
1038 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { dbgs() << "Creating VarLoc for spill:"
; VL.dump(TRI); }; } } while (false)
1039 dbgs() << "Creating VarLoc for spill:";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { dbgs() << "Creating VarLoc for spill:"
; VL.dump(TRI); }; } } while (false)
1040 VL.dump(TRI);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { dbgs() << "Creating VarLoc for spill:"
; VL.dump(TRI); }; } } while (false)
1041 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { dbgs() << "Creating VarLoc for spill:"
; VL.dump(TRI); }; } } while (false)
;
1042 return;
1043 }
1044 case TransferKind::TransferRestore: {
1045 assert(NewReg &&((NewReg && "No register supplied when handling a restore of a debug value"
) ? static_cast<void> (0) : __assert_fail ("NewReg && \"No register supplied when handling a restore of a debug value\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 1046, __PRETTY_FUNCTION__))
1046 "No register supplied when handling a restore of a debug value")((NewReg && "No register supplied when handling a restore of a debug value"
) ? static_cast<void> (0) : __assert_fail ("NewReg && \"No register supplied when handling a restore of a debug value\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 1046, __PRETTY_FUNCTION__))
;
1047 // DebugInstr refers to the pre-spill location, therefore we can reuse
1048 // its expression.
1049 VarLoc VL = VarLoc::CreateCopyLoc(*DebugInstr, LS, NewReg);
1050 ProcessVarLoc(VL);
1051 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { dbgs() << "Creating VarLoc for restore:"
; VL.dump(TRI); }; } } while (false)
1052 dbgs() << "Creating VarLoc for restore:";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { dbgs() << "Creating VarLoc for restore:"
; VL.dump(TRI); }; } } while (false)
1053 VL.dump(TRI);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { dbgs() << "Creating VarLoc for restore:"
; VL.dump(TRI); }; } } while (false)
1054 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { dbgs() << "Creating VarLoc for restore:"
; VL.dump(TRI); }; } } while (false)
;
1055 return;
1056 }
1057 }
1058 llvm_unreachable("Invalid transfer kind")::llvm::llvm_unreachable_internal("Invalid transfer kind", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 1058)
;
1059}
1060
1061/// A definition of a register may mark the end of a range.
1062void LiveDebugValues::transferRegisterDef(
1063 MachineInstr &MI, OpenRangesSet &OpenRanges, VarLocMap &VarLocIDs,
1064 TransferMap &Transfers) {
1065
1066 // Meta Instructions do not affect the debug liveness of any register they
1067 // define.
1068 if (MI.isMetaInstruction())
1069 return;
1070
1071 MachineFunction *MF = MI.getMF();
1072 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
1073 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
1074
1075 // Find the regs killed by MI, and find regmasks of preserved regs.
1076 // Max out the number of statically allocated elements in `DeadRegs`, as this
1077 // prevents fallback to std::set::count() operations.
1078 SmallSet<uint32_t, 32> DeadRegs;
1079 SmallVector<const uint32_t *, 4> RegMasks;
1080 for (const MachineOperand &MO : MI.operands()) {
1081 // Determine whether the operand is a register def.
1082 if (MO.isReg() && MO.isDef() && MO.getReg() &&
1083 Register::isPhysicalRegister(MO.getReg()) &&
1084 !(MI.isCall() && MO.getReg() == SP)) {
1085 // Remove ranges of all aliased registers.
1086 for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI)
1087 // FIXME: Can we break out of this loop early if no insertion occurs?
1088 DeadRegs.insert(*RAI);
1089 } else if (MO.isRegMask()) {
1090 RegMasks.push_back(MO.getRegMask());
1091 }
1092 }
1093
1094 // Erase VarLocs which reside in one of the dead registers. For performance
1095 // reasons, it's critical to not iterate over the full set of open VarLocs.
1096 // Iterate over the set of dying/used regs instead.
1097 VarLocSet KillSet(Alloc);
1098 for (uint32_t DeadReg : DeadRegs)
1099 collectIDsForReg(KillSet, DeadReg, OpenRanges.getVarLocs());
1100 if (!RegMasks.empty()) {
1101 SmallVector<uint32_t, 32> UsedRegs;
1102 getUsedRegs(OpenRanges.getVarLocs(), UsedRegs);
1103 for (uint32_t Reg : UsedRegs) {
1104 // The VarLocs residing in this register are already in the kill set.
1105 if (DeadRegs.count(Reg))
1106 continue;
1107
1108 // Remove ranges of all clobbered registers. Register masks don't usually
1109 // list SP as preserved. Assume that call instructions never clobber SP,
1110 // because some backends (e.g., AArch64) never list SP in the regmask.
1111 // While the debug info may be off for an instruction or two around
1112 // callee-cleanup calls, transferring the DEBUG_VALUE across the call is
1113 // still a better user experience.
1114 if (Reg == SP)
1115 continue;
1116 bool AnyRegMaskKillsReg =
1117 any_of(RegMasks, [Reg](const uint32_t *RegMask) {
1118 return MachineOperand::clobbersPhysReg(RegMask, Reg);
1119 });
1120 if (AnyRegMaskKillsReg)
1121 collectIDsForReg(KillSet, Reg, OpenRanges.getVarLocs());
1122 }
1123 }
1124 OpenRanges.erase(KillSet, VarLocIDs);
1125
1126 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
1127 auto &TM = TPC->getTM<TargetMachine>();
1128 if (TM.Options.EnableDebugEntryValues)
1129 emitEntryValues(MI, OpenRanges, VarLocIDs, Transfers, KillSet);
1130 }
1131}
1132
1133bool LiveDebugValues::isSpillInstruction(const MachineInstr &MI,
1134 MachineFunction *MF) {
1135 // TODO: Handle multiple stores folded into one.
1136 if (!MI.hasOneMemOperand())
1137 return false;
1138
1139 if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII))
1140 return false; // This is not a spill instruction, since no valid size was
1141 // returned from either function.
1142
1143 return true;
1144}
1145
1146bool LiveDebugValues::isLocationSpill(const MachineInstr &MI,
1147 MachineFunction *MF, unsigned &Reg) {
1148 if (!isSpillInstruction(MI, MF))
1149 return false;
1150
1151 auto isKilledReg = [&](const MachineOperand MO, unsigned &Reg) {
1152 if (!MO.isReg() || !MO.isUse()) {
1153 Reg = 0;
1154 return false;
1155 }
1156 Reg = MO.getReg();
1157 return MO.isKill();
1158 };
1159
1160 for (const MachineOperand &MO : MI.operands()) {
1161 // In a spill instruction generated by the InlineSpiller the spilled
1162 // register has its kill flag set.
1163 if (isKilledReg(MO, Reg))
1164 return true;
1165 if (Reg != 0) {
1166 // Check whether next instruction kills the spilled register.
1167 // FIXME: Current solution does not cover search for killed register in
1168 // bundles and instructions further down the chain.
1169 auto NextI = std::next(MI.getIterator());
1170 // Skip next instruction that points to basic block end iterator.
1171 if (MI.getParent()->end() == NextI)
1172 continue;
1173 unsigned RegNext;
1174 for (const MachineOperand &MONext : NextI->operands()) {
1175 // Return true if we came across the register from the
1176 // previous spill instruction that is killed in NextI.
1177 if (isKilledReg(MONext, RegNext) && RegNext == Reg)
1178 return true;
1179 }
1180 }
1181 }
1182 // Return false if we didn't find spilled register.
1183 return false;
1184}
1185
1186Optional<LiveDebugValues::VarLoc::SpillLoc>
1187LiveDebugValues::isRestoreInstruction(const MachineInstr &MI,
1188 MachineFunction *MF, unsigned &Reg) {
1189 if (!MI.hasOneMemOperand())
1190 return None;
1191
1192 // FIXME: Handle folded restore instructions with more than one memory
1193 // operand.
1194 if (MI.getRestoreSize(TII)) {
1195 Reg = MI.getOperand(0).getReg();
1196 return extractSpillBaseRegAndOffset(MI);
1197 }
1198 return None;
1199}
1200
1201/// A spilled register may indicate that we have to end the current range of
1202/// a variable and create a new one for the spill location.
1203/// A restored register may indicate the reverse situation.
1204/// We don't want to insert any instructions in process(), so we just create
1205/// the DBG_VALUE without inserting it and keep track of it in \p Transfers.
1206/// It will be inserted into the BB when we're done iterating over the
1207/// instructions.
1208void LiveDebugValues::transferSpillOrRestoreInst(MachineInstr &MI,
1209 OpenRangesSet &OpenRanges,
1210 VarLocMap &VarLocIDs,
1211 TransferMap &Transfers) {
1212 MachineFunction *MF = MI.getMF();
1213 TransferKind TKind;
1214 unsigned Reg;
1215 Optional<VarLoc::SpillLoc> Loc;
1216
1217 LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump();)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { dbgs() << "Examining instruction: "
; MI.dump();; } } while (false)
;
1218
1219 // First, if there are any DBG_VALUEs pointing at a spill slot that is
1220 // written to, then close the variable location. The value in memory
1221 // will have changed.
1222 VarLocSet KillSet(Alloc);
1223 if (isSpillInstruction(MI, MF)) {
1224 Loc = extractSpillBaseRegAndOffset(MI);
1225 for (uint64_t ID : OpenRanges.getVarLocs()) {
1226 LocIndex Idx = LocIndex::fromRawInteger(ID);
1227 const VarLoc &VL = VarLocIDs[Idx];
1228 if (VL.Kind == VarLoc::SpillLocKind && VL.Loc.SpillLocation == *Loc) {
1229 // This location is overwritten by the current instruction -- terminate
1230 // the open range, and insert an explicit DBG_VALUE $noreg.
1231 //
1232 // Doing this at a later stage would require re-interpreting all
1233 // DBG_VALUes and DIExpressions to identify whether they point at
1234 // memory, and then analysing all memory writes to see if they
1235 // overwrite that memory, which is expensive.
1236 //
1237 // At this stage, we already know which DBG_VALUEs are for spills and
1238 // where they are located; it's best to fix handle overwrites now.
1239 KillSet.set(ID);
1240 VarLoc UndefVL = VarLoc::CreateCopyLoc(VL.MI, LS, 0);
1241 LocIndex UndefLocID = VarLocIDs.insert(UndefVL);
1242 Transfers.push_back({&MI, UndefLocID});
1243 }
1244 }
1245 OpenRanges.erase(KillSet, VarLocIDs);
1246 }
1247
1248 // Try to recognise spill and restore instructions that may create a new
1249 // variable location.
1250 if (isLocationSpill(MI, MF, Reg)) {
1251 TKind = TransferKind::TransferSpill;
1252 LLVM_DEBUG(dbgs() << "Recognized as spill: "; MI.dump();)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { dbgs() << "Recognized as spill: "
; MI.dump();; } } while (false)
;
1253 LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { dbgs() << "Register: " << Reg
<< " " << printReg(Reg, TRI) << "\n"; } } while
(false)
1254 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { dbgs() << "Register: " << Reg
<< " " << printReg(Reg, TRI) << "\n"; } } while
(false)
;
1255 } else {
1256 if (!(Loc = isRestoreInstruction(MI, MF, Reg)))
1257 return;
1258 TKind = TransferKind::TransferRestore;
1259 LLVM_DEBUG(dbgs() << "Recognized as restore: "; MI.dump();)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { dbgs() << "Recognized as restore: "
; MI.dump();; } } while (false)
;
1260 LLVM_DEBUG(dbgs() << "Register: " << Reg << " " << printReg(Reg, TRI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { dbgs() << "Register: " << Reg
<< " " << printReg(Reg, TRI) << "\n"; } } while
(false)
1261 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { dbgs() << "Register: " << Reg
<< " " << printReg(Reg, TRI) << "\n"; } } while
(false)
;
1262 }
1263 // Check if the register or spill location is the location of a debug value.
1264 for (uint64_t ID : OpenRanges.getVarLocs()) {
1265 LocIndex Idx = LocIndex::fromRawInteger(ID);
1266 const VarLoc &VL = VarLocIDs[Idx];
1267 if (TKind == TransferKind::TransferSpill && VL.isDescribedByReg() == Reg) {
1268 LLVM_DEBUG(dbgs() << "Spilling Register " << printReg(Reg, TRI) << '('do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { dbgs() << "Spilling Register " <<
printReg(Reg, TRI) << '(' << VL.Var.getVariable(
)->getName() << ")\n"; } } while (false)
1269 << VL.Var.getVariable()->getName() << ")\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { dbgs() << "Spilling Register " <<
printReg(Reg, TRI) << '(' << VL.Var.getVariable(
)->getName() << ")\n"; } } while (false)
;
1270 } else if (TKind == TransferKind::TransferRestore &&
1271 VL.Kind == VarLoc::SpillLocKind &&
1272 VL.Loc.SpillLocation == *Loc) {
1273 LLVM_DEBUG(dbgs() << "Restoring Register " << printReg(Reg, TRI) << '('do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { dbgs() << "Restoring Register " <<
printReg(Reg, TRI) << '(' << VL.Var.getVariable(
)->getName() << ")\n"; } } while (false)
1274 << VL.Var.getVariable()->getName() << ")\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { dbgs() << "Restoring Register " <<
printReg(Reg, TRI) << '(' << VL.Var.getVariable(
)->getName() << ")\n"; } } while (false)
;
1275 } else
1276 continue;
1277 insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, Idx, TKind,
1278 Reg);
1279 return;
1280 }
1281}
1282
1283/// If \p MI is a register copy instruction, that copies a previously tracked
1284/// value from one register to another register that is callee saved, we
1285/// create new DBG_VALUE instruction described with copy destination register.
1286void LiveDebugValues::transferRegisterCopy(MachineInstr &MI,
1287 OpenRangesSet &OpenRanges,
1288 VarLocMap &VarLocIDs,
1289 TransferMap &Transfers) {
1290 auto DestSrc = TII->isCopyInstr(MI);
1291 if (!DestSrc)
1292 return;
1293
1294 const MachineOperand *DestRegOp = DestSrc->Destination;
1295 const MachineOperand *SrcRegOp = DestSrc->Source;
1296
1297 if (!DestRegOp->isDef())
1298 return;
1299
1300 auto isCalleeSavedReg = [&](unsigned Reg) {
1301 for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI)
1302 if (CalleeSavedRegs.test(*RAI))
1303 return true;
1304 return false;
1305 };
1306
1307 Register SrcReg = SrcRegOp->getReg();
1308 Register DestReg = DestRegOp->getReg();
1309
1310 // We want to recognize instructions where destination register is callee
1311 // saved register. If register that could be clobbered by the call is
1312 // included, there would be a great chance that it is going to be clobbered
1313 // soon. It is more likely that previous register location, which is callee
1314 // saved, is going to stay unclobbered longer, even if it is killed.
1315 if (!isCalleeSavedReg(DestReg))
1316 return;
1317
1318 // Remember an entry value movement. If we encounter a new debug value of
1319 // a parameter describing only a moving of the value around, rather then
1320 // modifying it, we are still able to use the entry value if needed.
1321 if (isRegOtherThanSPAndFP(*DestRegOp, MI, TRI)) {
1322 for (uint64_t ID : OpenRanges.getVarLocs()) {
1323 LocIndex Idx = LocIndex::fromRawInteger(ID);
1324 const VarLoc &VL = VarLocIDs[Idx];
1325 if (VL.getEntryValueBackupReg() == SrcReg) {
1326 LLVM_DEBUG(dbgs() << "Copy of the entry value: "; MI.dump();)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { dbgs() << "Copy of the entry value: "
; MI.dump();; } } while (false)
;
1327 VarLoc EntryValLocCopyBackup =
1328 VarLoc::CreateEntryCopyBackupLoc(VL.MI, LS, VL.Expr, DestReg);
1329
1330 // Stop tracking the original entry value.
1331 OpenRanges.erase(VL);
1332
1333 // Start tracking the entry value copy.
1334 LocIndex EntryValCopyLocID = VarLocIDs.insert(EntryValLocCopyBackup);
1335 OpenRanges.insert(EntryValCopyLocID, EntryValLocCopyBackup);
1336 break;
1337 }
1338 }
1339 }
1340
1341 if (!SrcRegOp->isKill())
1342 return;
1343
1344 for (uint64_t ID : OpenRanges.getVarLocs()) {
1345 LocIndex Idx = LocIndex::fromRawInteger(ID);
1346 if (VarLocIDs[Idx].isDescribedByReg() == SrcReg) {
1347 insertTransferDebugPair(MI, OpenRanges, Transfers, VarLocIDs, Idx,
1348 TransferKind::TransferCopy, DestReg);
1349 return;
1350 }
1351 }
1352}
1353
1354/// Terminate all open ranges at the end of the current basic block.
1355bool LiveDebugValues::transferTerminator(MachineBasicBlock *CurMBB,
1356 OpenRangesSet &OpenRanges,
1357 VarLocInMBB &OutLocs,
1358 const VarLocMap &VarLocIDs) {
1359 bool Changed = false;
1360
1361 LLVM_DEBUG(for (uint64_t IDdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { for (uint64_t ID : OpenRanges.getVarLocs
()) { dbgs() << "Add to OutLocs in MBB #" << CurMBB
->getNumber() << ": "; VarLocIDs[LocIndex::fromRawInteger
(ID)].dump(TRI); }; } } while (false)
1362 : OpenRanges.getVarLocs()) {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { for (uint64_t ID : OpenRanges.getVarLocs
()) { dbgs() << "Add to OutLocs in MBB #" << CurMBB
->getNumber() << ": "; VarLocIDs[LocIndex::fromRawInteger
(ID)].dump(TRI); }; } } while (false)
1363 // Copy OpenRanges to OutLocs, if not already present.do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { for (uint64_t ID : OpenRanges.getVarLocs
()) { dbgs() << "Add to OutLocs in MBB #" << CurMBB
->getNumber() << ": "; VarLocIDs[LocIndex::fromRawInteger
(ID)].dump(TRI); }; } } while (false)
1364 dbgs() << "Add to OutLocs in MBB #" << CurMBB->getNumber() << ": ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { for (uint64_t ID : OpenRanges.getVarLocs
()) { dbgs() << "Add to OutLocs in MBB #" << CurMBB
->getNumber() << ": "; VarLocIDs[LocIndex::fromRawInteger
(ID)].dump(TRI); }; } } while (false)
1365 VarLocIDs[LocIndex::fromRawInteger(ID)].dump(TRI);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { for (uint64_t ID : OpenRanges.getVarLocs
()) { dbgs() << "Add to OutLocs in MBB #" << CurMBB
->getNumber() << ": "; VarLocIDs[LocIndex::fromRawInteger
(ID)].dump(TRI); }; } } while (false)
1366 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { for (uint64_t ID : OpenRanges.getVarLocs
()) { dbgs() << "Add to OutLocs in MBB #" << CurMBB
->getNumber() << ": "; VarLocIDs[LocIndex::fromRawInteger
(ID)].dump(TRI); }; } } while (false)
;
1367 VarLocSet &VLS = getVarLocsInMBB(CurMBB, OutLocs);
1368 Changed = VLS != OpenRanges.getVarLocs();
1369 // New OutLocs set may be different due to spill, restore or register
1370 // copy instruction processing.
1371 if (Changed)
1372 VLS = OpenRanges.getVarLocs();
1373 OpenRanges.clear();
1374 return Changed;
1375}
1376
1377/// Accumulate a mapping between each DILocalVariable fragment and other
1378/// fragments of that DILocalVariable which overlap. This reduces work during
1379/// the data-flow stage from "Find any overlapping fragments" to "Check if the
1380/// known-to-overlap fragments are present".
1381/// \param MI A previously unprocessed DEBUG_VALUE instruction to analyze for
1382/// fragment usage.
1383/// \param SeenFragments Map from DILocalVariable to all fragments of that
1384/// Variable which are known to exist.
1385/// \param OverlappingFragments The overlap map being constructed, from one
1386/// Var/Fragment pair to a vector of fragments known to overlap.
1387void LiveDebugValues::accumulateFragmentMap(MachineInstr &MI,
1388 VarToFragments &SeenFragments,
1389 OverlapMap &OverlappingFragments) {
1390 DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(),
1391 MI.getDebugLoc()->getInlinedAt());
1392 FragmentInfo ThisFragment = MIVar.getFragmentOrDefault();
1393
1394 // If this is the first sighting of this variable, then we are guaranteed
1395 // there are currently no overlapping fragments either. Initialize the set
1396 // of seen fragments, record no overlaps for the current one, and return.
1397 auto SeenIt = SeenFragments.find(MIVar.getVariable());
1398 if (SeenIt == SeenFragments.end()) {
1399 SmallSet<FragmentInfo, 4> OneFragment;
1400 OneFragment.insert(ThisFragment);
1401 SeenFragments.insert({MIVar.getVariable(), OneFragment});
1402
1403 OverlappingFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
1404 return;
1405 }
1406
1407 // If this particular Variable/Fragment pair already exists in the overlap
1408 // map, it has already been accounted for.
1409 auto IsInOLapMap =
1410 OverlappingFragments.insert({{MIVar.getVariable(), ThisFragment}, {}});
1411 if (!IsInOLapMap.second)
1412 return;
1413
1414 auto &ThisFragmentsOverlaps = IsInOLapMap.first->second;
1415 auto &AllSeenFragments = SeenIt->second;
1416
1417 // Otherwise, examine all other seen fragments for this variable, with "this"
1418 // fragment being a previously unseen fragment. Record any pair of
1419 // overlapping fragments.
1420 for (auto &ASeenFragment : AllSeenFragments) {
1421 // Does this previously seen fragment overlap?
1422 if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) {
1423 // Yes: Mark the current fragment as being overlapped.
1424 ThisFragmentsOverlaps.push_back(ASeenFragment);
1425 // Mark the previously seen fragment as being overlapped by the current
1426 // one.
1427 auto ASeenFragmentsOverlaps =
1428 OverlappingFragments.find({MIVar.getVariable(), ASeenFragment});
1429 assert(ASeenFragmentsOverlaps != OverlappingFragments.end() &&((ASeenFragmentsOverlaps != OverlappingFragments.end() &&
"Previously seen var fragment has no vector of overlaps") ? static_cast
<void> (0) : __assert_fail ("ASeenFragmentsOverlaps != OverlappingFragments.end() && \"Previously seen var fragment has no vector of overlaps\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 1430, __PRETTY_FUNCTION__))
1430 "Previously seen var fragment has no vector of overlaps")((ASeenFragmentsOverlaps != OverlappingFragments.end() &&
"Previously seen var fragment has no vector of overlaps") ? static_cast
<void> (0) : __assert_fail ("ASeenFragmentsOverlaps != OverlappingFragments.end() && \"Previously seen var fragment has no vector of overlaps\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 1430, __PRETTY_FUNCTION__))
;
1431 ASeenFragmentsOverlaps->second.push_back(ThisFragment);
1432 }
1433 }
1434
1435 AllSeenFragments.insert(ThisFragment);
1436}
1437
1438/// This routine creates OpenRanges.
1439void LiveDebugValues::process(MachineInstr &MI, OpenRangesSet &OpenRanges,
1440 VarLocMap &VarLocIDs, TransferMap &Transfers) {
1441 transferDebugValue(MI, OpenRanges, VarLocIDs);
1442 transferRegisterDef(MI, OpenRanges, VarLocIDs, Transfers);
1443 transferRegisterCopy(MI, OpenRanges, VarLocIDs, Transfers);
1444 transferSpillOrRestoreInst(MI, OpenRanges, VarLocIDs, Transfers);
1445}
1446
1447/// This routine joins the analysis results of all incoming edges in @MBB by
1448/// inserting a new DBG_VALUE instruction at the start of the @MBB - if the same
1449/// source variable in all the predecessors of @MBB reside in the same location.
1450bool LiveDebugValues::join(
1451 MachineBasicBlock &MBB, VarLocInMBB &OutLocs, VarLocInMBB &InLocs,
1452 const VarLocMap &VarLocIDs,
1453 SmallPtrSet<const MachineBasicBlock *, 16> &Visited,
1454 SmallPtrSetImpl<const MachineBasicBlock *> &ArtificialBlocks,
1455 VarLocInMBB &PendingInLocs) {
1456 LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { dbgs() << "join MBB: " << MBB
.getNumber() << "\n"; } } while (false)
;
1457 bool Changed = false;
1458
1459 VarLocSet InLocsT(Alloc); // Temporary incoming locations.
1460
1461 // For all predecessors of this MBB, find the set of VarLocs that
1462 // can be joined.
1463 int NumVisited = 0;
1464 for (auto p : MBB.predecessors()) {
1465 // Ignore backedges if we have not visited the predecessor yet. As the
1466 // predecessor hasn't yet had locations propagated into it, most locations
1467 // will not yet be valid, so treat them as all being uninitialized and
1468 // potentially valid. If a location guessed to be correct here is
1469 // invalidated later, we will remove it when we revisit this block.
1470 if (!Visited.count(p)) {
1471 LLVM_DEBUG(dbgs() << " ignoring unvisited pred MBB: " << p->getNumber()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { dbgs() << " ignoring unvisited pred MBB: "
<< p->getNumber() << "\n"; } } while (false)
1472 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { dbgs() << " ignoring unvisited pred MBB: "
<< p->getNumber() << "\n"; } } while (false)
;
1473 continue;
1474 }
1475 auto OL = OutLocs.find(p);
1476 // Join is null in case of empty OutLocs from any of the pred.
1477 if (OL == OutLocs.end())
1478 return false;
1479
1480 // Just copy over the Out locs to incoming locs for the first visited
1481 // predecessor, and for all other predecessors join the Out locs.
1482 if (!NumVisited)
1483 InLocsT = OL->second;
1484 else
1485 InLocsT &= OL->second;
1486
1487 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { if (!InLocsT.empty()) { for (uint64_t
ID : InLocsT) dbgs() << " gathered candidate incoming var: "
<< VarLocIDs[LocIndex::fromRawInteger(ID)] .Var.getVariable
() ->getName() << "\n"; } }; } } while (false)
1488 if (!InLocsT.empty()) {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { if (!InLocsT.empty()) { for (uint64_t
ID : InLocsT) dbgs() << " gathered candidate incoming var: "
<< VarLocIDs[LocIndex::fromRawInteger(ID)] .Var.getVariable
() ->getName() << "\n"; } }; } } while (false)
1489 for (uint64_t ID : InLocsT)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { if (!InLocsT.empty()) { for (uint64_t
ID : InLocsT) dbgs() << " gathered candidate incoming var: "
<< VarLocIDs[LocIndex::fromRawInteger(ID)] .Var.getVariable
() ->getName() << "\n"; } }; } } while (false)
1490 dbgs() << " gathered candidate incoming var: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { if (!InLocsT.empty()) { for (uint64_t
ID : InLocsT) dbgs() << " gathered candidate incoming var: "
<< VarLocIDs[LocIndex::fromRawInteger(ID)] .Var.getVariable
() ->getName() << "\n"; } }; } } while (false)
1491 << VarLocIDs[LocIndex::fromRawInteger(ID)]do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { if (!InLocsT.empty()) { for (uint64_t
ID : InLocsT) dbgs() << " gathered candidate incoming var: "
<< VarLocIDs[LocIndex::fromRawInteger(ID)] .Var.getVariable
() ->getName() << "\n"; } }; } } while (false)
1492 .Var.getVariable()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { if (!InLocsT.empty()) { for (uint64_t
ID : InLocsT) dbgs() << " gathered candidate incoming var: "
<< VarLocIDs[LocIndex::fromRawInteger(ID)] .Var.getVariable
() ->getName() << "\n"; } }; } } while (false)
1493 ->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { if (!InLocsT.empty()) { for (uint64_t
ID : InLocsT) dbgs() << " gathered candidate incoming var: "
<< VarLocIDs[LocIndex::fromRawInteger(ID)] .Var.getVariable
() ->getName() << "\n"; } }; } } while (false)
1494 << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { if (!InLocsT.empty()) { for (uint64_t
ID : InLocsT) dbgs() << " gathered candidate incoming var: "
<< VarLocIDs[LocIndex::fromRawInteger(ID)] .Var.getVariable
() ->getName() << "\n"; } }; } } while (false)
1495 }do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { if (!InLocsT.empty()) { for (uint64_t
ID : InLocsT) dbgs() << " gathered candidate incoming var: "
<< VarLocIDs[LocIndex::fromRawInteger(ID)] .Var.getVariable
() ->getName() << "\n"; } }; } } while (false)
1496 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { if (!InLocsT.empty()) { for (uint64_t
ID : InLocsT) dbgs() << " gathered candidate incoming var: "
<< VarLocIDs[LocIndex::fromRawInteger(ID)] .Var.getVariable
() ->getName() << "\n"; } }; } } while (false)
;
1497
1498 NumVisited++;
1499 }
1500
1501 // Filter out DBG_VALUES that are out of scope.
1502 VarLocSet KillSet(Alloc);
1503 bool IsArtificial = ArtificialBlocks.count(&MBB);
1504 if (!IsArtificial) {
1505 for (uint64_t ID : InLocsT) {
1506 LocIndex Idx = LocIndex::fromRawInteger(ID);
1507 if (!VarLocIDs[Idx].dominates(MBB)) {
1508 KillSet.set(ID);
1509 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { auto Name = VarLocIDs[Idx].Var.getVariable
()->getName(); dbgs() << " killing " << Name <<
", it doesn't dominate MBB\n"; }; } } while (false)
1510 auto Name = VarLocIDs[Idx].Var.getVariable()->getName();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { auto Name = VarLocIDs[Idx].Var.getVariable
()->getName(); dbgs() << " killing " << Name <<
", it doesn't dominate MBB\n"; }; } } while (false)
1511 dbgs() << " killing " << Name << ", it doesn't dominate MBB\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { auto Name = VarLocIDs[Idx].Var.getVariable
()->getName(); dbgs() << " killing " << Name <<
", it doesn't dominate MBB\n"; }; } } while (false)
1512 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { { auto Name = VarLocIDs[Idx].Var.getVariable
()->getName(); dbgs() << " killing " << Name <<
", it doesn't dominate MBB\n"; }; } } while (false)
;
1513 }
1514 }
1515 }
1516 InLocsT.intersectWithComplement(KillSet);
1517
1518 // As we are processing blocks in reverse post-order we
1519 // should have processed at least one predecessor, unless it
1520 // is the entry block which has no predecessor.
1521 assert((NumVisited || MBB.pred_empty()) &&(((NumVisited || MBB.pred_empty()) && "Should have processed at least one predecessor"
) ? static_cast<void> (0) : __assert_fail ("(NumVisited || MBB.pred_empty()) && \"Should have processed at least one predecessor\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 1522, __PRETTY_FUNCTION__))
1522 "Should have processed at least one predecessor")(((NumVisited || MBB.pred_empty()) && "Should have processed at least one predecessor"
) ? static_cast<void> (0) : __assert_fail ("(NumVisited || MBB.pred_empty()) && \"Should have processed at least one predecessor\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 1522, __PRETTY_FUNCTION__))
;
1523
1524 VarLocSet &ILS = getVarLocsInMBB(&MBB, InLocs);
1525 VarLocSet &Pending = getVarLocsInMBB(&MBB, PendingInLocs);
1526
1527 // New locations will have DBG_VALUE insts inserted at the start of the
1528 // block, after location propagation has finished. Record the insertions
1529 // that we need to perform in the Pending set.
1530 VarLocSet Diff = InLocsT;
1531 Diff.intersectWithComplement(ILS);
1532 Pending.set(Diff);
1533 ILS.set(Diff);
1534 NumInserted += Diff.count();
1535 Changed |= !Diff.empty();
1536
1537 // We may have lost locations by learning about a predecessor that either
1538 // loses or moves a variable. Find any locations in ILS that are not in the
1539 // new in-locations, and delete those.
1540 VarLocSet Removed = ILS;
1541 Removed.intersectWithComplement(InLocsT);
1542 Pending.intersectWithComplement(Removed);
1543 ILS.intersectWithComplement(Removed);
1544 NumRemoved += Removed.count();
1545 Changed |= !Removed.empty();
1546
1547 return Changed;
1548}
1549
1550void LiveDebugValues::flushPendingLocs(VarLocInMBB &PendingInLocs,
1551 VarLocMap &VarLocIDs) {
1552 // PendingInLocs records all locations propagated into blocks, which have
1553 // not had DBG_VALUE insts created. Go through and create those insts now.
1554 for (auto &Iter : PendingInLocs) {
1555 // Map is keyed on a constant pointer, unwrap it so we can insert insts.
1556 auto &MBB = const_cast<MachineBasicBlock &>(*Iter.first);
1557 VarLocSet &Pending = Iter.second;
1558
1559 for (uint64_t ID : Pending) {
1560 // The ID location is live-in to MBB -- work out what kind of machine
1561 // location it is and create a DBG_VALUE.
1562 const VarLoc &DiffIt = VarLocIDs[LocIndex::fromRawInteger(ID)];
1563 if (DiffIt.isEntryBackupLoc())
1564 continue;
1565 MachineInstr *MI = DiffIt.BuildDbgValue(*MBB.getParent());
1566 MBB.insert(MBB.instr_begin(), MI);
1567
1568 (void)MI;
1569 LLVM_DEBUG(dbgs() << "Inserted: "; MI->dump();)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { dbgs() << "Inserted: "; MI->dump
();; } } while (false)
;
1570 }
1571 }
1572}
1573
1574bool LiveDebugValues::isEntryValueCandidate(
1575 const MachineInstr &MI, const DefinedRegsSet &DefinedRegs) const {
1576 assert(MI.isDebugValue() && "This must be DBG_VALUE.")((MI.isDebugValue() && "This must be DBG_VALUE.") ? static_cast
<void> (0) : __assert_fail ("MI.isDebugValue() && \"This must be DBG_VALUE.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 1576, __PRETTY_FUNCTION__))
;
1577
1578 // TODO: Add support for local variables that are expressed in terms of
1579 // parameters entry values.
1580 // TODO: Add support for modified arguments that can be expressed
1581 // by using its entry value.
1582 auto *DIVar = MI.getDebugVariable();
1583 if (!DIVar->isParameter())
1584 return false;
1585
1586 // Do not consider parameters that belong to an inlined function.
1587 if (MI.getDebugLoc()->getInlinedAt())
1588 return false;
1589
1590 // Do not consider indirect debug values (TODO: explain why).
1591 if (MI.isIndirectDebugValue())
1592 return false;
1593
1594 // Only consider parameters that are described using registers. Parameters
1595 // that are passed on the stack are not yet supported, so ignore debug
1596 // values that are described by the frame or stack pointer.
1597 if (!isRegOtherThanSPAndFP(MI.getOperand(0), MI, TRI))
1598 return false;
1599
1600 // If a parameter's value has been propagated from the caller, then the
1601 // parameter's DBG_VALUE may be described using a register defined by some
1602 // instruction in the entry block, in which case we shouldn't create an
1603 // entry value.
1604 if (DefinedRegs.count(MI.getOperand(0).getReg()))
1605 return false;
1606
1607 // TODO: Add support for parameters that have a pre-existing debug expressions
1608 // (e.g. fragments, or indirect parameters using DW_OP_deref).
1609 if (MI.getDebugExpression()->getNumElements() > 0)
1610 return false;
1611
1612 return true;
1613}
1614
1615/// Collect all register defines (including aliases) for the given instruction.
1616static void collectRegDefs(const MachineInstr &MI, DefinedRegsSet &Regs,
1617 const TargetRegisterInfo *TRI) {
1618 for (const MachineOperand &MO : MI.operands())
1619 if (MO.isReg() && MO.isDef() && MO.getReg())
1620 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
1621 Regs.insert(*AI);
1622}
1623
1624/// This routine records the entry values of function parameters. The values
1625/// could be used as backup values. If we loose the track of some unmodified
1626/// parameters, the backup values will be used as a primary locations.
1627void LiveDebugValues::recordEntryValue(const MachineInstr &MI,
1628 const DefinedRegsSet &DefinedRegs,
1629 OpenRangesSet &OpenRanges,
1630 VarLocMap &VarLocIDs) {
1631 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
1632 auto &TM = TPC->getTM<TargetMachine>();
1633 if (!TM.Options.EnableDebugEntryValues)
1634 return;
1635 }
1636
1637 DebugVariable V(MI.getDebugVariable(), MI.getDebugExpression(),
1638 MI.getDebugLoc()->getInlinedAt());
1639
1640 if (!isEntryValueCandidate(MI, DefinedRegs) ||
1641 OpenRanges.getEntryValueBackup(V))
1642 return;
1643
1644 LLVM_DEBUG(dbgs() << "Creating the backup entry location: "; MI.dump();)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { dbgs() << "Creating the backup entry location: "
; MI.dump();; } } while (false)
;
1645
1646 // Create the entry value and use it as a backup location until it is
1647 // valid. It is valid until a parameter is not changed.
1648 DIExpression *NewExpr =
1649 DIExpression::prepend(MI.getDebugExpression(), DIExpression::EntryValue);
1650 VarLoc EntryValLocAsBackup = VarLoc::CreateEntryBackupLoc(MI, LS, NewExpr);
1651 LocIndex EntryValLocID = VarLocIDs.insert(EntryValLocAsBackup);
1652 OpenRanges.insert(EntryValLocID, EntryValLocAsBackup);
1653}
1654
1655/// Calculate the liveness information for the given machine function and
1656/// extend ranges across basic blocks.
1657bool LiveDebugValues::ExtendRanges(MachineFunction &MF) {
1658 LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { dbgs() << "\nDebug Range Extension\n"
; } } while (false)
;
1659
1660 bool Changed = false;
1661 bool OLChanged = false;
1662 bool MBBJoined = false;
1663
1664 VarLocMap VarLocIDs; // Map VarLoc<>unique ID for use in bitvectors.
1665 OverlapMap OverlapFragments; // Map of overlapping variable fragments.
1666 OpenRangesSet OpenRanges(Alloc, OverlapFragments);
1667 // Ranges that are open until end of bb.
1668 VarLocInMBB OutLocs; // Ranges that exist beyond bb.
1669 VarLocInMBB InLocs; // Ranges that are incoming after joining.
1670 TransferMap Transfers; // DBG_VALUEs associated with transfers (such as
1671 // spills, copies and restores).
1672 VarLocInMBB PendingInLocs; // Ranges that are incoming after joining, but
1673 // that we have deferred creating DBG_VALUE insts
1674 // for immediately.
1675
1676 VarToFragments SeenFragments;
1677
1678 // Blocks which are artificial, i.e. blocks which exclusively contain
1679 // instructions without locations, or with line 0 locations.
1680 SmallPtrSet<const MachineBasicBlock *, 16> ArtificialBlocks;
1681
1682 DenseMap<unsigned int, MachineBasicBlock *> OrderToBB;
1683 DenseMap<MachineBasicBlock *, unsigned int> BBToOrder;
1684 std::priority_queue<unsigned int, std::vector<unsigned int>,
1685 std::greater<unsigned int>>
1686 Worklist;
1687 std::priority_queue<unsigned int, std::vector<unsigned int>,
1688 std::greater<unsigned int>>
1689 Pending;
1690
1691 // Set of register defines that are seen when traversing the entry block
1692 // looking for debug entry value candidates.
1693 DefinedRegsSet DefinedRegs;
1694
1695 // Only in the case of entry MBB collect DBG_VALUEs representing
1696 // function parameters in order to generate debug entry values for them.
1697 MachineBasicBlock &First_MBB = *(MF.begin());
1698 for (auto &MI : First_MBB) {
1699 collectRegDefs(MI, DefinedRegs, TRI);
1700 if (MI.isDebugValue())
1701 recordEntryValue(MI, DefinedRegs, OpenRanges, VarLocIDs);
1702 }
1703
1704 // Initialize per-block structures and scan for fragment overlaps.
1705 for (auto &MBB : MF) {
1706 PendingInLocs.try_emplace(&MBB, Alloc);
1707
1708 for (auto &MI : MBB) {
1709 if (MI.isDebugValue())
1710 accumulateFragmentMap(MI, SeenFragments, OverlapFragments);
1711 }
1712 }
1713
1714 auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool {
1715 if (const DebugLoc &DL = MI.getDebugLoc())
1716 return DL.getLine() != 0;
1717 return false;
1718 };
1719 for (auto &MBB : MF)
1720 if (none_of(MBB.instrs(), hasNonArtificialLocation))
1721 ArtificialBlocks.insert(&MBB);
1722
1723 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { printVarLocInMBB(MF, OutLocs, VarLocIDs
, "OutLocs after initialization", dbgs()); } } while (false)
1724 "OutLocs after initialization", dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { printVarLocInMBB(MF, OutLocs, VarLocIDs
, "OutLocs after initialization", dbgs()); } } while (false)
;
1725
1726 ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
1727 unsigned int RPONumber = 0;
1728 for (auto RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) {
1729 OrderToBB[RPONumber] = *RI;
1730 BBToOrder[*RI] = RPONumber;
1731 Worklist.push(RPONumber);
1732 ++RPONumber;
1733 }
1734 // This is a standard "union of predecessor outs" dataflow problem.
1735 // To solve it, we perform join() and process() using the two worklist method
1736 // until the ranges converge.
1737 // Ranges have converged when both worklists are empty.
1738 SmallPtrSet<const MachineBasicBlock *, 16> Visited;
1739 while (!Worklist.empty() || !Pending.empty()) {
1740 // We track what is on the pending worklist to avoid inserting the same
1741 // thing twice. We could avoid this with a custom priority queue, but this
1742 // is probably not worth it.
1743 SmallPtrSet<MachineBasicBlock *, 16> OnPending;
1744 LLVM_DEBUG(dbgs() << "Processing Worklist\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { dbgs() << "Processing Worklist\n"
; } } while (false)
;
1745 while (!Worklist.empty()) {
1746 MachineBasicBlock *MBB = OrderToBB[Worklist.top()];
1747 Worklist.pop();
1748 MBBJoined = join(*MBB, OutLocs, InLocs, VarLocIDs, Visited,
1749 ArtificialBlocks, PendingInLocs);
1750 MBBJoined |= Visited.insert(MBB).second;
1751 if (MBBJoined) {
1752 MBBJoined = false;
Value stored to 'MBBJoined' is never read
1753 Changed = true;
1754 // Now that we have started to extend ranges across BBs we need to
1755 // examine spill, copy and restore instructions to see whether they
1756 // operate with registers that correspond to user variables.
1757 // First load any pending inlocs.
1758 OpenRanges.insertFromLocSet(getVarLocsInMBB(MBB, PendingInLocs),
1759 VarLocIDs);
1760 for (auto &MI : *MBB)
1761 process(MI, OpenRanges, VarLocIDs, Transfers);
1762 OLChanged |= transferTerminator(MBB, OpenRanges, OutLocs, VarLocIDs);
1763
1764 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs,do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { printVarLocInMBB(MF, OutLocs, VarLocIDs
, "OutLocs after propagating", dbgs()); } } while (false)
1765 "OutLocs after propagating", dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { printVarLocInMBB(MF, OutLocs, VarLocIDs
, "OutLocs after propagating", dbgs()); } } while (false)
;
1766 LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs,do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { printVarLocInMBB(MF, InLocs, VarLocIDs
, "InLocs after propagating", dbgs()); } } while (false)
1767 "InLocs after propagating", dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { printVarLocInMBB(MF, InLocs, VarLocIDs
, "InLocs after propagating", dbgs()); } } while (false)
;
1768
1769 if (OLChanged) {
1770 OLChanged = false;
1771 for (auto s : MBB->successors())
1772 if (OnPending.insert(s).second) {
1773 Pending.push(BBToOrder[s]);
1774 }
1775 }
1776 }
1777 }
1778 Worklist.swap(Pending);
1779 // At this point, pending must be empty, since it was just the empty
1780 // worklist
1781 assert(Pending.empty() && "Pending should be empty")((Pending.empty() && "Pending should be empty") ? static_cast
<void> (0) : __assert_fail ("Pending.empty() && \"Pending should be empty\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 1781, __PRETTY_FUNCTION__))
;
1782 }
1783
1784 // Add any DBG_VALUE instructions created by location transfers.
1785 for (auto &TR : Transfers) {
1786 assert(!TR.TransferInst->isTerminator() &&((!TR.TransferInst->isTerminator() && "Cannot insert DBG_VALUE after terminator"
) ? static_cast<void> (0) : __assert_fail ("!TR.TransferInst->isTerminator() && \"Cannot insert DBG_VALUE after terminator\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 1787, __PRETTY_FUNCTION__))
1787 "Cannot insert DBG_VALUE after terminator")((!TR.TransferInst->isTerminator() && "Cannot insert DBG_VALUE after terminator"
) ? static_cast<void> (0) : __assert_fail ("!TR.TransferInst->isTerminator() && \"Cannot insert DBG_VALUE after terminator\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/CodeGen/LiveDebugValues.cpp"
, 1787, __PRETTY_FUNCTION__))
;
1788 MachineBasicBlock *MBB = TR.TransferInst->getParent();
1789 const VarLoc &VL = VarLocIDs[TR.LocationID];
1790 MachineInstr *MI = VL.BuildDbgValue(MF);
1791 MBB->insertAfterBundle(TR.TransferInst->getIterator(), MI);
1792 }
1793 Transfers.clear();
1794
1795 // Deferred inlocs will not have had any DBG_VALUE insts created; do
1796 // that now.
1797 flushPendingLocs(PendingInLocs, VarLocIDs);
1798
1799 LLVM_DEBUG(printVarLocInMBB(MF, OutLocs, VarLocIDs, "Final OutLocs", dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { printVarLocInMBB(MF, OutLocs, VarLocIDs
, "Final OutLocs", dbgs()); } } while (false)
;
1800 LLVM_DEBUG(printVarLocInMBB(MF, InLocs, VarLocIDs, "Final InLocs", dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("livedebugvalues")) { printVarLocInMBB(MF, InLocs, VarLocIDs
, "Final InLocs", dbgs()); } } while (false)
;
1801 return Changed;
1802}
1803
1804bool LiveDebugValues::runOnMachineFunction(MachineFunction &MF) {
1805 if (!MF.getFunction().getSubprogram())
1806 // LiveDebugValues will already have removed all DBG_VALUEs.
1807 return false;
1808
1809 // Skip functions from NoDebug compilation units.
1810 if (MF.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
1811 DICompileUnit::NoDebug)
1812 return false;
1813
1814 TRI = MF.getSubtarget().getRegisterInfo();
1815 TII = MF.getSubtarget().getInstrInfo();
1816 TFI = MF.getSubtarget().getFrameLowering();
1817 TFI->getCalleeSaves(MF, CalleeSavedRegs);
1818 LS.initialize(MF);
1819
1820 bool Changed = ExtendRanges(MF);
1821 return Changed;
1822}