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     // The loop below is emitting the value starting at least significant byte,
235     // so we need to perform a byte-swap to get the byte order correct in case
236     // of a big-endian target.
237     if (AP.getDataLayout().isBigEndian())
238       API = API.byteSwap();
239 
240     for (int i = 0; i < NumBytes; ++i) {
241       emitData1(API.getZExtValue() & 0xFF);
242       API = API.lshr(8);
243     }
244 
245     return;
246   }
247   LLVM_DEBUG(
248       dbgs() << "Skipped DW_OP_implicit_value creation for ConstantFP of size: "
249              << API.getBitWidth() << " bits\n");
250 }
251 
252 bool DwarfExpression::addMachineRegExpression(const TargetRegisterInfo &TRI,
253                                               DIExpressionCursor &ExprCursor,
254                                               unsigned MachineReg,
255                                               unsigned FragmentOffsetInBits) {
256   auto Fragment = ExprCursor.getFragmentInfo();
257   if (!addMachineReg(TRI, MachineReg, Fragment ? Fragment->SizeInBits : ~1U)) {
258     LocationKind = Unknown;
259     return false;
260   }
261 
262   bool HasComplexExpression = false;
263   auto Op = ExprCursor.peek();
264   if (Op && Op->getOp() != dwarf::DW_OP_LLVM_fragment)
265     HasComplexExpression = true;
266 
267   // If the register can only be described by a complex expression (i.e.,
268   // multiple subregisters) it doesn't safely compose with another complex
269   // expression. For example, it is not possible to apply a DW_OP_deref
270   // operation to multiple DW_OP_pieces, since composite location descriptions
271   // do not push anything on the DWARF stack.
272   //
273   // DW_OP_entry_value operations can only hold a DWARF expression or a
274   // register location description, so we can't emit a single entry value
275   // covering a composite location description. In the future we may want to
276   // emit entry value operations for each register location in the composite
277   // location, but until that is supported do not emit anything.
278   if ((HasComplexExpression || IsEmittingEntryValue) && DwarfRegs.size() > 1) {
279     if (IsEmittingEntryValue)
280       cancelEntryValue();
281     DwarfRegs.clear();
282     LocationKind = Unknown;
283     return false;
284   }
285 
286   // Handle simple register locations. If we are supposed to emit
287   // a call site parameter expression and if that expression is just a register
288   // location, emit it with addBReg and offset 0, because we should emit a DWARF
289   // expression representing a value, rather than a location.
290   if (!isMemoryLocation() && !HasComplexExpression &&
291       (!isParameterValue() || isEntryValue())) {
292     for (auto &Reg : DwarfRegs) {
293       if (Reg.DwarfRegNo >= 0)
294         addReg(Reg.DwarfRegNo, Reg.Comment);
295       addOpPiece(Reg.SubRegSize);
296     }
297 
298     if (isEntryValue())
299       finalizeEntryValue();
300 
301     if (isEntryValue() && !isIndirect() && !isParameterValue() &&
302         DwarfVersion >= 4)
303       emitOp(dwarf::DW_OP_stack_value);
304 
305     DwarfRegs.clear();
306     return true;
307   }
308 
309   // Don't emit locations that cannot be expressed without DW_OP_stack_value.
310   if (DwarfVersion < 4)
311     if (any_of(ExprCursor, [](DIExpression::ExprOperand Op) -> bool {
312           return Op.getOp() == dwarf::DW_OP_stack_value;
313         })) {
314       DwarfRegs.clear();
315       LocationKind = Unknown;
316       return false;
317     }
318 
319   assert(DwarfRegs.size() == 1);
320   auto Reg = DwarfRegs[0];
321   bool FBReg = isFrameRegister(TRI, MachineReg);
322   int SignedOffset = 0;
323   assert(!Reg.isSubRegister() && "full register expected");
324 
325   // Pattern-match combinations for which more efficient representations exist.
326   // [Reg, DW_OP_plus_uconst, Offset] --> [DW_OP_breg, Offset].
327   if (Op && (Op->getOp() == dwarf::DW_OP_plus_uconst)) {
328     uint64_t Offset = Op->getArg(0);
329     uint64_t IntMax = static_cast<uint64_t>(std::numeric_limits<int>::max());
330     if (Offset <= IntMax) {
331       SignedOffset = Offset;
332       ExprCursor.take();
333     }
334   }
335 
336   // [Reg, DW_OP_constu, Offset, DW_OP_plus]  --> [DW_OP_breg, Offset]
337   // [Reg, DW_OP_constu, Offset, DW_OP_minus] --> [DW_OP_breg,-Offset]
338   // If Reg is a subregister we need to mask it out before subtracting.
339   if (Op && Op->getOp() == dwarf::DW_OP_constu) {
340     uint64_t Offset = Op->getArg(0);
341     uint64_t IntMax = static_cast<uint64_t>(std::numeric_limits<int>::max());
342     auto N = ExprCursor.peekNext();
343     if (N && N->getOp() == dwarf::DW_OP_plus && Offset <= IntMax) {
344       SignedOffset = Offset;
345       ExprCursor.consume(2);
346     } else if (N && N->getOp() == dwarf::DW_OP_minus &&
347                !SubRegisterSizeInBits && Offset <= IntMax + 1) {
348       SignedOffset = -static_cast<int64_t>(Offset);
349       ExprCursor.consume(2);
350     }
351   }
352 
353   if (FBReg)
354     addFBReg(SignedOffset);
355   else
356     addBReg(Reg.DwarfRegNo, SignedOffset);
357   DwarfRegs.clear();
358   return true;
359 }
360 
361 void DwarfExpression::setEntryValueFlags(const MachineLocation &Loc) {
362   LocationFlags |= EntryValue;
363   if (Loc.isIndirect())
364     LocationFlags |= Indirect;
365 }
366 
367 void DwarfExpression::setLocation(const MachineLocation &Loc,
368                                   const DIExpression *DIExpr) {
369   if (Loc.isIndirect())
370     // Do not treat entry value descriptions of indirect parameters as memory
371     // locations. This allows DwarfExpression::addReg() to add DW_OP_regN to an
372     // entry value description.
373     if (!DIExpr->isEntryValue())
374       setMemoryLocationKind();
375 
376   if (DIExpr->isEntryValue())
377     setEntryValueFlags(Loc);
378 }
379 
380 void DwarfExpression::beginEntryValueExpression(
381     DIExpressionCursor &ExprCursor) {
382   auto Op = ExprCursor.take();
383   (void)Op;
384   assert(Op && Op->getOp() == dwarf::DW_OP_LLVM_entry_value);
385   assert(!isMemoryLocation() &&
386          "We don't support entry values of memory locations yet");
387   assert(!IsEmittingEntryValue && "Already emitting entry value?");
388   assert(Op->getArg(0) == 1 &&
389          "Can currently only emit entry values covering a single operation");
390 
391   IsEmittingEntryValue = true;
392   enableTemporaryBuffer();
393 }
394 
395 void DwarfExpression::finalizeEntryValue() {
396   assert(IsEmittingEntryValue && "Entry value not open?");
397   disableTemporaryBuffer();
398 
399   emitOp(CU.getDwarf5OrGNULocationAtom(dwarf::DW_OP_entry_value));
400 
401   // Emit the entry value's size operand.
402   unsigned Size = getTemporaryBufferSize();
403   emitUnsigned(Size);
404 
405   // Emit the entry value's DWARF block operand.
406   commitTemporaryBuffer();
407 
408   IsEmittingEntryValue = false;
409 }
410 
411 void DwarfExpression::cancelEntryValue() {
412   assert(IsEmittingEntryValue && "Entry value not open?");
413   disableTemporaryBuffer();
414 
415   // The temporary buffer can't be emptied, so for now just assert that nothing
416   // has been emitted to it.
417   assert(getTemporaryBufferSize() == 0 &&
418          "Began emitting entry value block before cancelling entry value");
419 
420   IsEmittingEntryValue = false;
421 }
422 
423 unsigned DwarfExpression::getOrCreateBaseType(unsigned BitSize,
424                                               dwarf::TypeKind Encoding) {
425   // Reuse the base_type if we already have one in this CU otherwise we
426   // create a new one.
427   unsigned I = 0, E = CU.ExprRefedBaseTypes.size();
428   for (; I != E; ++I)
429     if (CU.ExprRefedBaseTypes[I].BitSize == BitSize &&
430         CU.ExprRefedBaseTypes[I].Encoding == Encoding)
431       break;
432 
433   if (I == E)
434     CU.ExprRefedBaseTypes.emplace_back(BitSize, Encoding);
435   return I;
436 }
437 
438 /// Assuming a well-formed expression, match "DW_OP_deref*
439 /// DW_OP_LLVM_fragment?".
440 static bool isMemoryLocation(DIExpressionCursor ExprCursor) {
441   while (ExprCursor) {
442     auto Op = ExprCursor.take();
443     switch (Op->getOp()) {
444     case dwarf::DW_OP_deref:
445     case dwarf::DW_OP_LLVM_fragment:
446       break;
447     default:
448       return false;
449     }
450   }
451   return true;
452 }
453 
454 void DwarfExpression::addExpression(DIExpressionCursor &&ExprCursor,
455                                     unsigned FragmentOffsetInBits) {
456   // Entry values can currently only cover the initial register location,
457   // and not any other parts of the following DWARF expression.
458   assert(!IsEmittingEntryValue && "Can't emit entry value around expression");
459 
460   // If we need to mask out a subregister, do it now, unless the next
461   // operation would emit an OpPiece anyway.
462   auto N = ExprCursor.peek();
463   if (SubRegisterSizeInBits && N && (N->getOp() != dwarf::DW_OP_LLVM_fragment))
464     maskSubRegister();
465 
466   Optional<DIExpression::ExprOperand> PrevConvertOp = None;
467 
468   while (ExprCursor) {
469     auto Op = ExprCursor.take();
470     uint64_t OpNum = Op->getOp();
471 
472     if (OpNum >= dwarf::DW_OP_reg0 && OpNum <= dwarf::DW_OP_reg31) {
473       emitOp(OpNum);
474       continue;
475     } else if (OpNum >= dwarf::DW_OP_breg0 && OpNum <= dwarf::DW_OP_breg31) {
476       addBReg(OpNum - dwarf::DW_OP_breg0, Op->getArg(0));
477       continue;
478     }
479 
480     switch (OpNum) {
481     case dwarf::DW_OP_LLVM_fragment: {
482       unsigned SizeInBits = Op->getArg(1);
483       unsigned FragmentOffset = Op->getArg(0);
484       // The fragment offset must have already been adjusted by emitting an
485       // empty DW_OP_piece / DW_OP_bit_piece before we emitted the base
486       // location.
487       assert(OffsetInBits >= FragmentOffset && "fragment offset not added?");
488       assert(SizeInBits >= OffsetInBits - FragmentOffset && "size underflow");
489 
490       // If addMachineReg already emitted DW_OP_piece operations to represent
491       // a super-register by splicing together sub-registers, subtract the size
492       // of the pieces that was already emitted.
493       SizeInBits -= OffsetInBits - FragmentOffset;
494 
495       // If addMachineReg requested a DW_OP_bit_piece to stencil out a
496       // sub-register that is smaller than the current fragment's size, use it.
497       if (SubRegisterSizeInBits)
498         SizeInBits = std::min<unsigned>(SizeInBits, SubRegisterSizeInBits);
499 
500       // Emit a DW_OP_stack_value for implicit location descriptions.
501       if (isImplicitLocation())
502         addStackValue();
503 
504       // Emit the DW_OP_piece.
505       addOpPiece(SizeInBits, SubRegisterOffsetInBits);
506       setSubRegisterPiece(0, 0);
507       // Reset the location description kind.
508       LocationKind = Unknown;
509       return;
510     }
511     case dwarf::DW_OP_plus_uconst:
512       assert(!isRegisterLocation());
513       emitOp(dwarf::DW_OP_plus_uconst);
514       emitUnsigned(Op->getArg(0));
515       break;
516     case dwarf::DW_OP_plus:
517     case dwarf::DW_OP_minus:
518     case dwarf::DW_OP_mul:
519     case dwarf::DW_OP_div:
520     case dwarf::DW_OP_mod:
521     case dwarf::DW_OP_or:
522     case dwarf::DW_OP_and:
523     case dwarf::DW_OP_xor:
524     case dwarf::DW_OP_shl:
525     case dwarf::DW_OP_shr:
526     case dwarf::DW_OP_shra:
527     case dwarf::DW_OP_lit0:
528     case dwarf::DW_OP_not:
529     case dwarf::DW_OP_dup:
530     case dwarf::DW_OP_push_object_address:
531       emitOp(OpNum);
532       break;
533     case dwarf::DW_OP_deref:
534       assert(!isRegisterLocation());
535       if (!isMemoryLocation() && ::isMemoryLocation(ExprCursor))
536         // Turning this into a memory location description makes the deref
537         // implicit.
538         LocationKind = Memory;
539       else
540         emitOp(dwarf::DW_OP_deref);
541       break;
542     case dwarf::DW_OP_constu:
543       assert(!isRegisterLocation());
544       emitConstu(Op->getArg(0));
545       break;
546     case dwarf::DW_OP_LLVM_convert: {
547       unsigned BitSize = Op->getArg(0);
548       dwarf::TypeKind Encoding = static_cast<dwarf::TypeKind>(Op->getArg(1));
549       if (DwarfVersion >= 5) {
550         emitOp(dwarf::DW_OP_convert);
551         // If targeting a location-list; simply emit the index into the raw
552         // byte stream as ULEB128, DwarfDebug::emitDebugLocEntry has been
553         // fitted with means to extract it later.
554         // If targeting a inlined DW_AT_location; insert a DIEBaseTypeRef
555         // (containing the index and a resolve mechanism during emit) into the
556         // DIE value list.
557         emitBaseTypeRef(getOrCreateBaseType(BitSize, Encoding));
558       } else {
559         if (PrevConvertOp && PrevConvertOp->getArg(0) < BitSize) {
560           if (Encoding == dwarf::DW_ATE_signed)
561             emitLegacySExt(PrevConvertOp->getArg(0));
562           else if (Encoding == dwarf::DW_ATE_unsigned)
563             emitLegacyZExt(PrevConvertOp->getArg(0));
564           PrevConvertOp = None;
565         } else {
566           PrevConvertOp = Op;
567         }
568       }
569       break;
570     }
571     case dwarf::DW_OP_stack_value:
572       LocationKind = Implicit;
573       break;
574     case dwarf::DW_OP_swap:
575       assert(!isRegisterLocation());
576       emitOp(dwarf::DW_OP_swap);
577       break;
578     case dwarf::DW_OP_xderef:
579       assert(!isRegisterLocation());
580       emitOp(dwarf::DW_OP_xderef);
581       break;
582     case dwarf::DW_OP_deref_size:
583       emitOp(dwarf::DW_OP_deref_size);
584       emitData1(Op->getArg(0));
585       break;
586     case dwarf::DW_OP_LLVM_tag_offset:
587       TagOffset = Op->getArg(0);
588       break;
589     case dwarf::DW_OP_regx:
590       emitOp(dwarf::DW_OP_regx);
591       emitUnsigned(Op->getArg(0));
592       break;
593     case dwarf::DW_OP_bregx:
594       emitOp(dwarf::DW_OP_bregx);
595       emitUnsigned(Op->getArg(0));
596       emitSigned(Op->getArg(1));
597       break;
598     default:
599       llvm_unreachable("unhandled opcode found in expression");
600     }
601   }
602 
603   if (isImplicitLocation() && !isParameterValue())
604     // Turn this into an implicit location description.
605     addStackValue();
606 }
607 
608 /// add masking operations to stencil out a subregister.
609 void DwarfExpression::maskSubRegister() {
610   assert(SubRegisterSizeInBits && "no subregister was registered");
611   if (SubRegisterOffsetInBits > 0)
612     addShr(SubRegisterOffsetInBits);
613   uint64_t Mask = (1ULL << (uint64_t)SubRegisterSizeInBits) - 1ULL;
614   addAnd(Mask);
615 }
616 
617 void DwarfExpression::finalize() {
618   assert(DwarfRegs.size() == 0 && "dwarf registers not emitted");
619   // Emit any outstanding DW_OP_piece operations to mask out subregisters.
620   if (SubRegisterSizeInBits == 0)
621     return;
622   // Don't emit a DW_OP_piece for a subregister at offset 0.
623   if (SubRegisterOffsetInBits == 0)
624     return;
625   addOpPiece(SubRegisterSizeInBits, SubRegisterOffsetInBits);
626 }
627 
628 void DwarfExpression::addFragmentOffset(const DIExpression *Expr) {
629   if (!Expr || !Expr->isFragment())
630     return;
631 
632   uint64_t FragmentOffset = Expr->getFragmentInfo()->OffsetInBits;
633   assert(FragmentOffset >= OffsetInBits &&
634          "overlapping or duplicate fragments");
635   if (FragmentOffset > OffsetInBits)
636     addOpPiece(FragmentOffset - OffsetInBits);
637   OffsetInBits = FragmentOffset;
638 }
639 
640 void DwarfExpression::emitLegacySExt(unsigned FromBits) {
641   // (((X >> (FromBits - 1)) * (~0)) << FromBits) | X
642   emitOp(dwarf::DW_OP_dup);
643   emitOp(dwarf::DW_OP_constu);
644   emitUnsigned(FromBits - 1);
645   emitOp(dwarf::DW_OP_shr);
646   emitOp(dwarf::DW_OP_lit0);
647   emitOp(dwarf::DW_OP_not);
648   emitOp(dwarf::DW_OP_mul);
649   emitOp(dwarf::DW_OP_constu);
650   emitUnsigned(FromBits);
651   emitOp(dwarf::DW_OP_shl);
652   emitOp(dwarf::DW_OP_or);
653 }
654 
655 void DwarfExpression::emitLegacyZExt(unsigned FromBits) {
656   // (X & (1 << FromBits - 1))
657   emitOp(dwarf::DW_OP_constu);
658   emitUnsigned((1ULL << FromBits) - 1);
659   emitOp(dwarf::DW_OP_and);
660 }
661 
662 void DwarfExpression::addWasmLocation(unsigned Index, uint64_t Offset) {
663   assert(LocationKind == Implicit || LocationKind == Unknown);
664   LocationKind = Implicit;
665   emitOp(dwarf::DW_OP_WASM_location);
666   emitUnsigned(Index);
667   emitUnsigned(Offset);
668 }
669