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