LLVM 24.0.0git
DwarfExpression.cpp
Go to the documentation of this file.
1//===- llvm/CodeGen/DwarfExpression.cpp - Dwarf Debug Framework -----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains support for writing dwarf debug info into asm files.
10//
11//===----------------------------------------------------------------------===//
12
13#include "DwarfExpression.h"
14#include "DwarfCompileUnit.h"
15#include "llvm/ADT/APInt.h"
20#include "llvm/IR/DataLayout.h"
21#include "llvm/MC/MCAsmInfo.h"
23#include <algorithm>
24
25using namespace llvm;
26
27#define DEBUG_TYPE "dwarfdebug"
28
29/// Return whether the rest of the expression needs the complex register path.
30/// We use this to decide whether we can emit a simple register location and
31/// whether a subregister needs to be masked. Non-emitting operations don't
32/// affect either decision, so look past them.
33static bool isRemainingExpressionComplex(const DIExpressionCursor &ExprCursor) {
34 for (DIExpression::ExprOperand Op : ExprCursor) {
35 if (Op.isNonEmitting())
36 continue;
37 return Op.getOp() != dwarf::DW_OP_LLVM_fragment;
38 }
39 return false;
40}
41
43 if (Value < 32)
44 emitOp(dwarf::DW_OP_lit0 + Value);
45 else if (Value == std::numeric_limits<uint64_t>::max()) {
46 // Only do this for 64-bit values as the DWARF expression stack uses
47 // target-address-size values.
48 emitOp(dwarf::DW_OP_lit0);
49 emitOp(dwarf::DW_OP_not);
50 } else {
51 emitOp(dwarf::DW_OP_constu);
53 }
54}
55
56void DwarfExpression::addReg(int64_t DwarfReg, const char *Comment) {
57 assert(DwarfReg >= 0 && "invalid negative dwarf register number");
59 "location description already locked down");
61 if (DwarfReg < 32) {
62 emitOp(dwarf::DW_OP_reg0 + DwarfReg, Comment);
63 } else {
64 emitOp(dwarf::DW_OP_regx, Comment);
65 emitUnsigned(DwarfReg);
66 }
67}
68
69void DwarfExpression::addBReg(int64_t DwarfReg, int64_t Offset) {
70 assert(DwarfReg >= 0 && "invalid negative dwarf register number");
71 assert(!isRegisterLocation() && "location description already locked down");
72 if (DwarfReg < 32) {
73 emitOp(dwarf::DW_OP_breg0 + DwarfReg);
74 } else {
75 emitOp(dwarf::DW_OP_bregx);
76 emitUnsigned(DwarfReg);
77 }
79}
80
82 emitOp(dwarf::DW_OP_fbreg);
84}
85
86void DwarfExpression::addOpPiece(unsigned SizeInBits, unsigned OffsetInBits) {
87 if (!SizeInBits)
88 return;
89
90 const unsigned SizeOfByte = 8;
91 if (OffsetInBits > 0 || SizeInBits % SizeOfByte) {
92 emitOp(dwarf::DW_OP_bit_piece);
93 emitUnsigned(SizeInBits);
95 } else {
96 emitOp(dwarf::DW_OP_piece);
97 unsigned ByteSize = SizeInBits / SizeOfByte;
98 emitUnsigned(ByteSize);
99 }
100 this->OffsetInBits += SizeInBits;
101}
102
103void DwarfExpression::addShr(unsigned ShiftBy) {
104 emitConstu(ShiftBy);
105 emitOp(dwarf::DW_OP_shr);
106}
107
108void DwarfExpression::addAnd(unsigned Mask) {
109 emitConstu(Mask);
110 emitOp(dwarf::DW_OP_and);
111}
112
114 llvm::Register MachineReg,
115 unsigned MaxSize) {
116 if (!MachineReg.isPhysical()) {
117 if (isFrameRegister(TRI, MachineReg)) {
118 DwarfRegs.push_back(Register::createRegister(-1, nullptr));
119 return true;
120 }
121 // Try getting dwarf register for targets that use virtual registers.
122 int64_t Reg = TRI.getDwarfRegNumForVirtReg(MachineReg, false);
123 if (Reg > 0) {
124 DwarfRegs.push_back(Register::createRegister(Reg, nullptr));
125 return true;
126 }
127 return false;
128 }
129
130 int64_t Reg = TRI.getDwarfRegNum(MachineReg, false);
131
132 // If this is a valid register number, emit it.
133 if (Reg >= 0) {
134 DwarfRegs.push_back(Register::createRegister(Reg, nullptr));
135 return true;
136 }
137
138 // The frame register is referenced through DW_OP_fbreg relative to
139 // DW_AT_frame_base, so it needs no DWARF register number of its own.
140 if (isFrameRegister(TRI, MachineReg)) {
141 DwarfRegs.push_back(Register::createRegister(-1, nullptr));
142 return true;
143 }
144
145 // Walk up the super-register chain until we find a valid number.
146 // For example, EAX on x86_64 is a 32-bit fragment of RAX with offset 0.
147 for (MCPhysReg SR : TRI.superregs(MachineReg)) {
148 Reg = TRI.getDwarfRegNum(SR, false);
149 if (Reg >= 0) {
150 unsigned Idx = TRI.getSubRegIndex(SR, MachineReg);
151 unsigned Size = TRI.getSubRegIdxSize(Idx);
152 unsigned RegOffset = TRI.getSubRegIdxOffset(Idx);
153 DwarfRegs.push_back(Register::createRegister(Reg, "super-register"));
154 // Use a DW_OP_bit_piece to describe the sub-register.
155 setSubRegisterPiece(Size, RegOffset);
156 return true;
157 }
158 }
159
160 // Otherwise, attempt to find a covering set of sub-register numbers.
161 // For example, Q0 on ARM is a composition of D0+D1.
162 unsigned CurPos = 0;
163 // The size of the register in bits.
164 const TargetRegisterClass *RC = TRI.getMinimalPhysRegClass(MachineReg);
165 unsigned RegSize = TRI.getRegSizeInBits(*RC);
166 // Keep track of the bits in the register we already emitted, so we
167 // can avoid emitting redundant aliasing subregs. Because this is
168 // just doing a greedy scan of all subregisters, it is possible that
169 // this doesn't find a combination of subregisters that fully cover
170 // the register (even though one may exist).
171 SmallBitVector Coverage(RegSize, false);
172 for (MCPhysReg SR : TRI.subregs(MachineReg)) {
173 unsigned Idx = TRI.getSubRegIndex(MachineReg, SR);
174 unsigned Size = TRI.getSubRegIdxSize(Idx);
175 unsigned Offset = TRI.getSubRegIdxOffset(Idx);
176 Reg = TRI.getDwarfRegNum(SR, false);
178 continue;
179
180 // Used to build the intersection between the bits we already
181 // emitted and the bits covered by this subregister.
182 SmallBitVector CurSubReg(RegSize, false);
183 CurSubReg.set(Offset, Offset + Size);
184
185 // If this sub-register has a DWARF number and we haven't covered
186 // its range, and its range covers the value, emit a DWARF piece for it.
187 if (Offset < MaxSize && !CurSubReg.subsetOf(Coverage)) {
188 // Emit a piece for any gap in the coverage.
189 if (Offset > CurPos)
191 -1, Offset - CurPos, "no DWARF register encoding"));
192 if (Offset == 0 && Size >= MaxSize)
193 DwarfRegs.push_back(Register::createRegister(Reg, "sub-register"));
194 else
196 Reg, std::min<unsigned>(Size, MaxSize - Offset), "sub-register"));
197 }
198 // Mark it as emitted.
199 Coverage.set(Offset, Offset + Size);
200 CurPos = Offset + Size;
201 }
202 // Failed to find any DWARF encoding.
203 if (CurPos == 0)
204 return false;
205 // Found a partial or complete DWARF encoding.
206 if (CurPos < RegSize)
208 -1, RegSize - CurPos, "no DWARF register encoding"));
209 return true;
210}
211
213 if (DwarfVersion >= 4)
214 emitOp(dwarf::DW_OP_stack_value);
215}
216
220 if (Value == 0)
221 emitOp(dwarf::DW_OP_lit0);
222 else
223 emitOp(dwarf::DW_OP_lit1);
224}
225
232
238
242
243 unsigned Size = Value.getBitWidth();
244 const uint64_t *Data = Value.getRawData();
245
246 // Chop it up into 64-bit pieces, because that's the maximum that
247 // addUnsignedConstant takes.
248 unsigned Offset = 0;
249 while (Offset < Size) {
251 if (Offset == 0 && Size <= 64)
252 break;
254 addOpPiece(std::min(Size - Offset, 64u), Offset);
255 Offset += 64;
256 }
257}
258
260 const AsmPrinter &AP) {
262 assert(DwarfVersion >= 4);
263
264 APInt API = Value;
265 unsigned NumBytes = API.getBitWidth() / 8;
266 assert(API.getBitWidth() == NumBytes * 8 &&
267 "implicit value must be byte-sized");
268
269 emitOp(dwarf::DW_OP_implicit_value);
270 emitUnsigned(NumBytes);
271
272 // The loop below is emitting the value starting at the least significant
273 // byte, so byte-swap first for big-endian targets.
274 if (AP.getDataLayout().isBigEndian())
275 API = API.byteSwap();
276
277 for (unsigned I = 0; I < NumBytes; ++I)
278 emitData1(API.extractBits(8, I * 8).getZExtValue());
279}
280
283 APInt API = APF.bitcastToAPInt();
284 int NumBytes = API.getBitWidth() / 8;
285 if (NumBytes == 4 /*float*/ || NumBytes == 8 /*double*/) {
286 // FIXME: Add support for `long double`.
287 emitOp(dwarf::DW_OP_implicit_value);
288 emitUnsigned(NumBytes /*Size of the block in bytes*/);
289
290 // The loop below is emitting the value starting at least significant byte,
291 // so we need to perform a byte-swap to get the byte order correct in case
292 // of a big-endian target.
293 if (AP.getDataLayout().isBigEndian())
294 API = API.byteSwap();
295
296 for (int i = 0; i < NumBytes; ++i) {
297 emitData1(API.getZExtValue() & 0xFF);
298 API = API.lshr(8);
299 }
300
301 return;
302 }
304 dbgs() << "Skipped DW_OP_implicit_value creation for ConstantFP of size: "
305 << API.getBitWidth() << " bits\n");
306}
307
309 DIExpressionCursor &ExprCursor,
310 llvm::Register MachineReg,
311 unsigned FragmentOffsetInBits) {
312 auto Fragment = ExprCursor.getFragmentInfo();
313 if (!addMachineReg(TRI, MachineReg, Fragment ? Fragment->SizeInBits : ~1U)) {
315 return false;
316 }
317
318 bool HasComplexExpression = isRemainingExpressionComplex(ExprCursor);
319
320 // If the register can only be described by a complex expression (i.e.,
321 // multiple subregisters) it doesn't safely compose with another complex
322 // expression. For example, it is not possible to apply a DW_OP_deref
323 // operation to multiple DW_OP_pieces, since composite location descriptions
324 // do not push anything on the DWARF stack.
325 //
326 // DW_OP_entry_value operations can only hold a DWARF expression or a
327 // register location description, so we can't emit a single entry value
328 // covering a composite location description. In the future we may want to
329 // emit entry value operations for each register location in the composite
330 // location, but until that is supported do not emit anything.
331 if ((HasComplexExpression || IsEmittingEntryValue) && DwarfRegs.size() > 1) {
334 DwarfRegs.clear();
336 return false;
337 }
338
339 // Handle simple register locations. If we are supposed to emit
340 // a call site parameter expression and if that expression is just a register
341 // location, emit it with addBReg and offset 0, because we should emit a DWARF
342 // expression representing a value, rather than a location.
343 if ((!isParameterValue() && !isMemoryLocation() && !HasComplexExpression) ||
344 isEntryValue()) {
345 unsigned RegSize = 0;
346 for (auto &Reg : DwarfRegs) {
347 RegSize += Reg.SubRegSize;
348 if (Reg.DwarfRegNo >= 0)
349 addReg(Reg.DwarfRegNo, Reg.Comment);
350 if (Fragment && RegSize > Fragment->SizeInBits)
351 // If the register is larger than the current fragment stop
352 // once the fragment is covered.
353 break;
354 addOpPiece(Reg.SubRegSize);
355 }
356
357 if (isEntryValue()) {
359
360 if (!isIndirect() && !isParameterValue() && !HasComplexExpression &&
361 DwarfVersion >= 4)
362 emitOp(dwarf::DW_OP_stack_value);
363 }
364
365 DwarfRegs.clear();
366 // If we need to mask out a subregister, do it now, unless the next
367 // operation would emit an OpPiece anyway.
370 return true;
371 }
372
373 // Don't emit locations that cannot be expressed without DW_OP_stack_value.
374 if (DwarfVersion < 4)
375 if (any_of(ExprCursor, [](DIExpression::ExprOperand Op) -> bool {
376 return Op.getOp() == dwarf::DW_OP_stack_value;
377 })) {
378 DwarfRegs.clear();
380 return false;
381 }
382
383 // TODO: We should not give up here but the following code needs to be changed
384 // to deal with multiple (sub)registers first.
385 if (DwarfRegs.size() > 1) {
386 LLVM_DEBUG(dbgs() << "TODO: giving up on debug information due to "
387 "multi-register usage.\n");
388 DwarfRegs.clear();
390 return false;
391 }
392
393 // Consume leading tag offsets before matching the register expression.
394 // Record the tag offset here because addExpression won't see a consumed
395 // operation.
396 while (auto Op = ExprCursor.peek()) {
398 if (!Tag)
399 break;
400 TagOffset = Tag.getTagOffset();
401 ExprCursor.take();
402 }
403
404 auto Op = ExprCursor.peek();
405 auto Reg = DwarfRegs[0];
406 int SignedOffset = 0;
407 assert(!Reg.isSubRegister() && "full register expected");
408
409 // Pattern-match combinations for which more efficient representations exist.
410 if (Op) {
411 const uint64_t IntMax =
412 static_cast<uint64_t>(std::numeric_limits<int>::max());
413 // [Reg, DW_OP_plus_uconst, Offset] --> [DW_OP_breg, Offset].
415 uint64_t Offset = PlusUconst.getOffset();
416 if (Offset <= IntMax) {
417 SignedOffset = Offset;
418 ExprCursor.take();
419 }
420 } else if (auto Constant = dyn_cast<DIExpression::ConstuOp>(*Op)) {
421 // [Reg, DW_OP_constu, Offset, DW_OP_plus] --> [DW_OP_breg, Offset]
422 // [Reg, DW_OP_constu, Offset, DW_OP_minus] --> [DW_OP_breg,-Offset]
423 // If Reg is a subregister we need to mask it out before subtracting.
424 uint64_t Offset = Constant.getValue();
425 auto N = ExprCursor.peekNext();
426 if (N && N->getOp() == dwarf::DW_OP_plus && Offset <= IntMax) {
427 SignedOffset = Offset;
428 ExprCursor.consume(2);
429 } else if (N && N->getOp() == dwarf::DW_OP_minus &&
430 !SubRegisterSizeInBits && Offset <= IntMax + 1) {
431 SignedOffset = -static_cast<int64_t>(Offset);
432 ExprCursor.consume(2);
433 }
434 }
435 }
436
437 if (isFrameRegister(TRI, MachineReg))
438 addFBReg(SignedOffset);
439 else
440 addBReg(Reg.DwarfRegNo, SignedOffset);
441 DwarfRegs.clear();
442
443 // If we need to mask out a subregister, do it now, unless the next
444 // operation would emit an OpPiece anyway.
447
448 return true;
449}
450
456
458 const DIExpression *DIExpr) {
459 if (Loc.isIndirect())
461
462 if (DIExpr->isEntryValue())
464}
465
467 DIExpressionCursor &ExprCursor) {
468 auto Op = ExprCursor.take();
469 (void)Op;
471 assert(!IsEmittingEntryValue && "Already emitting entry value?");
472 assert(cast<DIExpression::EntryValueOp>(*Op).getNumOperations() == 1 &&
473 "Can currently only emit entry values covering a single operation");
474
480}
481
483 assert(IsEmittingEntryValue && "Entry value not open?");
485
486 emitOp(CU.getDwarf5OrGNULocationAtom(dwarf::DW_OP_entry_value));
487
488 // Emit the entry value's size operand.
489 unsigned Size = getTemporaryBufferSize();
491
492 // Emit the entry value's DWARF block operand.
494
497 IsEmittingEntryValue = false;
498}
499
501 assert(IsEmittingEntryValue && "Entry value not open?");
503
504 // The temporary buffer can't be emptied, so for now just assert that nothing
505 // has been emitted to it.
507 "Began emitting entry value block before cancelling entry value");
508
510 IsEmittingEntryValue = false;
511}
512
513unsigned DwarfExpression::getOrCreateBaseType(unsigned BitSize,
514 dwarf::TypeKind Encoding) {
515 // Reuse the base_type if we already have one in this CU otherwise we
516 // create a new one.
517 unsigned I = 0, E = CU.ExprRefedBaseTypes.size();
518 for (; I != E; ++I)
519 if (CU.ExprRefedBaseTypes[I].BitSize == BitSize &&
520 CU.ExprRefedBaseTypes[I].Encoding == Encoding)
521 break;
522
523 if (I == E)
524 CU.ExprRefedBaseTypes.emplace_back(BitSize, Encoding);
525 return I;
526}
527
528/// Assuming a well-formed expression, match "DW_OP_deref*
529/// DW_OP_LLVM_fragment?".
530static bool isMemoryLocation(DIExpressionCursor ExprCursor) {
531 while (ExprCursor) {
532 auto Op = ExprCursor.take();
533 switch (Op->getOp()) {
534 case dwarf::DW_OP_deref:
536 break;
537 default:
538 return false;
539 }
540 }
541 return true;
542}
543
545 return addExpression(std::move(ExprCursor),
546 [](unsigned Idx, DIExpressionCursor &Cursor) -> bool {
548 "unhandled opcode found in expression");
549 });
550}
551
553 DIExpressionCursor &&ExprCursor,
554 llvm::function_ref<bool(unsigned, DIExpressionCursor &)> InsertArg) {
555 // Entry values can currently only cover the initial register location,
556 // and not any other parts of the following DWARF expression.
557 assert(!IsEmittingEntryValue && "Can't emit entry value around expression");
558
559 std::optional<DIExpression::ConvertOp> PrevConvertOp;
560
561 while (ExprCursor) {
562 auto Op = ExprCursor.take();
563 uint64_t OpNum = Op->getOp();
564
565 if (OpNum >= dwarf::DW_OP_reg0 && OpNum <= dwarf::DW_OP_reg31) {
566 emitOp(OpNum);
567 continue;
568 } else if (OpNum >= dwarf::DW_OP_breg0 && OpNum <= dwarf::DW_OP_breg31) {
569 addBReg(OpNum - dwarf::DW_OP_breg0, Op->getArg(0));
570 continue;
571 }
572
573 switch (OpNum) {
575 if (!InsertArg(cast<DIExpression::ArgOp>(*Op).getIndex(), ExprCursor)) {
577 return false;
578 }
579 break;
582 unsigned SizeInBits = Fragment.getSizeInBits();
583 unsigned FragmentOffset = Fragment.getOffsetInBits();
584 // The fragment offset must have already been adjusted by emitting an
585 // empty DW_OP_piece / DW_OP_bit_piece before we emitted the base
586 // location.
587 assert(OffsetInBits >= FragmentOffset && "fragment offset not added?");
588 assert(SizeInBits >= OffsetInBits - FragmentOffset && "size underflow");
589
590 // If addMachineReg already emitted DW_OP_piece operations to represent
591 // a super-register by splicing together sub-registers, subtract the size
592 // of the pieces that was already emitted.
593 SizeInBits -= OffsetInBits - FragmentOffset;
594
595 // If addMachineReg requested a DW_OP_bit_piece to stencil out a
596 // sub-register that is smaller than the current fragment's size, use it.
598 SizeInBits = std::min<unsigned>(SizeInBits, SubRegisterSizeInBits);
599
600 // Emit a DW_OP_stack_value for implicit location descriptions.
601 if (isImplicitLocation())
603
604 // Emit the DW_OP_piece.
607 // Reset the location description kind.
609 return true;
610 }
613 auto Extract = cast<DIExpression::ExtractBitsOp>(*Op);
614 unsigned SizeInBits = Extract.getSizeInBits();
615 unsigned BitOffset = Extract.getOffsetInBits();
616 bool IsSigned = Extract.isSigned();
617 unsigned DerefSize = 0;
618 // Operations are done in the DWARF "generic type" whose size
619 // is the size of a pointer.
620 unsigned PtrSizeInBytes = CU.getAsmPrinter()->MAI.getCodePointerSize();
621
622 // If we have a memory location then dereference to get the value, though
623 // we have to make sure we don't dereference any bytes past the end of the
624 // object.
625 if (isMemoryLocation()) {
626 DerefSize = alignTo(BitOffset + SizeInBits, 8) / 8;
627 if (DerefSize == PtrSizeInBytes) {
628 emitOp(dwarf::DW_OP_deref);
629 } else {
630 emitOp(dwarf::DW_OP_deref_size);
631 emitUnsigned(DerefSize);
632 }
633 }
634
635 // If a dereference was emitted for an unsigned value, and
636 // there's no bit offset, then a bit of optimization is
637 // possible.
638 if (!IsSigned && BitOffset == 0) {
639 if (8 * DerefSize == SizeInBits) {
640 // The correct value is already on the stack.
641 } else {
642 // No need to shift, we can just mask off the desired bits.
643 emitOp(dwarf::DW_OP_constu);
644 emitUnsigned((1u << SizeInBits) - 1);
645 emitOp(dwarf::DW_OP_and);
646 }
647 } else {
648 // Extract the bits by a shift left (to shift out the bits after what we
649 // want to extract) followed by shift right (to shift the bits to
650 // position 0 and also sign/zero extend).
651 unsigned LeftShift = PtrSizeInBytes * 8 - (SizeInBits + BitOffset);
652 unsigned RightShift = LeftShift + BitOffset;
653 if (LeftShift) {
654 emitOp(dwarf::DW_OP_constu);
655 emitUnsigned(LeftShift);
656 emitOp(dwarf::DW_OP_shl);
657 }
658 if (RightShift) {
659 emitOp(dwarf::DW_OP_constu);
660 emitUnsigned(RightShift);
661 emitOp(IsSigned ? dwarf::DW_OP_shra : dwarf::DW_OP_shr);
662 }
663 }
664
665 // The value is now at the top of the stack, so set the location to
666 // implicit so that we get a stack_value at the end.
668 break;
669 }
670 case dwarf::DW_OP_plus_uconst:
672 emitOp(dwarf::DW_OP_plus_uconst);
674 break;
675 case dwarf::DW_OP_plus:
676 case dwarf::DW_OP_minus:
677 case dwarf::DW_OP_mul:
678 case dwarf::DW_OP_div:
679 case dwarf::DW_OP_mod:
680 case dwarf::DW_OP_or:
681 case dwarf::DW_OP_and:
682 case dwarf::DW_OP_xor:
683 case dwarf::DW_OP_shl:
684 case dwarf::DW_OP_shr:
685 case dwarf::DW_OP_shra:
686 case dwarf::DW_OP_lit0:
687 case dwarf::DW_OP_not:
688 case dwarf::DW_OP_dup:
689 case dwarf::DW_OP_push_object_address:
690 case dwarf::DW_OP_over:
691 case dwarf::DW_OP_rot:
692 case dwarf::DW_OP_eq:
693 case dwarf::DW_OP_ne:
694 case dwarf::DW_OP_gt:
695 case dwarf::DW_OP_ge:
696 case dwarf::DW_OP_lt:
697 case dwarf::DW_OP_le:
698 case dwarf::DW_OP_neg:
699 case dwarf::DW_OP_abs:
700 emitOp(OpNum);
701 break;
702 case dwarf::DW_OP_deref:
704 if (!isMemoryLocation() && ::isMemoryLocation(ExprCursor))
705 // Turning this into a memory location description makes the deref
706 // implicit.
708 else
709 emitOp(dwarf::DW_OP_deref);
710 break;
711 case dwarf::DW_OP_constu:
714 break;
715 case dwarf::DW_OP_consts:
717 emitOp(dwarf::DW_OP_consts);
718 emitSigned(Op->getArg(0));
719 break;
721 auto Convert = cast<DIExpression::ConvertOp>(*Op);
722 unsigned BitSize = Convert.getBitSize();
723 dwarf::TypeKind Encoding =
724 static_cast<dwarf::TypeKind>(Convert.getEncoding());
725 if (DwarfVersion >= 5 && CU.getDwarfDebug().useOpConvert()) {
726 emitOp(dwarf::DW_OP_convert);
727 // If targeting a location-list; simply emit the index into the raw
728 // byte stream as ULEB128, DwarfDebug::emitDebugLocEntry has been
729 // fitted with means to extract it later.
730 // If targeting a inlined DW_AT_location; insert a DIEBaseTypeRef
731 // (containing the index and a resolve mechanism during emit) into the
732 // DIE value list.
733 emitBaseTypeRef(getOrCreateBaseType(BitSize, Encoding));
734 } else {
735 if (PrevConvertOp && PrevConvertOp->getBitSize() < BitSize) {
736 if (Encoding == dwarf::DW_ATE_signed)
737 emitLegacySExt(PrevConvertOp->getBitSize());
738 else if (Encoding == dwarf::DW_ATE_unsigned)
739 emitLegacyZExt(PrevConvertOp->getBitSize());
740 PrevConvertOp = std::nullopt;
741 } else {
742 PrevConvertOp = Convert;
743 }
744 }
745 break;
746 }
747 case dwarf::DW_OP_stack_value:
749 break;
750 case dwarf::DW_OP_swap:
752 emitOp(dwarf::DW_OP_swap);
753 break;
754 case dwarf::DW_OP_xderef:
756 emitOp(dwarf::DW_OP_xderef);
757 break;
758 case dwarf::DW_OP_deref_size:
759 emitOp(dwarf::DW_OP_deref_size);
760 emitData1(Op->getArg(0));
761 break;
763 TagOffset = cast<DIExpression::TagOffsetOp>(*Op).getTagOffset();
764 break;
765 case dwarf::DW_OP_regx:
766 emitOp(dwarf::DW_OP_regx);
767 emitUnsigned(Op->getArg(0));
768 break;
769 case dwarf::DW_OP_bregx:
770 emitOp(dwarf::DW_OP_bregx);
771 emitUnsigned(Op->getArg(0));
772 emitSigned(Op->getArg(1));
773 break;
775 // Handled in DwarfCompileUnit::emitImplicitPointerLocation for
776 // Loc::Single variables. If we reach here, the variable has a
777 // location list or other unsupported path. Drop the
778 // location rather than crashing.
779 return false;
780 default:
781 llvm_unreachable("unhandled opcode found in expression");
782 }
783 }
784
786 // Turn this into an implicit location description.
788
789 return true;
790}
791
792/// Emit shift/mask operations for the pending subregister. After the operations
793/// are emitted, consume the pending subregister description by clearing
794/// SubRegisterSizeInBits and SubRegisterOffsetInBits.
796 assert(SubRegisterSizeInBits && "no subregister was registered");
799 uint64_t Mask = (1ULL << (uint64_t)SubRegisterSizeInBits) - 1ULL;
800 addAnd(Mask);
801 // The mask consumes the pending subregister description.
803}
804
806 assert(DwarfRegs.size() == 0 && "dwarf registers not emitted");
807 // Emit any outstanding DW_OP_piece operations to mask out subregisters.
808 if (SubRegisterSizeInBits == 0)
809 return;
810 // Don't emit a DW_OP_piece for a subregister at offset 0.
812 return;
814}
815
817 if (!Expr || !Expr->isFragment())
818 return;
819
820 uint64_t FragmentOffset = Expr->getFragmentInfo()->OffsetInBits;
821 assert(FragmentOffset >= OffsetInBits &&
822 "overlapping or duplicate fragments");
823 if (FragmentOffset > OffsetInBits)
824 addOpPiece(FragmentOffset - OffsetInBits);
825 OffsetInBits = FragmentOffset;
826}
827
828void DwarfExpression::emitLegacySExt(unsigned FromBits) {
829 // (((X >> (FromBits - 1)) * (~0)) << FromBits) | X
830 emitOp(dwarf::DW_OP_dup);
831 emitOp(dwarf::DW_OP_constu);
832 emitUnsigned(FromBits - 1);
833 emitOp(dwarf::DW_OP_shr);
834 emitOp(dwarf::DW_OP_lit0);
835 emitOp(dwarf::DW_OP_not);
836 emitOp(dwarf::DW_OP_mul);
837 emitOp(dwarf::DW_OP_constu);
838 emitUnsigned(FromBits);
839 emitOp(dwarf::DW_OP_shl);
840 emitOp(dwarf::DW_OP_or);
841}
842
843void DwarfExpression::emitLegacyZExt(unsigned FromBits) {
844 // Heuristic to decide the most efficient encoding.
845 // A ULEB can encode 7 1-bits per byte.
846 if (FromBits / 7 < 1+1+1+1+1) {
847 // (X & (1 << FromBits - 1))
848 emitOp(dwarf::DW_OP_constu);
849 emitUnsigned((1ULL << FromBits) - 1);
850 } else {
851 // Note that the DWARF 4 stack consists of pointer-sized elements,
852 // so technically it doesn't make sense to shift left more than 64
853 // bits. We leave that for the consumer to decide though. LLDB for
854 // example uses APInt for the stack elements and can still deal
855 // with this.
856 emitOp(dwarf::DW_OP_lit1);
857 emitOp(dwarf::DW_OP_constu);
858 emitUnsigned(FromBits);
859 emitOp(dwarf::DW_OP_shl);
860 emitOp(dwarf::DW_OP_lit1);
861 emitOp(dwarf::DW_OP_minus);
862 }
863 emitOp(dwarf::DW_OP_and);
864}
865
867 // This is an implicit location, and finalize() spells that with
868 // DW_OP_stack_value, which DWARF 4 introduced. Before it, the expression
869 // would read as the address the variable lives at rather than as its value,
870 // and there is no older spelling to fall back on.
871 if (DwarfVersion < 4)
872 return false;
873
874 // Prefer the address pool, whose index is plain data and so can be emitted
875 // into either output form. Before DWARF 5 the pool is only available under
876 // split DWARF, leaving a relocated DW_OP_addr as the only spelling -- which
877 // only a DIE can carry.
879}
880
882 return DwarfVersion >= 5 || CU.getDwarfDebug().useSplitDwarf();
883}
884
886 if (!canAddGlobalAddress())
887 return false;
888
891
892 DwarfDebug &DD = CU.getDwarfDebug();
893 const MCSymbol *Sym = CU.getAsmPrinter()->getSymbol(GV);
894 if (usesAddressPool()) {
895 emitOp(DwarfVersion >= 5 ? dwarf::DW_OP_addrx
896 : dwarf::DW_OP_GNU_addr_index);
898 } else {
899 emitOp(dwarf::DW_OP_addr);
901 }
902
903 // The displacement cannot be folded into the address itself: a pool entry is
904 // keyed on the symbol alone, and a DW_FORM_addr label carries no addend. Let
905 // the expression apply it instead.
906 if (Offset > 0) {
907 emitOp(dwarf::DW_OP_plus_uconst);
909 } else if (Offset < 0) {
911 emitOp(dwarf::DW_OP_plus);
912 }
913 return true;
914}
915
916void DwarfExpression::addWasmLocation(unsigned Index, uint64_t Offset) {
917 emitOp(dwarf::DW_OP_WASM_location);
918 emitUnsigned(Index == 4/*TI_LOCAL_INDIRECT*/ ? 0/*TI_LOCAL*/ : Index);
920 if (Index == 4 /*TI_LOCAL_INDIRECT*/) {
923 } else {
926 }
927}
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
static bool isRemainingExpressionComplex(const DIExpressionCursor &ExprCursor)
Return whether the rest of the expression needs the complex register path.
static bool isMemoryLocation(DIExpressionCursor ExprCursor)
Assuming a well-formed expression, match "DW_OP_deref* DW_OP_LLVM_fragment?
This file contains constants used for implementing Dwarf debug support.
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
This file implements the SmallBitVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
APInt bitcastToAPInt() const
Definition APFloat.h:1475
Class for arbitrary precision integers.
Definition APInt.h:78
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
LLVM_ABI APInt byteSwap() const
Definition APInt.cpp:764
LLVM_ABI APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
Definition APInt.cpp:478
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
unsigned getIndex(const MCSymbol *Sym, bool TLS=false)
Returns the index into the address pool with the given label/symbol.
This class is intended to be used as a driving class for all asm writers.
Definition AsmPrinter.h:91
const DataLayout & getDataLayout() const
Return information about data layout.
This is an important base class in LLVM.
Definition Constant.h:43
Holds a DIExpression and keeps track of how many operands have been consumed so far.
std::optional< DIExpression::ExprOperand > peekNext() const
Return the next operation.
std::optional< DIExpression::FragmentInfo > getFragmentInfo() const
Retrieve the fragment information, if any.
std::optional< DIExpression::ExprOperand > peek() const
Return the current operation.
void consume(unsigned N)
Consume N operations.
std::optional< DIExpression::ExprOperand > take()
Consume one operation.
A lightweight wrapper around an expression operand.
DWARF expression.
LLVM_ABI bool isEntryValue() const
Check if the expression consists of exactly one entry value operand.
bool isFragment() const
Return whether this is a piece of an aggregate variable.
static LLVM_ABI std::optional< FragmentInfo > getFragmentInfo(expr_op_iterator Start, expr_op_iterator End)
Retrieve the details of this fragment expression.
bool isBigEndian() const
Definition DataLayout.h:218
Collects and handles dwarf debug information.
Definition DwarfDebug.h:352
AddressPool & getAddressPool()
Definition DwarfDebug.h:927
virtual void emitRelocatedAddress(const MCSymbol *Sym)
Emit a relocated address operand.
void addAnd(unsigned Mask)
Emit a bitwise and dwarf operation.
void setLocation(const MachineLocation &Loc, const DIExpression *DIExpr)
Set the location (Loc) and DIExpression (DIExpr) to describe.
bool canAddGlobalAddress() const
Whether addGlobalAddress() can spell a global's address at all.
virtual void emitOp(uint8_t Op, const char *Comment=nullptr)=0
Output a dwarf operand and an optional assembler comment.
virtual void disableTemporaryBuffer()=0
Disable emission to the temporary buffer.
bool isUnknownLocation() const
virtual unsigned getTemporaryBufferSize()=0
Return the emitted size, in number of bytes, for the data stored in the temporary buffer.
uint64_t OffsetInBits
Current Fragment Offset in Bits.
virtual bool isFrameRegister(const TargetRegisterInfo &TRI, llvm::Register MachineReg)=0
Return whether the given machine register is the frame register in the current function.
bool addGlobalAddress(const GlobalValue *GV, int64_t Offset)
Emit the address of GV displaced by Offset as an implicit location description, i....
void finalize()
This needs to be called last to commit any pending changes.
void addFragmentOffset(const DIExpression *Expr)
If applicable, emit an empty DW_OP_piece / DW_OP_bit_piece to advance to the fragment described by Ex...
void emitLegacySExt(unsigned FromBits)
void cancelEntryValue()
Cancel the emission of an entry value.
bool isRegisterLocation() const
void setMemoryLocationKind()
Lock this down to become a memory location description.
virtual void emitBaseTypeRef(uint64_t Idx)=0
virtual void emitData1(uint8_t Value)=0
bool addMachineReg(const TargetRegisterInfo &TRI, llvm::Register MachineReg, unsigned MaxSize=~1U)
Emit a partial DWARF register operation.
bool addExpression(DIExpressionCursor &&Expr)
Emit all remaining operations in the DIExpressionCursor.
std::optional< uint8_t > TagOffset
bool isImplicitLocation() const
virtual bool supportsRelocatedAddress() const
Whether a relocated address operand, as needed by DW_OP_addr, can be emitted into this output form.
virtual void emitUnsigned(uint64_t Value)=0
Emit a raw unsigned value.
void addBooleanConstant(int64_t Value)
Emit a boolean constant.
void addConstantFP(const APFloat &Value, const AsmPrinter &AP)
Emit an floating point constant.
void maskSubRegister()
Emit shift/mask operations for the pending subregister.
SmallVector< Register, 2 > DwarfRegs
The register location, if any.
bool addMachineRegExpression(const TargetRegisterInfo &TRI, DIExpressionCursor &Expr, llvm::Register MachineReg, unsigned FragmentOffsetInBits=0)
Emit a machine register location.
void addStackValue()
Emit a DW_OP_stack_value, if supported.
bool usesAddressPool() const
Whether a global's address is spelled through the address pool, whose index is plain data,...
void finalizeEntryValue()
Finalize an entry value by emitting its size operand, and committing the DWARF block which has been e...
bool isMemoryLocation() const
void addUnsignedConstant(uint64_t Value)
Emit an unsigned constant.
unsigned SubRegisterSizeInBits
Sometimes we need to add a DW_OP_bit_piece to describe a subregister.
void addFBReg(int64_t Offset)
Emit DW_OP_fbreg <Offset>.
void setSubRegisterPiece(unsigned SizeInBits, unsigned OffsetInBits)
Push a DW_OP_piece / DW_OP_bit_piece for emitting later, if one is needed to represent a subregister.
unsigned getOrCreateBaseType(unsigned BitSize, dwarf::TypeKind Encoding)
Return the index of a base type with the given properties and create one if necessary.
void addImplicitValue(const APInt &Value, const AsmPrinter &AP)
Emit an implicit value.
void addSignedConstant(int64_t Value)
Emit a signed constant.
void emitLegacyZExt(unsigned FromBits)
bool IsEmittingEntryValue
Whether we are currently emitting an entry value operation.
virtual void emitSigned(int64_t Value)=0
Emit a raw signed value.
void addReg(int64_t DwarfReg, const char *Comment=nullptr)
Emit a DW_OP_reg operation.
void setEntryValueFlags(const MachineLocation &Loc)
Lock this down to become an entry value location.
virtual void commitTemporaryBuffer()=0
Commit the data stored in the temporary buffer to the main output.
void addShr(unsigned ShiftBy)
Emit a shift-right dwarf operation.
void addWasmLocation(unsigned Index, uint64_t Offset)
Emit location information expressed via WebAssembly location + offset The Index is an identifier for ...
virtual void enableTemporaryBuffer()=0
Start emitting data to the temporary buffer.
void emitConstu(uint64_t Value)
Emit a normalized unsigned constant.
void beginEntryValueExpression(DIExpressionCursor &ExprCursor)
Begin emission of an entry value dwarf operation.
void addOpPiece(unsigned SizeInBits, unsigned OffsetInBits=0)
Emit a DW_OP_piece or DW_OP_bit_piece operation for a variable fragment.
void addBReg(int64_t DwarfReg, int64_t Offset)
Emit a DW_OP_breg operation.
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
SmallBitVector & set()
bool subsetOf(const SmallBitVector &RHS) const
Check if This is a subset of RHS.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
LLVM Value Representation.
Definition Value.h:75
An efficient, type-erasing, non-owning reference to a callable.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ DW_OP_LLVM_implicit_pointer
Only used in LLVM metadata.
Definition Dwarf.h:148
@ DW_OP_LLVM_extract_bits_zext
Only used in LLVM metadata.
Definition Dwarf.h:151
@ DW_OP_LLVM_tag_offset
Only used in LLVM metadata.
Definition Dwarf.h:146
@ DW_OP_LLVM_fragment
Only used in LLVM metadata.
Definition Dwarf.h:144
@ DW_OP_LLVM_arg
Only used in LLVM metadata.
Definition Dwarf.h:149
@ DW_OP_LLVM_convert
Only used in LLVM metadata.
Definition Dwarf.h:145
@ DW_OP_LLVM_extract_bits_sext
Only used in LLVM metadata.
Definition Dwarf.h:150
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
#define N
Holds information about all subregisters comprising a register location.
static Register createRegister(int64_t RegNo, const char *Comment)
Create a full register, no extra DW_OP_piece operators necessary.
static Register createSubRegister(int64_t RegNo, unsigned SizeInBits, const char *Comment)
Create a subregister that needs a DW_OP_piece operator with SizeInBits.