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"
16#include "llvm/ADT/SmallBitVector.h"
17#include "llvm/BinaryFormat/Dwarf.h"
18#include "llvm/CodeGen/Register.h"
19#include "llvm/CodeGen/TargetRegisterInfo.h"
20#include "llvm/IR/DataLayout.h"
21#include "llvm/MC/MCAsmInfo.h"
22#include "llvm/Support/ErrorHandling.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
42void DwarfExpression::emitConstu(uint64_t Value) {
43 if (Value < 32)
44 emitOp(Op: 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(Op: dwarf::DW_OP_lit0);
49 emitOp(Op: dwarf::DW_OP_not);
50 } else {
51 emitOp(Op: dwarf::DW_OP_constu);
52 emitUnsigned(Value);
53 }
54}
55
56void DwarfExpression::addReg(int64_t DwarfReg, const char *Comment) {
57 assert(DwarfReg >= 0 && "invalid negative dwarf register number");
58 assert((isUnknownLocation() || isRegisterLocation()) &&
59 "location description already locked down");
60 LocationKind = Register;
61 if (DwarfReg < 32) {
62 emitOp(Op: dwarf::DW_OP_reg0 + DwarfReg, Comment);
63 } else {
64 emitOp(Op: dwarf::DW_OP_regx, Comment);
65 emitUnsigned(Value: 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(Op: dwarf::DW_OP_breg0 + DwarfReg);
74 } else {
75 emitOp(Op: dwarf::DW_OP_bregx);
76 emitUnsigned(Value: DwarfReg);
77 }
78 emitSigned(Value: Offset);
79}
80
81void DwarfExpression::addFBReg(int64_t Offset) {
82 emitOp(Op: dwarf::DW_OP_fbreg);
83 emitSigned(Value: Offset);
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(Op: dwarf::DW_OP_bit_piece);
93 emitUnsigned(Value: SizeInBits);
94 emitUnsigned(Value: OffsetInBits);
95 } else {
96 emitOp(Op: dwarf::DW_OP_piece);
97 unsigned ByteSize = SizeInBits / SizeOfByte;
98 emitUnsigned(Value: ByteSize);
99 }
100 this->OffsetInBits += SizeInBits;
101}
102
103void DwarfExpression::addShr(unsigned ShiftBy) {
104 emitConstu(Value: ShiftBy);
105 emitOp(Op: dwarf::DW_OP_shr);
106}
107
108void DwarfExpression::addAnd(unsigned Mask) {
109 emitConstu(Value: Mask);
110 emitOp(Op: dwarf::DW_OP_and);
111}
112
113bool DwarfExpression::addMachineReg(const TargetRegisterInfo &TRI,
114 llvm::Register MachineReg,
115 unsigned MaxSize) {
116 if (!MachineReg.isPhysical()) {
117 if (isFrameRegister(TRI, MachineReg)) {
118 DwarfRegs.push_back(Elt: Register::createRegister(RegNo: -1, Comment: nullptr));
119 return true;
120 }
121 // Try getting dwarf register for targets that use virtual registers.
122 int64_t Reg = TRI.getDwarfRegNumForVirtReg(RegNum: MachineReg, isEH: false);
123 if (Reg > 0) {
124 DwarfRegs.push_back(Elt: Register::createRegister(RegNo: Reg, Comment: nullptr));
125 return true;
126 }
127 return false;
128 }
129
130 int64_t Reg = TRI.getDwarfRegNum(Reg: MachineReg, isEH: false);
131
132 // If this is a valid register number, emit it.
133 if (Reg >= 0) {
134 DwarfRegs.push_back(Elt: Register::createRegister(RegNo: Reg, Comment: 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(Elt: Register::createRegister(RegNo: -1, Comment: 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(Reg: MachineReg)) {
148 Reg = TRI.getDwarfRegNum(Reg: SR, isEH: false);
149 if (Reg >= 0) {
150 unsigned Idx = TRI.getSubRegIndex(RegNo: SR, SubRegNo: MachineReg);
151 unsigned Size = TRI.getSubRegIdxSize(Idx);
152 unsigned RegOffset = TRI.getSubRegIdxOffset(Idx);
153 DwarfRegs.push_back(Elt: Register::createRegister(RegNo: Reg, Comment: "super-register"));
154 // Use a DW_OP_bit_piece to describe the sub-register.
155 setSubRegisterPiece(SizeInBits: Size, OffsetInBits: 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(Reg: MachineReg);
165 unsigned RegSize = TRI.getRegSizeInBits(RC: *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(Reg: MachineReg)) {
173 unsigned Idx = TRI.getSubRegIndex(RegNo: MachineReg, SubRegNo: SR);
174 unsigned Size = TRI.getSubRegIdxSize(Idx);
175 unsigned Offset = TRI.getSubRegIdxOffset(Idx);
176 Reg = TRI.getDwarfRegNum(Reg: SR, isEH: false);
177 if (Reg < 0 || Offset + Size > RegSize)
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(I: Offset, E: 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(RHS: Coverage)) {
188 // Emit a piece for any gap in the coverage.
189 if (Offset > CurPos)
190 DwarfRegs.push_back(Elt: Register::createSubRegister(
191 RegNo: -1, SizeInBits: Offset - CurPos, Comment: "no DWARF register encoding"));
192 if (Offset == 0 && Size >= MaxSize)
193 DwarfRegs.push_back(Elt: Register::createRegister(RegNo: Reg, Comment: "sub-register"));
194 else
195 DwarfRegs.push_back(Elt: Register::createSubRegister(
196 RegNo: Reg, SizeInBits: std::min<unsigned>(a: Size, b: MaxSize - Offset), Comment: "sub-register"));
197 }
198 // Mark it as emitted.
199 Coverage.set(I: Offset, E: 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)
207 DwarfRegs.push_back(Elt: Register::createSubRegister(
208 RegNo: -1, SizeInBits: RegSize - CurPos, Comment: "no DWARF register encoding"));
209 return true;
210}
211
212void DwarfExpression::addStackValue() {
213 if (DwarfVersion >= 4)
214 emitOp(Op: dwarf::DW_OP_stack_value);
215}
216
217void DwarfExpression::addBooleanConstant(int64_t Value) {
218 assert(isImplicitLocation() || isUnknownLocation());
219 LocationKind = Implicit;
220 if (Value == 0)
221 emitOp(Op: dwarf::DW_OP_lit0);
222 else
223 emitOp(Op: dwarf::DW_OP_lit1);
224}
225
226void DwarfExpression::addSignedConstant(int64_t Value) {
227 assert(isImplicitLocation() || isUnknownLocation());
228 LocationKind = Implicit;
229 emitOp(Op: dwarf::DW_OP_consts);
230 emitSigned(Value);
231}
232
233void DwarfExpression::addUnsignedConstant(uint64_t Value) {
234 assert(isImplicitLocation() || isUnknownLocation());
235 LocationKind = Implicit;
236 emitConstu(Value);
237}
238
239void DwarfExpression::addUnsignedConstant(const APInt &Value) {
240 assert(isImplicitLocation() || isUnknownLocation());
241 LocationKind = Implicit;
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) {
250 addUnsignedConstant(Value: *Data++);
251 if (Offset == 0 && Size <= 64)
252 break;
253 addStackValue();
254 addOpPiece(SizeInBits: std::min(a: Size - Offset, b: 64u), OffsetInBits: Offset);
255 Offset += 64;
256 }
257}
258
259void DwarfExpression::addImplicitValue(const APInt &Value,
260 const AsmPrinter &AP) {
261 assert(isImplicitLocation() || isUnknownLocation());
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(Op: dwarf::DW_OP_implicit_value);
270 emitUnsigned(Value: 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(Value: API.extractBits(numBits: 8, bitPosition: I * 8).getZExtValue());
279}
280
281void DwarfExpression::addConstantFP(const APFloat &APF, const AsmPrinter &AP) {
282 assert(isImplicitLocation() || isUnknownLocation());
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(Op: dwarf::DW_OP_implicit_value);
288 emitUnsigned(Value: 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(Value: API.getZExtValue() & 0xFF);
298 API = API.lshr(shiftAmt: 8);
299 }
300
301 return;
302 }
303 LLVM_DEBUG(
304 dbgs() << "Skipped DW_OP_implicit_value creation for ConstantFP of size: "
305 << API.getBitWidth() << " bits\n");
306}
307
308bool DwarfExpression::addMachineRegExpression(const TargetRegisterInfo &TRI,
309 DIExpressionCursor &ExprCursor,
310 llvm::Register MachineReg,
311 unsigned FragmentOffsetInBits) {
312 auto Fragment = ExprCursor.getFragmentInfo();
313 if (!addMachineReg(TRI, MachineReg, MaxSize: Fragment ? Fragment->SizeInBits : ~1U)) {
314 LocationKind = Unknown;
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) {
332 if (IsEmittingEntryValue)
333 cancelEntryValue();
334 DwarfRegs.clear();
335 LocationKind = Unknown;
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(DwarfReg: Reg.DwarfRegNo, Comment: 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(SizeInBits: Reg.SubRegSize);
355 }
356
357 if (isEntryValue()) {
358 finalizeEntryValue();
359
360 if (!isIndirect() && !isParameterValue() && !HasComplexExpression &&
361 DwarfVersion >= 4)
362 emitOp(Op: 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.
368 if (SubRegisterSizeInBits && isRemainingExpressionComplex(ExprCursor))
369 maskSubRegister();
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(Range&: ExprCursor, P: [](DIExpression::ExprOperand Op) -> bool {
376 return Op.getOp() == dwarf::DW_OP_stack_value;
377 })) {
378 DwarfRegs.clear();
379 LocationKind = Unknown;
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();
389 LocationKind = Unknown;
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()) {
397 auto Tag = dyn_cast<DIExpression::TagOffsetOp>(Val&: *Op);
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].
414 if (auto PlusUconst = dyn_cast<DIExpression::PlusUconstOp>(Val&: *Op)) {
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>(Val&: *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(N: 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(N: 2);
433 }
434 }
435 }
436
437 if (isFrameRegister(TRI, MachineReg))
438 addFBReg(Offset: SignedOffset);
439 else
440 addBReg(DwarfReg: Reg.DwarfRegNo, Offset: 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.
445 if (SubRegisterSizeInBits && isRemainingExpressionComplex(ExprCursor))
446 maskSubRegister();
447
448 return true;
449}
450
451void DwarfExpression::setEntryValueFlags(const MachineLocation &Loc) {
452 LocationFlags |= EntryValue;
453 if (Loc.isIndirect())
454 LocationFlags |= Indirect;
455}
456
457void DwarfExpression::setLocation(const MachineLocation &Loc,
458 const DIExpression *DIExpr) {
459 if (Loc.isIndirect())
460 setMemoryLocationKind();
461
462 if (DIExpr->isEntryValue())
463 setEntryValueFlags(Loc);
464}
465
466void DwarfExpression::beginEntryValueExpression(
467 DIExpressionCursor &ExprCursor) {
468 auto Op = ExprCursor.take();
469 (void)Op;
470 assert(Op && isa<DIExpression::EntryValueOp>(*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
475 SavedLocationKind = LocationKind;
476 LocationKind = Register;
477 LocationFlags |= EntryValue;
478 IsEmittingEntryValue = true;
479 enableTemporaryBuffer();
480}
481
482void DwarfExpression::finalizeEntryValue() {
483 assert(IsEmittingEntryValue && "Entry value not open?");
484 disableTemporaryBuffer();
485
486 emitOp(Op: CU.getDwarf5OrGNULocationAtom(Loc: dwarf::DW_OP_entry_value));
487
488 // Emit the entry value's size operand.
489 unsigned Size = getTemporaryBufferSize();
490 emitUnsigned(Value: Size);
491
492 // Emit the entry value's DWARF block operand.
493 commitTemporaryBuffer();
494
495 LocationFlags &= ~EntryValue;
496 LocationKind = SavedLocationKind;
497 IsEmittingEntryValue = false;
498}
499
500void DwarfExpression::cancelEntryValue() {
501 assert(IsEmittingEntryValue && "Entry value not open?");
502 disableTemporaryBuffer();
503
504 // The temporary buffer can't be emptied, so for now just assert that nothing
505 // has been emitted to it.
506 assert(getTemporaryBufferSize() == 0 &&
507 "Began emitting entry value block before cancelling entry value");
508
509 LocationKind = SavedLocationKind;
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(args&: BitSize, args&: 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:
535 case dwarf::DW_OP_LLVM_fragment:
536 break;
537 default:
538 return false;
539 }
540 }
541 return true;
542}
543
544void DwarfExpression::addExpression(DIExpressionCursor &&ExprCursor) {
545 addExpression(Expr: std::move(ExprCursor),
546 InsertArg: [](unsigned Idx, DIExpressionCursor &Cursor) -> bool {
547 llvm_unreachable("unhandled opcode found in expression");
548 });
549}
550
551bool DwarfExpression::addExpression(
552 DIExpressionCursor &&ExprCursor,
553 llvm::function_ref<bool(unsigned, DIExpressionCursor &)> InsertArg) {
554 // Entry values can currently only cover the initial register location,
555 // and not any other parts of the following DWARF expression.
556 assert(!IsEmittingEntryValue && "Can't emit entry value around expression");
557
558 std::optional<DIExpression::ConvertOp> PrevConvertOp;
559
560 while (ExprCursor) {
561 auto Op = ExprCursor.take();
562 uint64_t OpNum = Op->getOp();
563
564 if (OpNum >= dwarf::DW_OP_reg0 && OpNum <= dwarf::DW_OP_reg31) {
565 emitOp(Op: OpNum);
566 continue;
567 } else if (OpNum >= dwarf::DW_OP_breg0 && OpNum <= dwarf::DW_OP_breg31) {
568 addBReg(DwarfReg: OpNum - dwarf::DW_OP_breg0, Offset: Op->getArg(I: 0));
569 continue;
570 }
571
572 switch (OpNum) {
573 case dwarf::DW_OP_LLVM_arg:
574 if (!InsertArg(cast<DIExpression::ArgOp>(Val&: *Op).getIndex(), ExprCursor)) {
575 LocationKind = Unknown;
576 return false;
577 }
578 break;
579 case dwarf::DW_OP_LLVM_fragment: {
580 auto Fragment = cast<DIExpression::FragmentOp>(Val&: *Op);
581 unsigned SizeInBits = Fragment.getSizeInBits();
582 unsigned FragmentOffset = Fragment.getOffsetInBits();
583 // The fragment offset must have already been adjusted by emitting an
584 // empty DW_OP_piece / DW_OP_bit_piece before we emitted the base
585 // location.
586 assert(OffsetInBits >= FragmentOffset && "fragment offset not added?");
587 assert(SizeInBits >= OffsetInBits - FragmentOffset && "size underflow");
588
589 // If addMachineReg already emitted DW_OP_piece operations to represent
590 // a super-register by splicing together sub-registers, subtract the size
591 // of the pieces that was already emitted.
592 SizeInBits -= OffsetInBits - FragmentOffset;
593
594 // If addMachineReg requested a DW_OP_bit_piece to stencil out a
595 // sub-register that is smaller than the current fragment's size, use it.
596 if (SubRegisterSizeInBits)
597 SizeInBits = std::min<unsigned>(a: SizeInBits, b: SubRegisterSizeInBits);
598
599 // Emit a DW_OP_stack_value for implicit location descriptions.
600 if (isImplicitLocation())
601 addStackValue();
602
603 // Emit the DW_OP_piece.
604 addOpPiece(SizeInBits, OffsetInBits: SubRegisterOffsetInBits);
605 setSubRegisterPiece(SizeInBits: 0, OffsetInBits: 0);
606 // Reset the location description kind.
607 LocationKind = Unknown;
608 return true;
609 }
610 case dwarf::DW_OP_LLVM_extract_bits_sext:
611 case dwarf::DW_OP_LLVM_extract_bits_zext: {
612 auto Extract = cast<DIExpression::ExtractBitsOp>(Val&: *Op);
613 unsigned SizeInBits = Extract.getSizeInBits();
614 unsigned BitOffset = Extract.getOffsetInBits();
615 bool IsSigned = Extract.isSigned();
616 unsigned DerefSize = 0;
617 // Operations are done in the DWARF "generic type" whose size
618 // is the size of a pointer.
619 unsigned PtrSizeInBytes = CU.getAsmPrinter()->MAI.getCodePointerSize();
620
621 // If we have a memory location then dereference to get the value, though
622 // we have to make sure we don't dereference any bytes past the end of the
623 // object.
624 if (isMemoryLocation()) {
625 DerefSize = alignTo(Value: BitOffset + SizeInBits, Align: 8) / 8;
626 if (DerefSize == PtrSizeInBytes) {
627 emitOp(Op: dwarf::DW_OP_deref);
628 } else {
629 emitOp(Op: dwarf::DW_OP_deref_size);
630 emitUnsigned(Value: DerefSize);
631 }
632 }
633
634 // If a dereference was emitted for an unsigned value, and
635 // there's no bit offset, then a bit of optimization is
636 // possible.
637 if (!IsSigned && BitOffset == 0) {
638 if (8 * DerefSize == SizeInBits) {
639 // The correct value is already on the stack.
640 } else {
641 // No need to shift, we can just mask off the desired bits.
642 emitOp(Op: dwarf::DW_OP_constu);
643 emitUnsigned(Value: (1u << SizeInBits) - 1);
644 emitOp(Op: dwarf::DW_OP_and);
645 }
646 } else {
647 // Extract the bits by a shift left (to shift out the bits after what we
648 // want to extract) followed by shift right (to shift the bits to
649 // position 0 and also sign/zero extend).
650 unsigned LeftShift = PtrSizeInBytes * 8 - (SizeInBits + BitOffset);
651 unsigned RightShift = LeftShift + BitOffset;
652 if (LeftShift) {
653 emitOp(Op: dwarf::DW_OP_constu);
654 emitUnsigned(Value: LeftShift);
655 emitOp(Op: dwarf::DW_OP_shl);
656 }
657 if (RightShift) {
658 emitOp(Op: dwarf::DW_OP_constu);
659 emitUnsigned(Value: RightShift);
660 emitOp(Op: IsSigned ? dwarf::DW_OP_shra : dwarf::DW_OP_shr);
661 }
662 }
663
664 // The value is now at the top of the stack, so set the location to
665 // implicit so that we get a stack_value at the end.
666 LocationKind = Implicit;
667 break;
668 }
669 case dwarf::DW_OP_plus_uconst:
670 assert(!isRegisterLocation());
671 emitOp(Op: dwarf::DW_OP_plus_uconst);
672 emitUnsigned(Value: cast<DIExpression::PlusUconstOp>(Val&: *Op).getOffset());
673 break;
674 case dwarf::DW_OP_plus:
675 case dwarf::DW_OP_minus:
676 case dwarf::DW_OP_mul:
677 case dwarf::DW_OP_div:
678 case dwarf::DW_OP_mod:
679 case dwarf::DW_OP_or:
680 case dwarf::DW_OP_and:
681 case dwarf::DW_OP_xor:
682 case dwarf::DW_OP_shl:
683 case dwarf::DW_OP_shr:
684 case dwarf::DW_OP_shra:
685 case dwarf::DW_OP_lit0:
686 case dwarf::DW_OP_not:
687 case dwarf::DW_OP_dup:
688 case dwarf::DW_OP_push_object_address:
689 case dwarf::DW_OP_over:
690 case dwarf::DW_OP_rot:
691 case dwarf::DW_OP_eq:
692 case dwarf::DW_OP_ne:
693 case dwarf::DW_OP_gt:
694 case dwarf::DW_OP_ge:
695 case dwarf::DW_OP_lt:
696 case dwarf::DW_OP_le:
697 case dwarf::DW_OP_neg:
698 case dwarf::DW_OP_abs:
699 emitOp(Op: OpNum);
700 break;
701 case dwarf::DW_OP_deref:
702 assert(!isRegisterLocation());
703 if (!isMemoryLocation() && ::isMemoryLocation(ExprCursor))
704 // Turning this into a memory location description makes the deref
705 // implicit.
706 LocationKind = Memory;
707 else
708 emitOp(Op: dwarf::DW_OP_deref);
709 break;
710 case dwarf::DW_OP_constu:
711 assert(!isRegisterLocation());
712 emitConstu(Value: cast<DIExpression::ConstuOp>(Val&: *Op).getValue());
713 break;
714 case dwarf::DW_OP_consts:
715 assert(!isRegisterLocation());
716 emitOp(Op: dwarf::DW_OP_consts);
717 emitSigned(Value: Op->getArg(I: 0));
718 break;
719 case dwarf::DW_OP_LLVM_convert: {
720 auto Convert = cast<DIExpression::ConvertOp>(Val&: *Op);
721 unsigned BitSize = Convert.getBitSize();
722 dwarf::TypeKind Encoding =
723 static_cast<dwarf::TypeKind>(Convert.getEncoding());
724 if (DwarfVersion >= 5 && CU.getDwarfDebug().useOpConvert()) {
725 emitOp(Op: dwarf::DW_OP_convert);
726 // If targeting a location-list; simply emit the index into the raw
727 // byte stream as ULEB128, DwarfDebug::emitDebugLocEntry has been
728 // fitted with means to extract it later.
729 // If targeting a inlined DW_AT_location; insert a DIEBaseTypeRef
730 // (containing the index and a resolve mechanism during emit) into the
731 // DIE value list.
732 emitBaseTypeRef(Idx: getOrCreateBaseType(BitSize, Encoding));
733 } else {
734 if (PrevConvertOp && PrevConvertOp->getBitSize() < BitSize) {
735 if (Encoding == dwarf::DW_ATE_signed)
736 emitLegacySExt(FromBits: PrevConvertOp->getBitSize());
737 else if (Encoding == dwarf::DW_ATE_unsigned)
738 emitLegacyZExt(FromBits: PrevConvertOp->getBitSize());
739 PrevConvertOp = std::nullopt;
740 } else {
741 PrevConvertOp = Convert;
742 }
743 }
744 break;
745 }
746 case dwarf::DW_OP_stack_value:
747 LocationKind = Implicit;
748 break;
749 case dwarf::DW_OP_swap:
750 assert(!isRegisterLocation());
751 emitOp(Op: dwarf::DW_OP_swap);
752 break;
753 case dwarf::DW_OP_xderef:
754 assert(!isRegisterLocation());
755 emitOp(Op: dwarf::DW_OP_xderef);
756 break;
757 case dwarf::DW_OP_deref_size:
758 emitOp(Op: dwarf::DW_OP_deref_size);
759 emitData1(Value: Op->getArg(I: 0));
760 break;
761 case dwarf::DW_OP_LLVM_tag_offset:
762 TagOffset = cast<DIExpression::TagOffsetOp>(Val&: *Op).getTagOffset();
763 break;
764 case dwarf::DW_OP_regx:
765 emitOp(Op: dwarf::DW_OP_regx);
766 emitUnsigned(Value: Op->getArg(I: 0));
767 break;
768 case dwarf::DW_OP_bregx:
769 emitOp(Op: dwarf::DW_OP_bregx);
770 emitUnsigned(Value: Op->getArg(I: 0));
771 emitSigned(Value: Op->getArg(I: 1));
772 break;
773 case dwarf::DW_OP_LLVM_implicit_pointer:
774 // Handled in DwarfCompileUnit::emitImplicitPointerLocation for
775 // Loc::Single variables. If we reach here, the variable has a
776 // location list or other unsupported path. Drop the
777 // location rather than crashing.
778 return false;
779 default:
780 llvm_unreachable("unhandled opcode found in expression");
781 }
782 }
783
784 if (isImplicitLocation() && !isParameterValue())
785 // Turn this into an implicit location description.
786 addStackValue();
787
788 return true;
789}
790
791/// Emit shift/mask operations for the pending subregister. After the operations
792/// are emitted, consume the pending subregister description by clearing
793/// SubRegisterSizeInBits and SubRegisterOffsetInBits.
794void DwarfExpression::maskSubRegister() {
795 assert(SubRegisterSizeInBits && "no subregister was registered");
796 if (SubRegisterOffsetInBits > 0)
797 addShr(ShiftBy: SubRegisterOffsetInBits);
798 uint64_t Mask = (1ULL << (uint64_t)SubRegisterSizeInBits) - 1ULL;
799 addAnd(Mask);
800 // The mask consumes the pending subregister description.
801 setSubRegisterPiece(SizeInBits: 0, OffsetInBits: 0);
802}
803
804void DwarfExpression::finalize() {
805 assert(DwarfRegs.size() == 0 && "dwarf registers not emitted");
806 // Emit any outstanding DW_OP_piece operations to mask out subregisters.
807 if (SubRegisterSizeInBits == 0)
808 return;
809 // Don't emit a DW_OP_piece for a subregister at offset 0.
810 if (SubRegisterOffsetInBits == 0)
811 return;
812 addOpPiece(SizeInBits: SubRegisterSizeInBits, OffsetInBits: SubRegisterOffsetInBits);
813}
814
815void DwarfExpression::addFragmentOffset(const DIExpression *Expr) {
816 if (!Expr || !Expr->isFragment())
817 return;
818
819 uint64_t FragmentOffset = Expr->getFragmentInfo()->OffsetInBits;
820 assert(FragmentOffset >= OffsetInBits &&
821 "overlapping or duplicate fragments");
822 if (FragmentOffset > OffsetInBits)
823 addOpPiece(SizeInBits: FragmentOffset - OffsetInBits);
824 OffsetInBits = FragmentOffset;
825}
826
827void DwarfExpression::emitLegacySExt(unsigned FromBits) {
828 // (((X >> (FromBits - 1)) * (~0)) << FromBits) | X
829 emitOp(Op: dwarf::DW_OP_dup);
830 emitOp(Op: dwarf::DW_OP_constu);
831 emitUnsigned(Value: FromBits - 1);
832 emitOp(Op: dwarf::DW_OP_shr);
833 emitOp(Op: dwarf::DW_OP_lit0);
834 emitOp(Op: dwarf::DW_OP_not);
835 emitOp(Op: dwarf::DW_OP_mul);
836 emitOp(Op: dwarf::DW_OP_constu);
837 emitUnsigned(Value: FromBits);
838 emitOp(Op: dwarf::DW_OP_shl);
839 emitOp(Op: dwarf::DW_OP_or);
840}
841
842void DwarfExpression::emitLegacyZExt(unsigned FromBits) {
843 // Heuristic to decide the most efficient encoding.
844 // A ULEB can encode 7 1-bits per byte.
845 if (FromBits / 7 < 1+1+1+1+1) {
846 // (X & (1 << FromBits - 1))
847 emitOp(Op: dwarf::DW_OP_constu);
848 emitUnsigned(Value: (1ULL << FromBits) - 1);
849 } else {
850 // Note that the DWARF 4 stack consists of pointer-sized elements,
851 // so technically it doesn't make sense to shift left more than 64
852 // bits. We leave that for the consumer to decide though. LLDB for
853 // example uses APInt for the stack elements and can still deal
854 // with this.
855 emitOp(Op: dwarf::DW_OP_lit1);
856 emitOp(Op: dwarf::DW_OP_constu);
857 emitUnsigned(Value: FromBits);
858 emitOp(Op: dwarf::DW_OP_shl);
859 emitOp(Op: dwarf::DW_OP_lit1);
860 emitOp(Op: dwarf::DW_OP_minus);
861 }
862 emitOp(Op: dwarf::DW_OP_and);
863}
864
865void DwarfExpression::addWasmLocation(unsigned Index, uint64_t Offset) {
866 emitOp(Op: dwarf::DW_OP_WASM_location);
867 emitUnsigned(Value: Index == 4/*TI_LOCAL_INDIRECT*/ ? 0/*TI_LOCAL*/ : Index);
868 emitUnsigned(Value: Offset);
869 if (Index == 4 /*TI_LOCAL_INDIRECT*/) {
870 assert(LocationKind == Unknown);
871 LocationKind = Memory;
872 } else {
873 assert(LocationKind == Implicit || LocationKind == Unknown);
874 LocationKind = Implicit;
875 }
876}
877