xref: /llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfExpression.cpp (revision 09b832e74f6c71c2023a3094727bc5c24c639985)
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/Support/ErrorHandling.h"
22 #include <algorithm>
23 
24 using namespace llvm;
25 
26 #define DEBUG_TYPE "dwarfdebug"
27 
28 void DwarfExpression::emitConstu(uint64_t Value) {
29   if (Value < 32)
30     emitOp(dwarf::DW_OP_lit0 + Value);
31   else if (Value == std::numeric_limits<uint64_t>::max()) {
32     // Only do this for 64-bit values as the DWARF expression stack uses
33     // target-address-size values.
34     emitOp(dwarf::DW_OP_lit0);
35     emitOp(dwarf::DW_OP_not);
36   } else {
37     emitOp(dwarf::DW_OP_constu);
38     emitUnsigned(Value);
39   }
40 }
41 
42 void DwarfExpression::addReg(int DwarfReg, const char *Comment) {
43   assert(DwarfReg >= 0 && "invalid negative dwarf register number");
44   assert((isUnknownLocation() || isRegisterLocation()) &&
45          "location description already locked down");
46   LocationKind = Register;
47   if (DwarfReg < 32) {
48     emitOp(dwarf::DW_OP_reg0 + DwarfReg, Comment);
49   } else {
50     emitOp(dwarf::DW_OP_regx, Comment);
51     emitUnsigned(DwarfReg);
52   }
53 }
54 
55 void DwarfExpression::addBReg(int DwarfReg, int Offset) {
56   assert(DwarfReg >= 0 && "invalid negative dwarf register number");
57   assert(!isRegisterLocation() && "location description already locked down");
58   if (DwarfReg < 32) {
59     emitOp(dwarf::DW_OP_breg0 + DwarfReg);
60   } else {
61     emitOp(dwarf::DW_OP_bregx);
62     emitUnsigned(DwarfReg);
63   }
64   emitSigned(Offset);
65 }
66 
67 void DwarfExpression::addFBReg(int Offset) {
68   emitOp(dwarf::DW_OP_fbreg);
69   emitSigned(Offset);
70 }
71 
72 void DwarfExpression::addOpPiece(unsigned SizeInBits, unsigned OffsetInBits) {
73   if (!SizeInBits)
74     return;
75 
76   const unsigned SizeOfByte = 8;
77   if (OffsetInBits > 0 || SizeInBits % SizeOfByte) {
78     emitOp(dwarf::DW_OP_bit_piece);
79     emitUnsigned(SizeInBits);
80     emitUnsigned(OffsetInBits);
81   } else {
82     emitOp(dwarf::DW_OP_piece);
83     unsigned ByteSize = SizeInBits / SizeOfByte;
84     emitUnsigned(ByteSize);
85   }
86   this->OffsetInBits += SizeInBits;
87 }
88 
89 void DwarfExpression::addShr(unsigned ShiftBy) {
90   emitConstu(ShiftBy);
91   emitOp(dwarf::DW_OP_shr);
92 }
93 
94 void DwarfExpression::addAnd(unsigned Mask) {
95   emitConstu(Mask);
96   emitOp(dwarf::DW_OP_and);
97 }
98 
99 bool DwarfExpression::addMachineReg(const TargetRegisterInfo &TRI,
100                                     llvm::Register MachineReg,
101                                     unsigned MaxSize) {
102   if (!llvm::Register::isPhysicalRegister(MachineReg)) {
103     if (isFrameRegister(TRI, MachineReg)) {
104       DwarfRegs.push_back(Register::createRegister(-1, nullptr));
105       return true;
106     }
107     return false;
108   }
109 
110   int Reg = TRI.getDwarfRegNum(MachineReg, false);
111 
112   // If this is a valid register number, emit it.
113   if (Reg >= 0) {
114     DwarfRegs.push_back(Register::createRegister(Reg, nullptr));
115     return true;
116   }
117 
118   // Walk up the super-register chain until we find a valid number.
119   // For example, EAX on x86_64 is a 32-bit fragment of RAX with offset 0.
120   for (MCSuperRegIterator SR(MachineReg, &TRI); SR.isValid(); ++SR) {
121     Reg = TRI.getDwarfRegNum(*SR, false);
122     if (Reg >= 0) {
123       unsigned Idx = TRI.getSubRegIndex(*SR, MachineReg);
124       unsigned Size = TRI.getSubRegIdxSize(Idx);
125       unsigned RegOffset = TRI.getSubRegIdxOffset(Idx);
126       DwarfRegs.push_back(Register::createRegister(Reg, "super-register"));
127       // Use a DW_OP_bit_piece to describe the sub-register.
128       setSubRegisterPiece(Size, RegOffset);
129       return true;
130     }
131   }
132 
133   // Otherwise, attempt to find a covering set of sub-register numbers.
134   // For example, Q0 on ARM is a composition of D0+D1.
135   unsigned CurPos = 0;
136   // The size of the register in bits.
137   const TargetRegisterClass *RC = TRI.getMinimalPhysRegClass(MachineReg);
138   unsigned RegSize = TRI.getRegSizeInBits(*RC);
139   // Keep track of the bits in the register we already emitted, so we
140   // can avoid emitting redundant aliasing subregs. Because this is
141   // just doing a greedy scan of all subregisters, it is possible that
142   // this doesn't find a combination of subregisters that fully cover
143   // the register (even though one may exist).
144   SmallBitVector Coverage(RegSize, false);
145   for (MCSubRegIterator SR(MachineReg, &TRI); SR.isValid(); ++SR) {
146     unsigned Idx = TRI.getSubRegIndex(MachineReg, *SR);
147     unsigned Size = TRI.getSubRegIdxSize(Idx);
148     unsigned Offset = TRI.getSubRegIdxOffset(Idx);
149     Reg = TRI.getDwarfRegNum(*SR, false);
150     if (Reg < 0)
151       continue;
152 
153     // Used to build the intersection between the bits we already
154     // emitted and the bits covered by this subregister.
155     SmallBitVector CurSubReg(RegSize, false);
156     CurSubReg.set(Offset, Offset + Size);
157 
158     // If this sub-register has a DWARF number and we haven't covered
159     // its range, and its range covers the value, emit a DWARF piece for it.
160     if (Offset < MaxSize && CurSubReg.test(Coverage)) {
161       // Emit a piece for any gap in the coverage.
162       if (Offset > CurPos)
163         DwarfRegs.push_back(Register::createSubRegister(
164             -1, Offset - CurPos, "no DWARF register encoding"));
165       if (Offset == 0 && Size >= MaxSize)
166         DwarfRegs.push_back(Register::createRegister(Reg, "sub-register"));
167       else
168         DwarfRegs.push_back(Register::createSubRegister(
169             Reg, std::min<unsigned>(Size, MaxSize - Offset), "sub-register"));
170     }
171     // Mark it as emitted.
172     Coverage.set(Offset, Offset + Size);
173     CurPos = Offset + Size;
174   }
175   // Failed to find any DWARF encoding.
176   if (CurPos == 0)
177     return false;
178   // Found a partial or complete DWARF encoding.
179   if (CurPos < RegSize)
180     DwarfRegs.push_back(Register::createSubRegister(
181         -1, RegSize - CurPos, "no DWARF register encoding"));
182   return true;
183 }
184 
185 void DwarfExpression::addStackValue() {
186   if (DwarfVersion >= 4)
187     emitOp(dwarf::DW_OP_stack_value);
188 }
189 
190 void DwarfExpression::addSignedConstant(int64_t Value) {
191   assert(isImplicitLocation() || isUnknownLocation());
192   LocationKind = Implicit;
193   emitOp(dwarf::DW_OP_consts);
194   emitSigned(Value);
195 }
196 
197 void DwarfExpression::addUnsignedConstant(uint64_t Value) {
198   assert(isImplicitLocation() || isUnknownLocation());
199   LocationKind = Implicit;
200   emitConstu(Value);
201 }
202 
203 void DwarfExpression::addUnsignedConstant(const APInt &Value) {
204   assert(isImplicitLocation() || isUnknownLocation());
205   LocationKind = Implicit;
206 
207   unsigned Size = Value.getBitWidth();
208   const uint64_t *Data = Value.getRawData();
209 
210   // Chop it up into 64-bit pieces, because that's the maximum that
211   // addUnsignedConstant takes.
212   unsigned Offset = 0;
213   while (Offset < Size) {
214     addUnsignedConstant(*Data++);
215     if (Offset == 0 && Size <= 64)
216       break;
217     addStackValue();
218     addOpPiece(std::min(Size - Offset, 64u), Offset);
219     Offset += 64;
220   }
221 }
222 
223 void DwarfExpression::addConstantFP(const APFloat &APF, const AsmPrinter &AP) {
224   assert(isImplicitLocation() || isUnknownLocation());
225   APInt API = APF.bitcastToAPInt();
226   int NumBytes = API.getBitWidth() / 8;
227   if (NumBytes == 4 /*float*/ || NumBytes == 8 /*double*/) {
228     // FIXME: Add support for `long double`.
229     emitOp(dwarf::DW_OP_implicit_value);
230     emitUnsigned(NumBytes /*Size of the block in bytes*/);
231 
232     // The loop below is emitting the value starting at least significant byte,
233     // so we need to perform a byte-swap to get the byte order correct in case
234     // of a big-endian target.
235     if (AP.getDataLayout().isBigEndian())
236       API = API.byteSwap();
237 
238     for (int i = 0; i < NumBytes; ++i) {
239       emitData1(API.getZExtValue() & 0xFF);
240       API = API.lshr(8);
241     }
242 
243     return;
244   }
245   LLVM_DEBUG(
246       dbgs() << "Skipped DW_OP_implicit_value creation for ConstantFP of size: "
247              << API.getBitWidth() << " bits\n");
248 }
249 
250 bool DwarfExpression::addMachineRegExpression(const TargetRegisterInfo &TRI,
251                                               DIExpressionCursor &ExprCursor,
252                                               llvm::Register MachineReg,
253                                               unsigned FragmentOffsetInBits) {
254   auto Fragment = ExprCursor.getFragmentInfo();
255   if (!addMachineReg(TRI, MachineReg, Fragment ? Fragment->SizeInBits : ~1U)) {
256     LocationKind = Unknown;
257     return false;
258   }
259 
260   bool HasComplexExpression = false;
261   auto Op = ExprCursor.peek();
262   if (Op && Op->getOp() != dwarf::DW_OP_LLVM_fragment)
263     HasComplexExpression = true;
264 
265   // If the register can only be described by a complex expression (i.e.,
266   // multiple subregisters) it doesn't safely compose with another complex
267   // expression. For example, it is not possible to apply a DW_OP_deref
268   // operation to multiple DW_OP_pieces, since composite location descriptions
269   // do not push anything on the DWARF stack.
270   //
271   // DW_OP_entry_value operations can only hold a DWARF expression or a
272   // register location description, so we can't emit a single entry value
273   // covering a composite location description. In the future we may want to
274   // emit entry value operations for each register location in the composite
275   // location, but until that is supported do not emit anything.
276   if ((HasComplexExpression || IsEmittingEntryValue) && DwarfRegs.size() > 1) {
277     if (IsEmittingEntryValue)
278       cancelEntryValue();
279     DwarfRegs.clear();
280     LocationKind = Unknown;
281     return false;
282   }
283 
284   // Handle simple register locations. If we are supposed to emit
285   // a call site parameter expression and if that expression is just a register
286   // location, emit it with addBReg and offset 0, because we should emit a DWARF
287   // expression representing a value, rather than a location.
288   if ((!isParameterValue() && !isMemoryLocation() && !HasComplexExpression) ||
289       isEntryValue()) {
290     for (auto &Reg : DwarfRegs) {
291       if (Reg.DwarfRegNo >= 0)
292         addReg(Reg.DwarfRegNo, Reg.Comment);
293       addOpPiece(Reg.SubRegSize);
294     }
295 
296     if (isEntryValue()) {
297       finalizeEntryValue();
298 
299       if (!isIndirect() && !isParameterValue() && !HasComplexExpression &&
300           DwarfVersion >= 4)
301         emitOp(dwarf::DW_OP_stack_value);
302     }
303 
304     DwarfRegs.clear();
305     return true;
306   }
307 
308   // Don't emit locations that cannot be expressed without DW_OP_stack_value.
309   if (DwarfVersion < 4)
310     if (any_of(ExprCursor, [](DIExpression::ExprOperand Op) -> bool {
311           return Op.getOp() == dwarf::DW_OP_stack_value;
312         })) {
313       DwarfRegs.clear();
314       LocationKind = Unknown;
315       return false;
316     }
317 
318   assert(DwarfRegs.size() == 1);
319   auto Reg = DwarfRegs[0];
320   bool FBReg = isFrameRegister(TRI, MachineReg);
321   int SignedOffset = 0;
322   assert(!Reg.isSubRegister() && "full register expected");
323 
324   // Pattern-match combinations for which more efficient representations exist.
325   // [Reg, DW_OP_plus_uconst, Offset] --> [DW_OP_breg, Offset].
326   if (Op && (Op->getOp() == dwarf::DW_OP_plus_uconst)) {
327     uint64_t Offset = Op->getArg(0);
328     uint64_t IntMax = static_cast<uint64_t>(std::numeric_limits<int>::max());
329     if (Offset <= IntMax) {
330       SignedOffset = Offset;
331       ExprCursor.take();
332     }
333   }
334 
335   // [Reg, DW_OP_constu, Offset, DW_OP_plus]  --> [DW_OP_breg, Offset]
336   // [Reg, DW_OP_constu, Offset, DW_OP_minus] --> [DW_OP_breg,-Offset]
337   // If Reg is a subregister we need to mask it out before subtracting.
338   if (Op && Op->getOp() == dwarf::DW_OP_constu) {
339     uint64_t Offset = Op->getArg(0);
340     uint64_t IntMax = static_cast<uint64_t>(std::numeric_limits<int>::max());
341     auto N = ExprCursor.peekNext();
342     if (N && N->getOp() == dwarf::DW_OP_plus && Offset <= IntMax) {
343       SignedOffset = Offset;
344       ExprCursor.consume(2);
345     } else if (N && N->getOp() == dwarf::DW_OP_minus &&
346                !SubRegisterSizeInBits && Offset <= IntMax + 1) {
347       SignedOffset = -static_cast<int64_t>(Offset);
348       ExprCursor.consume(2);
349     }
350   }
351 
352   if (FBReg)
353     addFBReg(SignedOffset);
354   else
355     addBReg(Reg.DwarfRegNo, SignedOffset);
356   DwarfRegs.clear();
357   return true;
358 }
359 
360 void DwarfExpression::setEntryValueFlags(const MachineLocation &Loc) {
361   LocationFlags |= EntryValue;
362   if (Loc.isIndirect())
363     LocationFlags |= Indirect;
364 }
365 
366 void DwarfExpression::setLocation(const MachineLocation &Loc,
367                                   const DIExpression *DIExpr) {
368   if (Loc.isIndirect())
369     setMemoryLocationKind();
370 
371   if (DIExpr->isEntryValue())
372     setEntryValueFlags(Loc);
373 }
374 
375 void DwarfExpression::beginEntryValueExpression(
376     DIExpressionCursor &ExprCursor) {
377   auto Op = ExprCursor.take();
378   (void)Op;
379   assert(Op && Op->getOp() == dwarf::DW_OP_LLVM_entry_value);
380   assert(!IsEmittingEntryValue && "Already emitting entry value?");
381   assert(Op->getArg(0) == 1 &&
382          "Can currently only emit entry values covering a single operation");
383 
384   SavedLocationKind = LocationKind;
385   LocationKind = Register;
386   IsEmittingEntryValue = true;
387   enableTemporaryBuffer();
388 }
389 
390 void DwarfExpression::finalizeEntryValue() {
391   assert(IsEmittingEntryValue && "Entry value not open?");
392   disableTemporaryBuffer();
393 
394   emitOp(CU.getDwarf5OrGNULocationAtom(dwarf::DW_OP_entry_value));
395 
396   // Emit the entry value's size operand.
397   unsigned Size = getTemporaryBufferSize();
398   emitUnsigned(Size);
399 
400   // Emit the entry value's DWARF block operand.
401   commitTemporaryBuffer();
402 
403   LocationKind = SavedLocationKind;
404   IsEmittingEntryValue = false;
405 }
406 
407 void DwarfExpression::cancelEntryValue() {
408   assert(IsEmittingEntryValue && "Entry value not open?");
409   disableTemporaryBuffer();
410 
411   // The temporary buffer can't be emptied, so for now just assert that nothing
412   // has been emitted to it.
413   assert(getTemporaryBufferSize() == 0 &&
414          "Began emitting entry value block before cancelling entry value");
415 
416   LocationKind = SavedLocationKind;
417   IsEmittingEntryValue = false;
418 }
419 
420 unsigned DwarfExpression::getOrCreateBaseType(unsigned BitSize,
421                                               dwarf::TypeKind Encoding) {
422   // Reuse the base_type if we already have one in this CU otherwise we
423   // create a new one.
424   unsigned I = 0, E = CU.ExprRefedBaseTypes.size();
425   for (; I != E; ++I)
426     if (CU.ExprRefedBaseTypes[I].BitSize == BitSize &&
427         CU.ExprRefedBaseTypes[I].Encoding == Encoding)
428       break;
429 
430   if (I == E)
431     CU.ExprRefedBaseTypes.emplace_back(BitSize, Encoding);
432   return I;
433 }
434 
435 /// Assuming a well-formed expression, match "DW_OP_deref*
436 /// DW_OP_LLVM_fragment?".
437 static bool isMemoryLocation(DIExpressionCursor ExprCursor) {
438   while (ExprCursor) {
439     auto Op = ExprCursor.take();
440     switch (Op->getOp()) {
441     case dwarf::DW_OP_deref:
442     case dwarf::DW_OP_LLVM_fragment:
443       break;
444     default:
445       return false;
446     }
447   }
448   return true;
449 }
450 
451 void DwarfExpression::addExpression(DIExpressionCursor &&ExprCursor,
452                                     unsigned FragmentOffsetInBits) {
453   // Entry values can currently only cover the initial register location,
454   // and not any other parts of the following DWARF expression.
455   assert(!IsEmittingEntryValue && "Can't emit entry value around expression");
456 
457   // If we need to mask out a subregister, do it now, unless the next
458   // operation would emit an OpPiece anyway.
459   auto N = ExprCursor.peek();
460   if (SubRegisterSizeInBits && N && (N->getOp() != dwarf::DW_OP_LLVM_fragment))
461     maskSubRegister();
462 
463   Optional<DIExpression::ExprOperand> PrevConvertOp = None;
464 
465   while (ExprCursor) {
466     auto Op = ExprCursor.take();
467     uint64_t OpNum = Op->getOp();
468 
469     if (OpNum >= dwarf::DW_OP_reg0 && OpNum <= dwarf::DW_OP_reg31) {
470       emitOp(OpNum);
471       continue;
472     } else if (OpNum >= dwarf::DW_OP_breg0 && OpNum <= dwarf::DW_OP_breg31) {
473       addBReg(OpNum - dwarf::DW_OP_breg0, Op->getArg(0));
474       continue;
475     }
476 
477     switch (OpNum) {
478     case dwarf::DW_OP_LLVM_fragment: {
479       unsigned SizeInBits = Op->getArg(1);
480       unsigned FragmentOffset = Op->getArg(0);
481       // The fragment offset must have already been adjusted by emitting an
482       // empty DW_OP_piece / DW_OP_bit_piece before we emitted the base
483       // location.
484       assert(OffsetInBits >= FragmentOffset && "fragment offset not added?");
485       assert(SizeInBits >= OffsetInBits - FragmentOffset && "size underflow");
486 
487       // If addMachineReg already emitted DW_OP_piece operations to represent
488       // a super-register by splicing together sub-registers, subtract the size
489       // of the pieces that was already emitted.
490       SizeInBits -= OffsetInBits - FragmentOffset;
491 
492       // If addMachineReg requested a DW_OP_bit_piece to stencil out a
493       // sub-register that is smaller than the current fragment's size, use it.
494       if (SubRegisterSizeInBits)
495         SizeInBits = std::min<unsigned>(SizeInBits, SubRegisterSizeInBits);
496 
497       // Emit a DW_OP_stack_value for implicit location descriptions.
498       if (isImplicitLocation())
499         addStackValue();
500 
501       // Emit the DW_OP_piece.
502       addOpPiece(SizeInBits, SubRegisterOffsetInBits);
503       setSubRegisterPiece(0, 0);
504       // Reset the location description kind.
505       LocationKind = Unknown;
506       return;
507     }
508     case dwarf::DW_OP_plus_uconst:
509       assert(!isRegisterLocation());
510       emitOp(dwarf::DW_OP_plus_uconst);
511       emitUnsigned(Op->getArg(0));
512       break;
513     case dwarf::DW_OP_plus:
514     case dwarf::DW_OP_minus:
515     case dwarf::DW_OP_mul:
516     case dwarf::DW_OP_div:
517     case dwarf::DW_OP_mod:
518     case dwarf::DW_OP_or:
519     case dwarf::DW_OP_and:
520     case dwarf::DW_OP_xor:
521     case dwarf::DW_OP_shl:
522     case dwarf::DW_OP_shr:
523     case dwarf::DW_OP_shra:
524     case dwarf::DW_OP_lit0:
525     case dwarf::DW_OP_not:
526     case dwarf::DW_OP_dup:
527     case dwarf::DW_OP_push_object_address:
528     case dwarf::DW_OP_over:
529       emitOp(OpNum);
530       break;
531     case dwarf::DW_OP_deref:
532       assert(!isRegisterLocation());
533       if (!isMemoryLocation() && ::isMemoryLocation(ExprCursor))
534         // Turning this into a memory location description makes the deref
535         // implicit.
536         LocationKind = Memory;
537       else
538         emitOp(dwarf::DW_OP_deref);
539       break;
540     case dwarf::DW_OP_constu:
541       assert(!isRegisterLocation());
542       emitConstu(Op->getArg(0));
543       break;
544     case dwarf::DW_OP_consts:
545       assert(!isRegisterLocation());
546       emitOp(dwarf::DW_OP_consts);
547       emitSigned(Op->getArg(0));
548       break;
549     case dwarf::DW_OP_LLVM_convert: {
550       unsigned BitSize = Op->getArg(0);
551       dwarf::TypeKind Encoding = static_cast<dwarf::TypeKind>(Op->getArg(1));
552       if (DwarfVersion >= 5 && CU.getDwarfDebug().useOpConvert()) {
553         emitOp(dwarf::DW_OP_convert);
554         // If targeting a location-list; simply emit the index into the raw
555         // byte stream as ULEB128, DwarfDebug::emitDebugLocEntry has been
556         // fitted with means to extract it later.
557         // If targeting a inlined DW_AT_location; insert a DIEBaseTypeRef
558         // (containing the index and a resolve mechanism during emit) into the
559         // DIE value list.
560         emitBaseTypeRef(getOrCreateBaseType(BitSize, Encoding));
561       } else {
562         if (PrevConvertOp && PrevConvertOp->getArg(0) < BitSize) {
563           if (Encoding == dwarf::DW_ATE_signed)
564             emitLegacySExt(PrevConvertOp->getArg(0));
565           else if (Encoding == dwarf::DW_ATE_unsigned)
566             emitLegacyZExt(PrevConvertOp->getArg(0));
567           PrevConvertOp = None;
568         } else {
569           PrevConvertOp = Op;
570         }
571       }
572       break;
573     }
574     case dwarf::DW_OP_stack_value:
575       LocationKind = Implicit;
576       break;
577     case dwarf::DW_OP_swap:
578       assert(!isRegisterLocation());
579       emitOp(dwarf::DW_OP_swap);
580       break;
581     case dwarf::DW_OP_xderef:
582       assert(!isRegisterLocation());
583       emitOp(dwarf::DW_OP_xderef);
584       break;
585     case dwarf::DW_OP_deref_size:
586       emitOp(dwarf::DW_OP_deref_size);
587       emitData1(Op->getArg(0));
588       break;
589     case dwarf::DW_OP_LLVM_tag_offset:
590       TagOffset = Op->getArg(0);
591       break;
592     case dwarf::DW_OP_regx:
593       emitOp(dwarf::DW_OP_regx);
594       emitUnsigned(Op->getArg(0));
595       break;
596     case dwarf::DW_OP_bregx:
597       emitOp(dwarf::DW_OP_bregx);
598       emitUnsigned(Op->getArg(0));
599       emitSigned(Op->getArg(1));
600       break;
601     default:
602       llvm_unreachable("unhandled opcode found in expression");
603     }
604   }
605 
606   if (isImplicitLocation() && !isParameterValue())
607     // Turn this into an implicit location description.
608     addStackValue();
609 }
610 
611 /// add masking operations to stencil out a subregister.
612 void DwarfExpression::maskSubRegister() {
613   assert(SubRegisterSizeInBits && "no subregister was registered");
614   if (SubRegisterOffsetInBits > 0)
615     addShr(SubRegisterOffsetInBits);
616   uint64_t Mask = (1ULL << (uint64_t)SubRegisterSizeInBits) - 1ULL;
617   addAnd(Mask);
618 }
619 
620 void DwarfExpression::finalize() {
621   assert(DwarfRegs.size() == 0 && "dwarf registers not emitted");
622   // Emit any outstanding DW_OP_piece operations to mask out subregisters.
623   if (SubRegisterSizeInBits == 0)
624     return;
625   // Don't emit a DW_OP_piece for a subregister at offset 0.
626   if (SubRegisterOffsetInBits == 0)
627     return;
628   addOpPiece(SubRegisterSizeInBits, SubRegisterOffsetInBits);
629 }
630 
631 void DwarfExpression::addFragmentOffset(const DIExpression *Expr) {
632   if (!Expr || !Expr->isFragment())
633     return;
634 
635   uint64_t FragmentOffset = Expr->getFragmentInfo()->OffsetInBits;
636   assert(FragmentOffset >= OffsetInBits &&
637          "overlapping or duplicate fragments");
638   if (FragmentOffset > OffsetInBits)
639     addOpPiece(FragmentOffset - OffsetInBits);
640   OffsetInBits = FragmentOffset;
641 }
642 
643 void DwarfExpression::emitLegacySExt(unsigned FromBits) {
644   // (((X >> (FromBits - 1)) * (~0)) << FromBits) | X
645   emitOp(dwarf::DW_OP_dup);
646   emitOp(dwarf::DW_OP_constu);
647   emitUnsigned(FromBits - 1);
648   emitOp(dwarf::DW_OP_shr);
649   emitOp(dwarf::DW_OP_lit0);
650   emitOp(dwarf::DW_OP_not);
651   emitOp(dwarf::DW_OP_mul);
652   emitOp(dwarf::DW_OP_constu);
653   emitUnsigned(FromBits);
654   emitOp(dwarf::DW_OP_shl);
655   emitOp(dwarf::DW_OP_or);
656 }
657 
658 void DwarfExpression::emitLegacyZExt(unsigned FromBits) {
659   // (X & (1 << FromBits - 1))
660   emitOp(dwarf::DW_OP_constu);
661   emitUnsigned((1ULL << FromBits) - 1);
662   emitOp(dwarf::DW_OP_and);
663 }
664 
665 void DwarfExpression::addWasmLocation(unsigned Index, uint64_t Offset) {
666   emitOp(dwarf::DW_OP_WASM_location);
667   emitUnsigned(Index == 4/*TI_LOCAL_INDIRECT*/ ? 0/*TI_LOCAL*/ : Index);
668   emitUnsigned(Offset);
669   if (Index == 4 /*TI_LOCAL_INDIRECT*/) {
670     assert(LocationKind == Unknown);
671     LocationKind = Memory;
672   } else {
673     assert(LocationKind == Implicit || LocationKind == Unknown);
674     LocationKind = Implicit;
675   }
676 }
677