Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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