LLVM 23.0.0git
DWARFExpressionPrinter.cpp
Go to the documentation of this file.
1//===-- DWARFExpression.cpp -----------------------------------------------===//
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
14#include "llvm/Support/Endian.h"
15#include "llvm/Support/Format.h"
17#include <cassert>
18#include <cstdint>
19
20using namespace llvm;
21using namespace dwarf;
22
23namespace llvm {
24
27
28/// Some backends (e.g. NVPTX) encode virtual register names as the DWARF
29/// register number: the ASCII bytes of the name are concatenated into a
30/// uint64_t (see NVPTXRegisterInfo::encodeRegisterForDwarf). When the object
31/// file is not the target backend, MCRegisterInfo cannot map these numbers, so
32/// recover the string for dumping.
33/// Returns true if the register name was decoded successfully, false otherwise.
34static bool decodeVirtualRegisterName(uint64_t DwarfRegNum,
35 SmallString<8> &Out) {
36 if (DwarfRegNum == 0)
37 return false;
38
39 uint64_t DwarfRegNumBE =
41 const char *Data = reinterpret_cast<const char *>(&DwarfRegNumBE);
42 const char *Begin = std::find_if(Data, Data + sizeof(DwarfRegNumBE),
43 [](char c) { return c != '\0'; });
44 SmallString<8> Tmp(Begin, Data + sizeof(DwarfRegNumBE));
45
46 if (Tmp.size() < 2)
47 return false;
48
49 if (!llvm::isAlnum(Tmp[0]) && Tmp[0] != '%')
50 return false;
51
52 for (size_t I = 1; I < Tmp.size(); ++I)
53 if (!llvm::isAlnum(Tmp[I]))
54 return false;
55
56 Out = Tmp;
57 return true;
58}
59
60/// Resolves a DWARF register number to a display name: first via \p
61/// GetNameForDWARFReg (MC register names), otherwise try decoding
62/// ASCII-encoded virtual register names (NVPTX-specific).
63/// Returns empty if neither applies.
64static std::string resolveRegName(
65 uint64_t DwarfRegNum, bool IsEH,
66 const std::function<StringRef(uint64_t, bool)> &GetNameForDWARFReg) {
67 if (GetNameForDWARFReg) {
68 StringRef R = GetNameForDWARFReg(DwarfRegNum, IsEH);
69 if (!R.empty())
70 return R.str();
71 }
72 SmallString<8> Decoded;
73 if (decodeVirtualRegisterName(DwarfRegNum, Decoded))
74 return Decoded.str().str();
75 return "";
76}
77
79 DIDumpOptions DumpOpts,
80 ArrayRef<uint64_t> Operands,
81 unsigned Operand) {
82 assert(Operand < Operands.size() && "operand out of bounds");
83 if (!U) {
84 OS << formatv(" <base_type ref: {0:x}>", Operands[Operand]);
85 return;
86 }
87 auto Die = U->getDIEForOffset(U->getOffset() + Operands[Operand]);
88 if (Die && Die.getTag() == dwarf::DW_TAG_base_type) {
89 OS << " (";
90 if (DumpOpts.Verbose)
91 OS << formatv("{0:x8} -> ", Operands[Operand]);
92 OS << formatv("{0:x8})", U->getOffset() + Operands[Operand]);
93 if (auto Name = dwarf::toString(Die.find(dwarf::DW_AT_name)))
94 OS << " \"" << *Name << "\"";
95 } else {
96 OS << formatv(" <invalid base_type ref: {0:x}>", Operands[Operand]);
97 }
98}
99
101 DIDumpOptions DumpOpts, const DWARFExpression *Expr,
102 DWARFUnit *U) {
103 if (Op->isError()) {
104 if (!DumpOpts.PrintRegisterOnly)
105 OS << "<decoding error>";
106 return false;
107 }
108
109 std::optional<unsigned> SubOpcode = Op->getSubCode();
110
111 // In "register-only" mode, still show simple constant-valued locations.
112 // This lets clients print annotations like "i = 0" when the location is
113 // a constant (e.g. DW_OP_constu/consts ... DW_OP_stack_value).
114 // We continue to suppress all other non-register ops in this mode.
115 if (DumpOpts.PrintRegisterOnly) {
116 // First, try pretty-printing registers (existing behavior below also does
117 // this, but we need to short-circuit here to avoid printing opcode names).
118 if ((Op->getCode() >= DW_OP_breg0 && Op->getCode() <= DW_OP_breg31) ||
119 (Op->getCode() >= DW_OP_reg0 && Op->getCode() <= DW_OP_reg31) ||
120 Op->getCode() == DW_OP_bregx || Op->getCode() == DW_OP_regx ||
121 Op->getCode() == DW_OP_regval_type ||
122 SubOpcode == DW_OP_LLVM_call_frame_entry_reg ||
123 SubOpcode == DW_OP_LLVM_aspace_bregx) {
124 if (prettyPrintRegisterOp(U, OS, DumpOpts, Op->getCode(),
125 Op->getRawOperands()))
126 return true;
127 // If we couldn't pretty-print, fall through and suppress.
128 }
129
130 // Show constants (decimal), suppress everything else.
131 if (Op->getCode() == DW_OP_constu) {
132 OS << (uint64_t)Op->getRawOperand(0);
133 return true;
134 }
135 if (Op->getCode() == DW_OP_consts) {
136 OS << (int64_t)Op->getRawOperand(0);
137 return true;
138 }
139 if (Op->getCode() >= DW_OP_lit0 && Op->getCode() <= DW_OP_lit31) {
140 OS << (unsigned)(Op->getCode() - DW_OP_lit0);
141 return true;
142 }
143 if (Op->getCode() == DW_OP_stack_value)
144 return true; // metadata; don't print a token
145
146 return true; // suppress other opcodes silently in register-only mode
147 }
148
149 if (!DumpOpts.PrintRegisterOnly) {
150 StringRef Name = OperationEncodingString(Op->getCode());
151 assert(!Name.empty() && "DW_OP has no name!");
152 OS << Name;
153
154 if (SubOpcode) {
155 StringRef SubName = SubOperationEncodingString(Op->getCode(), *SubOpcode);
156 assert(!SubName.empty() && "DW_OP SubOp has no name!");
157 OS << ' ' << SubName;
158 }
159 }
160
161 if ((Op->getCode() >= DW_OP_breg0 && Op->getCode() <= DW_OP_breg31) ||
162 (Op->getCode() >= DW_OP_reg0 && Op->getCode() <= DW_OP_reg31) ||
163 Op->getCode() == DW_OP_bregx || Op->getCode() == DW_OP_regx ||
164 Op->getCode() == DW_OP_regval_type ||
165 SubOpcode == DW_OP_LLVM_call_frame_entry_reg ||
166 SubOpcode == DW_OP_LLVM_aspace_bregx)
167 if (prettyPrintRegisterOp(U, OS, DumpOpts, Op->getCode(),
168 Op->getRawOperands()))
169 return true;
170
171 if (!DumpOpts.PrintRegisterOnly) {
172 for (unsigned Operand = 0; Operand < Op->getDescription().Op.size();
173 ++Operand) {
174 unsigned Size = Op->getDescription().Op[Operand];
176
178 assert(Operand == 0 && "DW_OP SubOp must be the first operand");
179 assert(SubOpcode && "DW_OP SubOp description is inconsistent");
181 // For DW_OP_convert the operand may be 0 to indicate that conversion to
182 // the generic type should be done. The same holds for
183 // DW_OP_reinterpret, which is currently not supported.
184 if (Op->getCode() == DW_OP_convert && Op->getRawOperand(Operand) == 0)
185 OS << " 0x0";
186 else
187 prettyPrintBaseTypeRef(U, OS, DumpOpts, Op->getRawOperands(),
188 Operand);
190 assert(Operand == 1);
191 switch (Op->getRawOperand(0)) {
192 case 0:
193 case 1:
194 case 2:
195 case 3: // global as uint32
196 case 4:
197 OS << formatv(" {0:x}", Op->getRawOperand(Operand));
198 break;
199 default:
200 assert(false);
201 }
203 uint64_t Offset = Op->getRawOperand(Operand);
204 for (unsigned i = 0; i < Op->getRawOperand(Operand - 1); ++i)
205 OS << formatv(" {0:x2}",
206 static_cast<uint8_t>(Expr->getData()[Offset++]));
207 } else {
208 if (Signed)
209 OS << formatv(" {0:+d}", (int64_t)Op->getRawOperand(Operand));
210 else if (Op->getCode() != DW_OP_entry_value &&
211 Op->getCode() != DW_OP_GNU_entry_value)
212 OS << formatv(" {0:x}", Op->getRawOperand(Operand));
213 }
214 }
215 }
216 return true;
217}
218
220 DIDumpOptions DumpOpts, DWARFUnit *U, bool IsEH) {
221 uint32_t EntryValExprSize = 0;
222 uint64_t EntryValStartOffset = 0;
223 if (E->getData().empty())
224 OS << "<empty>";
225
226 for (auto &Op : *E) {
227 DumpOpts.IsEH = IsEH;
228 if (!printOp(&Op, OS, DumpOpts, E, U) && !DumpOpts.PrintRegisterOnly) {
229 uint64_t FailOffset = Op.getEndOffset();
230 while (FailOffset < E->getData().size())
231 OS << formatv(" {0:x-2}",
232 static_cast<uint8_t>(E->getData()[FailOffset++]));
233 return;
234 }
235 if (!DumpOpts.PrintRegisterOnly) {
236 if (Op.getCode() == DW_OP_entry_value ||
237 Op.getCode() == DW_OP_GNU_entry_value) {
238 OS << "(";
239 EntryValExprSize = Op.getRawOperand(0);
240 EntryValStartOffset = Op.getEndOffset();
241 continue;
242 }
243
244 if (EntryValExprSize) {
245 EntryValExprSize -= Op.getEndOffset() - EntryValStartOffset;
246 if (EntryValExprSize == 0)
247 OS << ")";
248 }
249
250 if (Op.getEndOffset() < E->getData().size())
251 OS << ", ";
252 }
253 }
254}
255
256/// A user-facing string representation of a DWARF expression. This might be an
257/// Address expression, in which case it will be implicitly dereferenced, or a
258/// Value expression.
269
273 std::function<StringRef(uint64_t RegNum, bool IsEH)> GetNameForDWARFReg =
274 nullptr) {
276
277 auto UnknownOpcode = [](raw_ostream &OS, uint8_t Opcode,
278 std::optional<unsigned> SubOpcode) -> bool {
279 // If we hit an unknown operand, we don't know its effect on the stack,
280 // so bail out on the whole expression.
281 OS << "<unknown op " << dwarf::OperationEncodingString(Opcode) << " ("
282 << (int)Opcode;
283 if (SubOpcode)
284 OS << ") subop " << dwarf::SubOperationEncodingString(Opcode, *SubOpcode)
285 << " (" << *SubOpcode;
286 OS << ")>";
287 return false;
288 };
289
290 while (I != E) {
292 uint8_t Opcode = Op.getCode();
293 switch (Opcode) {
294 case dwarf::DW_OP_regx: {
295 // DW_OP_regx: A register, with the register num given as an operand.
296 // Printed as the plain register name.
297 const uint64_t DwarfRegNum = Op.getRawOperand(0);
298 std::string RegName =
299 resolveRegName(DwarfRegNum, false, GetNameForDWARFReg);
300 if (RegName.empty())
301 return false;
302 raw_svector_ostream S(Stack.emplace_back(PrintedExpr::Value).String);
303 S << RegName;
304 break;
305 }
306 case dwarf::DW_OP_bregx: {
307 const uint64_t DwarfRegNum = Op.getRawOperand(0);
308 const uint64_t Offset = Op.getRawOperand(1);
309 std::string RegName =
310 resolveRegName(DwarfRegNum, false, GetNameForDWARFReg);
311 if (RegName.empty())
312 return false;
313 raw_svector_ostream S(Stack.emplace_back().String);
314 S << RegName;
315 if (Offset)
316 S << formatv("{0:+d}", Offset);
317 break;
318 }
319 case dwarf::DW_OP_entry_value:
320 case dwarf::DW_OP_GNU_entry_value: {
321 // DW_OP_entry_value contains a sub-expression which must be rendered
322 // separately.
323 uint64_t SubExprLength = Op.getRawOperand(0);
324 DWARFExpression::iterator SubExprEnd = I.skipBytes(SubExprLength);
325 ++I;
326 raw_svector_ostream S(Stack.emplace_back().String);
327 S << "entry(";
328 printCompactDWARFExpr(S, I, SubExprEnd, GetNameForDWARFReg);
329 S << ")";
330 I = SubExprEnd;
331 continue;
332 }
333 case dwarf::DW_OP_stack_value: {
334 // The top stack entry should be treated as the actual value of tne
335 // variable, rather than the address of the variable in memory.
336 assert(!Stack.empty());
337 Stack.back().Kind = PrintedExpr::Value;
338 break;
339 }
340 case dwarf::DW_OP_nop: {
341 break;
342 }
343 case dwarf::DW_OP_LLVM_user: {
344 std::optional<unsigned> SubOpcode = Op.getSubCode();
345 if (SubOpcode == dwarf::DW_OP_LLVM_nop)
346 break;
347 return UnknownOpcode(OS, Opcode, SubOpcode);
348 }
349 default:
350 if (Opcode >= dwarf::DW_OP_reg0 && Opcode <= dwarf::DW_OP_reg31) {
351 // DW_OP_reg<N>: A register, with the register num implied by the
352 // opcode. Printed as the plain register name.
353 uint64_t DwarfRegNum = Opcode - dwarf::DW_OP_reg0;
354 auto RegName = GetNameForDWARFReg(DwarfRegNum, false);
355 if (RegName.empty())
356 return false;
357 raw_svector_ostream S(Stack.emplace_back(PrintedExpr::Value).String);
358 S << RegName;
359 } else if (Opcode >= dwarf::DW_OP_breg0 &&
360 Opcode <= dwarf::DW_OP_breg31) {
361 int DwarfRegNum = Opcode - dwarf::DW_OP_breg0;
362 int64_t Offset = Op.getRawOperand(0);
363 auto RegName = GetNameForDWARFReg(DwarfRegNum, false);
364 if (RegName.empty())
365 return false;
366 raw_svector_ostream S(Stack.emplace_back().String);
367 S << RegName;
368 if (Offset)
369 S << formatv("{0:+d}", Offset);
370 } else {
371 return UnknownOpcode(OS, Opcode, std::nullopt);
372 }
373 break;
374 }
375 ++I;
376 }
377
378 if (Stack.size() != 1) {
379 OS << "<stack of size " << Stack.size() << ", expected 1>";
380 return false;
381 }
382
383 if (Stack.front().Kind == PrintedExpr::Address)
384 OS << "[" << Stack.front().String << "]";
385 else
386 OS << Stack.front().String;
387
388 return true;
389}
390
392 const DWARFExpression *E, raw_ostream &OS,
393 std::function<StringRef(uint64_t RegNum, bool IsEH)> GetNameForDWARFReg) {
394 return printCompactDWARFExpr(OS, E->begin(), E->end(), GetNameForDWARFReg);
395}
396
398 DIDumpOptions DumpOpts, uint8_t Opcode,
399 ArrayRef<uint64_t> Operands) {
400 uint64_t DwarfRegNum;
401 unsigned OpNum = 0;
402
403 std::optional<unsigned> SubOpcode;
404 if (Opcode == DW_OP_LLVM_user)
405 SubOpcode = Operands[OpNum++];
406
407 const bool RegNumFromOperand =
408 Opcode == DW_OP_bregx || Opcode == DW_OP_regx ||
409 Opcode == DW_OP_regval_type || SubOpcode == DW_OP_LLVM_aspace_bregx ||
410 SubOpcode == DW_OP_LLVM_call_frame_entry_reg;
411
412 if (RegNumFromOperand)
413 DwarfRegNum = Operands[OpNum++];
414 else if (Opcode >= DW_OP_breg0 && Opcode < DW_OP_bregx)
415 DwarfRegNum = Opcode - DW_OP_breg0;
416 else
417 DwarfRegNum = Opcode - DW_OP_reg0;
418
419 std::string RegName =
420 resolveRegName(DwarfRegNum, DumpOpts.IsEH, DumpOpts.GetNameForDWARFReg);
421
422 if (!RegName.empty()) {
423 if ((Opcode >= DW_OP_breg0 && Opcode <= DW_OP_breg31) ||
424 Opcode == DW_OP_bregx || SubOpcode == DW_OP_LLVM_aspace_bregx)
425 OS << ' ' << RegName << formatv("{0:+d}", int64_t(Operands[OpNum]));
426 else
427 OS << ' ' << RegName;
428
429 if (Opcode == DW_OP_regval_type)
430 prettyPrintBaseTypeRef(U, OS, DumpOpts, Operands, 1);
431 return true;
432 }
433
434 return false;
435}
436
437} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define RegName(no)
#define I(x, y, z)
Definition MD5.cpp:57
This file defines the SmallString class.
This file contains some functions that are useful when dealing with strings.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
This class represents an Operation in the Expression.
@ SizeSubOpLEB
The operand is a ULEB128 encoded SubOpcode.
@ SizeBlock
Preceding operand contains block size.
An iterator to go through the expression operations.
StringRef getData() const
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
StringRef str() const
Explicit conversion to StringRef.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an SmallVector or SmallString.
LLVM_ABI StringRef SubOperationEncodingString(unsigned OpEncoding, unsigned SubOpEncoding)
Definition Dwarf.cpp:202
LLVM_ABI StringRef OperationEncodingString(unsigned Encoding)
Definition Dwarf.cpp:138
Calculates the starting offsets for various sections within the .debug_names section.
Definition Dwarf.h:35
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
value_type byte_swap(value_type value, endianness endian)
Definition Endian.h:44
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:558
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1668
static bool printOp(const DWARFExpression::Operation *Op, raw_ostream &OS, DIDumpOptions DumpOpts, const DWARFExpression *Expr, DWARFUnit *U)
LLVM_ABI void printDwarfExpression(const DWARFExpression *E, raw_ostream &OS, DIDumpOptions DumpOpts, DWARFUnit *U, bool IsEH=false)
Print a Dwarf expression/.
Op::Description Desc
static bool printCompactDWARFExpr(raw_ostream &OS, DWARFExpression::iterator I, const DWARFExpression::iterator E, std::function< StringRef(uint64_t RegNum, bool IsEH)> GetNameForDWARFReg=nullptr)
static void prettyPrintBaseTypeRef(DWARFUnit *U, raw_ostream &OS, DIDumpOptions DumpOpts, ArrayRef< uint64_t > Operands, unsigned Operand)
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
static bool decodeVirtualRegisterName(uint64_t DwarfRegNum, SmallString< 8 > &Out)
Some backends (e.g.
bool isAlnum(char C)
Checks whether character C is either a decimal digit or an uppercase or lowercase letter as classifie...
static std::string resolveRegName(uint64_t DwarfRegNum, bool IsEH, const std::function< StringRef(uint64_t, bool)> &GetNameForDWARFReg)
Resolves a DWARF register number to a display name: first via GetNameForDWARFReg (MC register names),...
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:221
DWARFExpression::Operation Op
LLVM_ABI bool prettyPrintRegisterOp(DWARFUnit *U, raw_ostream &OS, DIDumpOptions DumpOpts, uint8_t Opcode, ArrayRef< uint64_t > Operands)
Pretty print a register opcode and operands.
LLVM_ABI bool printDwarfExpressionCompact(const DWARFExpression *E, raw_ostream &OS, std::function< StringRef(uint64_t RegNum, bool IsEH)> GetNameForDWARFReg=nullptr)
Print the expression in a format intended to be compact and useful to a user, but not perfectly unamb...
Container for dump options that control which debug information will be dumped.
Definition DIContext.h:196
std::function< llvm::StringRef(uint64_t DwarfRegNum, bool IsEH)> GetNameForDWARFReg
Definition DIContext.h:217
Description of the encoding of one expression Op.
PrintedExpr(ExprKind K=Address)