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
9#include "llvm/DebugInfo/DWARF/DWARFExpressionPrinter.h"
10#include "llvm/ADT/SmallString.h"
11#include "llvm/ADT/StringExtras.h"
12#include "llvm/DebugInfo/DWARF/DWARFUnit.h"
13#include "llvm/DebugInfo/DWARF/LowLevel/DWARFExpression.h"
14#include "llvm/Support/Endian.h"
15#include "llvm/Support/FormatVariadic.h"
16#include <cassert>
17#include <cstdint>
18
19using namespace llvm;
20using namespace dwarf;
21
22namespace llvm {
23
24typedef DWARFExpression::Operation Op;
25typedef Op::Description Desc;
26
27/// Some backends (e.g. NVPTX) encode virtual register names as the DWARF
28/// register number: the ASCII bytes of the name are concatenated into a
29/// uint64_t (see NVPTXRegisterInfo::encodeRegisterForDwarf). When the object
30/// file is not the target backend, MCRegisterInfo cannot map these numbers, so
31/// recover the string for dumping.
32/// Returns true if the register name was decoded successfully, false otherwise.
33static bool decodeVirtualRegisterName(uint64_t DwarfRegNum,
34 SmallString<8> &Out) {
35 if (DwarfRegNum == 0)
36 return false;
37
38 uint64_t DwarfRegNumBE =
39 support::endian::byte_swap<uint64_t>(value: DwarfRegNum, endian: endianness::big);
40 const char *Data = reinterpret_cast<const char *>(&DwarfRegNumBE);
41 const char *Begin = std::find_if(first: Data, last: Data + sizeof(DwarfRegNumBE),
42 pred: [](char c) { return c != '\0'; });
43 SmallString<8> Tmp(Begin, Data + sizeof(DwarfRegNumBE));
44
45 if (Tmp.size() < 2)
46 return false;
47
48 if (!llvm::isAlnum(C: Tmp[0]) && Tmp[0] != '%')
49 return false;
50
51 for (size_t I = 1; I < Tmp.size(); ++I)
52 if (!llvm::isAlnum(C: Tmp[I]))
53 return false;
54
55 Out = Tmp;
56 return true;
57}
58
59/// Resolves a DWARF register number to a display name: first via \p
60/// GetNameForDWARFReg (MC register names), otherwise try decoding
61/// ASCII-encoded virtual register names (NVPTX-specific).
62/// Returns empty if neither applies.
63static std::string resolveRegName(
64 uint64_t DwarfRegNum, bool IsEH,
65 const std::function<StringRef(uint64_t, bool)> &GetNameForDWARFReg) {
66 if (GetNameForDWARFReg) {
67 StringRef R = GetNameForDWARFReg(DwarfRegNum, IsEH);
68 if (!R.empty())
69 return R.str();
70 }
71 SmallString<8> Decoded;
72 if (decodeVirtualRegisterName(DwarfRegNum, Out&: Decoded))
73 return Decoded.str().str();
74 return "";
75}
76
77static void prettyPrintBaseTypeRef(DWARFUnit *U, raw_ostream &OS,
78 DIDumpOptions DumpOpts,
79 ArrayRef<uint64_t> Operands,
80 unsigned Operand) {
81 assert(Operand < Operands.size() && "operand out of bounds");
82 if (!U) {
83 OS << formatv(Fmt: " <base_type ref: {0:x}>", Vals: Operands[Operand]);
84 return;
85 }
86 auto Die = U->getDIEForOffset(Offset: U->getOffset() + Operands[Operand]);
87 if (Die && Die.getTag() == dwarf::DW_TAG_base_type) {
88 OS << " (";
89 if (DumpOpts.Verbose)
90 OS << formatv(Fmt: "{0:x8} -> ", Vals: Operands[Operand]);
91 OS << formatv(Fmt: "{0:x8})", Vals: U->getOffset() + Operands[Operand]);
92 if (auto Name = dwarf::toString(V: Die.find(Attr: dwarf::DW_AT_name)))
93 OS << " \"" << *Name << "\"";
94 } else {
95 OS << formatv(Fmt: " <invalid base_type ref: {0:x}>", Vals: Operands[Operand]);
96 }
97}
98
99static bool printOp(const DWARFExpression::Operation *Op, raw_ostream &OS,
100 DIDumpOptions DumpOpts, const DWARFExpression *Expr,
101 DWARFUnit *U) {
102 if (Op->isError()) {
103 if (!DumpOpts.PrintRegisterOnly)
104 OS << "<decoding error>";
105 return false;
106 }
107
108 std::optional<unsigned> SubOpcode = Op->getSubCode();
109
110 // In "register-only" mode, still show simple constant-valued locations.
111 // This lets clients print annotations like "i = 0" when the location is
112 // a constant (e.g. DW_OP_constu/consts ... DW_OP_stack_value).
113 // We continue to suppress all other non-register ops in this mode.
114 if (DumpOpts.PrintRegisterOnly) {
115 // First, try pretty-printing registers (existing behavior below also does
116 // this, but we need to short-circuit here to avoid printing opcode names).
117 if ((Op->getCode() >= DW_OP_breg0 && Op->getCode() <= DW_OP_breg31) ||
118 (Op->getCode() >= DW_OP_reg0 && Op->getCode() <= DW_OP_reg31) ||
119 Op->getCode() == DW_OP_bregx || Op->getCode() == DW_OP_regx ||
120 Op->getCode() == DW_OP_regval_type ||
121 SubOpcode == DW_OP_LLVM_call_frame_entry_reg ||
122 SubOpcode == DW_OP_LLVM_aspace_bregx) {
123 if (prettyPrintRegisterOp(U, OS, DumpOpts, Opcode: Op->getCode(),
124 Operands: Op->getRawOperands()))
125 return true;
126 // If we couldn't pretty-print, fall through and suppress.
127 }
128
129 // Show constants (decimal), suppress everything else.
130 if (Op->getCode() == DW_OP_constu) {
131 OS << (uint64_t)Op->getRawOperand(Idx: 0);
132 return true;
133 }
134 if (Op->getCode() == DW_OP_consts) {
135 OS << (int64_t)Op->getRawOperand(Idx: 0);
136 return true;
137 }
138 if (Op->getCode() >= DW_OP_lit0 && Op->getCode() <= DW_OP_lit31) {
139 OS << (unsigned)(Op->getCode() - DW_OP_lit0);
140 return true;
141 }
142 if (Op->getCode() == DW_OP_stack_value)
143 return true; // metadata; don't print a token
144
145 return true; // suppress other opcodes silently in register-only mode
146 }
147
148 if (!DumpOpts.PrintRegisterOnly) {
149 StringRef Name = OperationEncodingString(Encoding: Op->getCode());
150 assert(!Name.empty() && "DW_OP has no name!");
151 OS << Name;
152
153 if (SubOpcode) {
154 StringRef SubName = SubOperationEncodingString(OpEncoding: Op->getCode(), SubOpEncoding: *SubOpcode);
155 assert(!SubName.empty() && "DW_OP SubOp has no name!");
156 OS << ' ' << SubName;
157 }
158 }
159
160 if ((Op->getCode() >= DW_OP_breg0 && Op->getCode() <= DW_OP_breg31) ||
161 (Op->getCode() >= DW_OP_reg0 && Op->getCode() <= DW_OP_reg31) ||
162 Op->getCode() == DW_OP_bregx || Op->getCode() == DW_OP_regx ||
163 Op->getCode() == DW_OP_regval_type ||
164 SubOpcode == DW_OP_LLVM_call_frame_entry_reg ||
165 SubOpcode == DW_OP_LLVM_aspace_bregx)
166 if (prettyPrintRegisterOp(U, OS, DumpOpts, Opcode: Op->getCode(),
167 Operands: Op->getRawOperands()))
168 return true;
169
170 if (!DumpOpts.PrintRegisterOnly) {
171 for (unsigned Operand = 0; Operand < Op->getDescription().Op.size();
172 ++Operand) {
173 unsigned Size = Op->getDescription().Op[Operand];
174 unsigned Signed = Size & DWARFExpression::Operation::SignBit;
175
176 if (Size == DWARFExpression::Operation::SizeSubOpLEB) {
177 assert(Operand == 0 && "DW_OP SubOp must be the first operand");
178 assert(SubOpcode && "DW_OP SubOp description is inconsistent");
179 } else if (Size == DWARFExpression::Operation::BaseTypeRef && U) {
180 // For DW_OP_convert the operand may be 0 to indicate that conversion to
181 // the generic type should be done. The same holds for
182 // DW_OP_reinterpret, which is currently not supported.
183 if (Op->getCode() == DW_OP_convert && Op->getRawOperand(Idx: Operand) == 0)
184 OS << " 0x0";
185 else
186 prettyPrintBaseTypeRef(U, OS, DumpOpts, Operands: Op->getRawOperands(),
187 Operand);
188 } else if (Size == DWARFExpression::Operation::WasmLocationArg) {
189 assert(Operand == 1);
190 switch (Op->getRawOperand(Idx: 0)) {
191 case 0:
192 case 1:
193 case 2:
194 case 3: // global as uint32
195 case 4:
196 OS << formatv(Fmt: " {0:x}", Vals: Op->getRawOperand(Idx: Operand));
197 break;
198 default:
199 assert(false);
200 }
201 } else if (Size == DWARFExpression::Operation::SizeBlock) {
202 uint64_t Offset = Op->getRawOperand(Idx: Operand);
203 for (unsigned i = 0; i < Op->getRawOperand(Idx: Operand - 1); ++i)
204 OS << formatv(Fmt: " {0:x2}",
205 Vals: static_cast<uint8_t>(Expr->getData()[Offset++]));
206 } else {
207 if (Signed)
208 OS << formatv(Fmt: " {0:+d}", Vals: (int64_t)Op->getRawOperand(Idx: Operand));
209 else if (Op->getCode() != DW_OP_entry_value &&
210 Op->getCode() != DW_OP_GNU_entry_value)
211 OS << formatv(Fmt: " {0:x}", Vals: Op->getRawOperand(Idx: Operand));
212 }
213 }
214 }
215 return true;
216}
217
218void printDwarfExpression(const DWARFExpression *E, raw_ostream &OS,
219 DIDumpOptions DumpOpts, DWARFUnit *U, bool IsEH) {
220 uint32_t EntryValExprSize = 0;
221 uint64_t EntryValStartOffset = 0;
222 if (E->getData().empty())
223 OS << "<empty>";
224
225 for (auto &Op : *E) {
226 DumpOpts.IsEH = IsEH;
227 if (!printOp(Op: &Op, OS, DumpOpts, Expr: E, U) && !DumpOpts.PrintRegisterOnly) {
228 uint64_t FailOffset = Op.getEndOffset();
229 while (FailOffset < E->getData().size())
230 OS << formatv(Fmt: " {0:x-2}",
231 Vals: static_cast<uint8_t>(E->getData()[FailOffset++]));
232 return;
233 }
234 if (!DumpOpts.PrintRegisterOnly) {
235 if (Op.getCode() == DW_OP_entry_value ||
236 Op.getCode() == DW_OP_GNU_entry_value) {
237 OS << "(";
238 EntryValExprSize = Op.getRawOperand(Idx: 0);
239 EntryValStartOffset = Op.getEndOffset();
240 continue;
241 }
242
243 if (EntryValExprSize) {
244 EntryValExprSize -= Op.getEndOffset() - EntryValStartOffset;
245 if (EntryValExprSize == 0)
246 OS << ")";
247 }
248
249 if (Op.getEndOffset() < E->getData().size())
250 OS << ", ";
251 }
252 }
253}
254
255/// A user-facing string representation of a DWARF expression. This might be an
256/// Address expression, in which case it will be implicitly dereferenced, or a
257/// Value expression.
258struct PrintedExpr {
259 enum ExprKind {
260 Address,
261 Value,
262 };
263 ExprKind Kind;
264 SmallString<16> String;
265
266 PrintedExpr(ExprKind K = Address) : Kind(K) {}
267};
268
269static bool printCompactDWARFExpr(
270 raw_ostream &OS, DWARFExpression::iterator I,
271 const DWARFExpression::iterator E,
272 std::function<StringRef(uint64_t RegNum, bool IsEH)> GetNameForDWARFReg =
273 nullptr) {
274 SmallVector<PrintedExpr, 4> Stack;
275
276 auto UnknownOpcode = [](raw_ostream &OS, uint8_t Opcode,
277 std::optional<unsigned> SubOpcode) -> bool {
278 // If we hit an unknown operand, we don't know its effect on the stack,
279 // so bail out on the whole expression.
280 OS << "<unknown op " << dwarf::OperationEncodingString(Encoding: Opcode) << " ("
281 << (int)Opcode;
282 if (SubOpcode)
283 OS << ") subop " << dwarf::SubOperationEncodingString(OpEncoding: Opcode, SubOpEncoding: *SubOpcode)
284 << " (" << *SubOpcode;
285 OS << ")>";
286 return false;
287 };
288
289 // Keep the diagnostic in the compact printer so every register form reports
290 // failure only after resolveRegName has tried to get a target name and decode
291 // an ASCII-packed name.
292 auto UnknownRegister = [](raw_ostream &OS, uint64_t DwarfRegNum) -> bool {
293 OS << "<unknown register " << DwarfRegNum << ">";
294 return false;
295 };
296
297 while (I != E) {
298 const DWARFExpression::Operation &Op = *I;
299 uint8_t Opcode = Op.getCode();
300 switch (Opcode) {
301 case dwarf::DW_OP_regx: {
302 // DW_OP_regx: A register, with the register num given as an operand.
303 // Printed as the plain register name.
304 const uint64_t DwarfRegNum = Op.getRawOperand(Idx: 0);
305 std::string RegName =
306 resolveRegName(DwarfRegNum, IsEH: false, GetNameForDWARFReg);
307 if (RegName.empty())
308 return UnknownRegister(OS, DwarfRegNum);
309 raw_svector_ostream S(Stack.emplace_back(Args: PrintedExpr::Value).String);
310 S << RegName;
311 break;
312 }
313 case dwarf::DW_OP_bregx: {
314 const uint64_t DwarfRegNum = Op.getRawOperand(Idx: 0);
315 const uint64_t Offset = Op.getRawOperand(Idx: 1);
316 std::string RegName =
317 resolveRegName(DwarfRegNum, IsEH: false, GetNameForDWARFReg);
318 if (RegName.empty())
319 return UnknownRegister(OS, DwarfRegNum);
320 raw_svector_ostream S(Stack.emplace_back().String);
321 S << RegName;
322 if (Offset)
323 S << formatv(Fmt: "{0:+d}", Vals: Offset);
324 break;
325 }
326 case dwarf::DW_OP_entry_value:
327 case dwarf::DW_OP_GNU_entry_value: {
328 // DW_OP_entry_value contains a sub-expression which must be rendered
329 // separately.
330 uint64_t SubExprLength = Op.getRawOperand(Idx: 0);
331 DWARFExpression::iterator SubExprEnd = I.skipBytes(Add: SubExprLength);
332 ++I;
333
334 SmallString<16> SubExpr;
335 raw_svector_ostream SubExprOS(SubExpr);
336 // Keep the subexpression separate so we can copy its diagnostic on
337 // failure without leaving a partial entry(...) in the output.
338 if (!printCompactDWARFExpr(OS&: SubExprOS, I, E: SubExprEnd,
339 GetNameForDWARFReg)) {
340 OS << SubExprOS.str();
341 return false;
342 }
343
344 raw_svector_ostream S(Stack.emplace_back().String);
345 S << "entry(" << SubExprOS.str() << ")";
346 I = SubExprEnd;
347 continue;
348 }
349 case dwarf::DW_OP_stack_value: {
350 // The top stack entry should be treated as the actual value of tne
351 // variable, rather than the address of the variable in memory.
352 assert(!Stack.empty());
353 Stack.back().Kind = PrintedExpr::Value;
354 break;
355 }
356 case dwarf::DW_OP_nop: {
357 break;
358 }
359 case dwarf::DW_OP_LLVM_user: {
360 std::optional<unsigned> SubOpcode = Op.getSubCode();
361 if (SubOpcode == dwarf::DW_OP_LLVM_nop)
362 break;
363 return UnknownOpcode(OS, Opcode, SubOpcode);
364 }
365 default:
366 if (Opcode >= dwarf::DW_OP_reg0 && Opcode <= dwarf::DW_OP_reg31) {
367 // DW_OP_reg<N>: A register, with the register num implied by the
368 // opcode. Printed as the plain register name.
369 uint64_t DwarfRegNum = Opcode - dwarf::DW_OP_reg0;
370 std::string RegName =
371 resolveRegName(DwarfRegNum, IsEH: false, GetNameForDWARFReg);
372 if (RegName.empty())
373 return UnknownRegister(OS, DwarfRegNum);
374 raw_svector_ostream S(Stack.emplace_back(Args: PrintedExpr::Value).String);
375 S << RegName;
376 } else if (Opcode >= dwarf::DW_OP_breg0 &&
377 Opcode <= dwarf::DW_OP_breg31) {
378 int DwarfRegNum = Opcode - dwarf::DW_OP_breg0;
379 int64_t Offset = Op.getRawOperand(Idx: 0);
380 std::string RegName =
381 resolveRegName(DwarfRegNum, IsEH: false, GetNameForDWARFReg);
382 if (RegName.empty())
383 return UnknownRegister(OS, DwarfRegNum);
384 raw_svector_ostream S(Stack.emplace_back().String);
385 S << RegName;
386 if (Offset)
387 S << formatv(Fmt: "{0:+d}", Vals&: Offset);
388 } else {
389 return UnknownOpcode(OS, Opcode, std::nullopt);
390 }
391 break;
392 }
393 ++I;
394 }
395
396 if (Stack.size() != 1) {
397 OS << "<stack of size " << Stack.size() << ", expected 1>";
398 return false;
399 }
400
401 if (Stack.front().Kind == PrintedExpr::Address)
402 OS << "[" << Stack.front().String << "]";
403 else
404 OS << Stack.front().String;
405
406 return true;
407}
408
409bool printDwarfExpressionCompact(
410 const DWARFExpression *E, raw_ostream &OS,
411 std::function<StringRef(uint64_t RegNum, bool IsEH)> GetNameForDWARFReg) {
412 return printCompactDWARFExpr(OS, I: E->begin(), E: E->end(), GetNameForDWARFReg);
413}
414
415bool prettyPrintRegisterOp(DWARFUnit *U, raw_ostream &OS,
416 DIDumpOptions DumpOpts, uint8_t Opcode,
417 ArrayRef<uint64_t> Operands) {
418 uint64_t DwarfRegNum;
419 unsigned OpNum = 0;
420
421 std::optional<unsigned> SubOpcode;
422 if (Opcode == DW_OP_LLVM_user)
423 SubOpcode = Operands[OpNum++];
424
425 const bool RegNumFromOperand =
426 Opcode == DW_OP_bregx || Opcode == DW_OP_regx ||
427 Opcode == DW_OP_regval_type || SubOpcode == DW_OP_LLVM_aspace_bregx ||
428 SubOpcode == DW_OP_LLVM_call_frame_entry_reg;
429
430 if (RegNumFromOperand)
431 DwarfRegNum = Operands[OpNum++];
432 else if (Opcode >= DW_OP_breg0 && Opcode < DW_OP_bregx)
433 DwarfRegNum = Opcode - DW_OP_breg0;
434 else
435 DwarfRegNum = Opcode - DW_OP_reg0;
436
437 std::string RegName =
438 resolveRegName(DwarfRegNum, IsEH: DumpOpts.IsEH, GetNameForDWARFReg: DumpOpts.GetNameForDWARFReg);
439
440 if (!RegName.empty()) {
441 if ((Opcode >= DW_OP_breg0 && Opcode <= DW_OP_breg31) ||
442 Opcode == DW_OP_bregx || SubOpcode == DW_OP_LLVM_aspace_bregx)
443 OS << ' ' << RegName << formatv(Fmt: "{0:+d}", Vals: int64_t(Operands[OpNum]));
444 else
445 OS << ' ' << RegName;
446
447 if (Opcode == DW_OP_regval_type)
448 prettyPrintBaseTypeRef(U, OS, DumpOpts, Operands, Operand: 1);
449 return true;
450 }
451
452 return false;
453}
454
455} // namespace llvm
456