1 //===- llvm/CodeGen/DwarfExpression.cpp - Dwarf Debug Framework -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing dwarf debug info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "DwarfExpression.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/SmallBitVector.h"
17 #include "llvm/BinaryFormat/Dwarf.h"
18 #include "llvm/IR/DebugInfoMetadata.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Target/TargetRegisterInfo.h"
21 #include <algorithm>
22 #include <cassert>
23 #include <cstdint>
24 
25 using namespace llvm;
26 
27 void DwarfExpression::addReg(int DwarfReg, const char *Comment) {
28  assert(DwarfReg >= 0 && "invalid negative dwarf register number");
29  assert((LocationKind == Unknown || LocationKind == Register) &&
30         "location description already locked down");
31  LocationKind = Register;
32  if (DwarfReg < 32) {
33    emitOp(dwarf::DW_OP_reg0 + DwarfReg, Comment);
34   } else {
35     emitOp(dwarf::DW_OP_regx, Comment);
36     emitUnsigned(DwarfReg);
37   }
38 }
39 
40 void DwarfExpression::addBReg(int DwarfReg, int Offset) {
41   assert(DwarfReg >= 0 && "invalid negative dwarf register number");
42   assert(LocationKind != Register && "location description already locked down");
43   if (DwarfReg < 32) {
44     emitOp(dwarf::DW_OP_breg0 + DwarfReg);
45   } else {
46     emitOp(dwarf::DW_OP_bregx);
47     emitUnsigned(DwarfReg);
48   }
49   emitSigned(Offset);
50 }
51 
52 void DwarfExpression::addFBReg(int Offset) {
53   emitOp(dwarf::DW_OP_fbreg);
54   emitSigned(Offset);
55 }
56 
57 void DwarfExpression::addOpPiece(unsigned SizeInBits, unsigned OffsetInBits) {
58   if (!SizeInBits)
59     return;
60 
61   const unsigned SizeOfByte = 8;
62   if (OffsetInBits > 0 || SizeInBits % SizeOfByte) {
63     emitOp(dwarf::DW_OP_bit_piece);
64     emitUnsigned(SizeInBits);
65     emitUnsigned(OffsetInBits);
66   } else {
67     emitOp(dwarf::DW_OP_piece);
68     unsigned ByteSize = SizeInBits / SizeOfByte;
69     emitUnsigned(ByteSize);
70   }
71   this->OffsetInBits += SizeInBits;
72 }
73 
74 void DwarfExpression::addShr(unsigned ShiftBy) {
75   emitOp(dwarf::DW_OP_constu);
76   emitUnsigned(ShiftBy);
77   emitOp(dwarf::DW_OP_shr);
78 }
79 
80 void DwarfExpression::addAnd(unsigned Mask) {
81   emitOp(dwarf::DW_OP_constu);
82   emitUnsigned(Mask);
83   emitOp(dwarf::DW_OP_and);
84 }
85 
86 bool DwarfExpression::addMachineReg(const TargetRegisterInfo &TRI,
87                                     unsigned MachineReg, unsigned MaxSize) {
88   if (!TRI.isPhysicalRegister(MachineReg)) {
89     if (isFrameRegister(TRI, MachineReg)) {
90       DwarfRegs.push_back({-1, 0, nullptr});
91       return true;
92     }
93     return false;
94   }
95 
96   int Reg = TRI.getDwarfRegNum(MachineReg, false);
97 
98   // If this is a valid register number, emit it.
99   if (Reg >= 0) {
100     DwarfRegs.push_back({Reg, 0, nullptr});
101     return true;
102   }
103 
104   // Walk up the super-register chain until we find a valid number.
105   // For example, EAX on x86_64 is a 32-bit fragment of RAX with offset 0.
106   for (MCSuperRegIterator SR(MachineReg, &TRI); SR.isValid(); ++SR) {
107     Reg = TRI.getDwarfRegNum(*SR, false);
108     if (Reg >= 0) {
109       unsigned Idx = TRI.getSubRegIndex(*SR, MachineReg);
110       unsigned Size = TRI.getSubRegIdxSize(Idx);
111       unsigned RegOffset = TRI.getSubRegIdxOffset(Idx);
112       DwarfRegs.push_back({Reg, 0, "super-register"});
113       // Use a DW_OP_bit_piece to describe the sub-register.
114       setSubRegisterPiece(Size, RegOffset);
115       return true;
116     }
117   }
118 
119   // Otherwise, attempt to find a covering set of sub-register numbers.
120   // For example, Q0 on ARM is a composition of D0+D1.
121   unsigned CurPos = 0;
122   // The size of the register in bits.
123   const TargetRegisterClass *RC = TRI.getMinimalPhysRegClass(MachineReg);
124   unsigned RegSize = TRI.getRegSizeInBits(*RC);
125   // Keep track of the bits in the register we already emitted, so we
126   // can avoid emitting redundant aliasing subregs.
127   SmallBitVector Coverage(RegSize, false);
128   for (MCSubRegIterator SR(MachineReg, &TRI); SR.isValid(); ++SR) {
129     unsigned Idx = TRI.getSubRegIndex(MachineReg, *SR);
130     unsigned Size = TRI.getSubRegIdxSize(Idx);
131     unsigned Offset = TRI.getSubRegIdxOffset(Idx);
132     Reg = TRI.getDwarfRegNum(*SR, false);
133 
134     // Intersection between the bits we already emitted and the bits
135     // covered by this subregister.
136     SmallBitVector Intersection(RegSize, false);
137     Intersection.set(Offset, Offset + Size);
138     Intersection ^= Coverage;
139 
140     // If this sub-register has a DWARF number and we haven't covered
141     // its range, emit a DWARF piece for it.
142     if (Reg >= 0 && Intersection.any()) {
143       // Emit a piece for any gap in the coverage.
144       if (Offset > CurPos)
145         DwarfRegs.push_back({-1, Offset - CurPos, nullptr});
146       DwarfRegs.push_back(
147           {Reg, std::min<unsigned>(Size, MaxSize - Offset), "sub-register"});
148       if (Offset >= MaxSize)
149 	break;
150 
151       // Mark it as emitted.
152       Coverage.set(Offset, Offset + Size);
153       CurPos = Offset + Size;
154     }
155   }
156 
157   return CurPos;
158 }
159 
160 void DwarfExpression::addStackValue() {
161   if (DwarfVersion >= 4)
162     emitOp(dwarf::DW_OP_stack_value);
163 }
164 
165 void DwarfExpression::addSignedConstant(int64_t Value) {
166   assert(LocationKind == Implicit || LocationKind == Unknown);
167   LocationKind = Implicit;
168   emitOp(dwarf::DW_OP_consts);
169   emitSigned(Value);
170 }
171 
172 void DwarfExpression::addUnsignedConstant(uint64_t Value) {
173   assert(LocationKind == Implicit || LocationKind == Unknown);
174   LocationKind = Implicit;
175   emitOp(dwarf::DW_OP_constu);
176   emitUnsigned(Value);
177 }
178 
179 void DwarfExpression::addUnsignedConstant(const APInt &Value) {
180   assert(LocationKind == Implicit || LocationKind == Unknown);
181   LocationKind = Implicit;
182 
183   unsigned Size = Value.getBitWidth();
184   const uint64_t *Data = Value.getRawData();
185 
186   // Chop it up into 64-bit pieces, because that's the maximum that
187   // addUnsignedConstant takes.
188   unsigned Offset = 0;
189   while (Offset < Size) {
190     addUnsignedConstant(*Data++);
191     if (Offset == 0 && Size <= 64)
192       break;
193     addStackValue();
194     addOpPiece(std::min(Size - Offset, 64u), Offset);
195     Offset += 64;
196   }
197 }
198 
199 bool DwarfExpression::addMachineRegExpression(const TargetRegisterInfo &TRI,
200                                               DIExpressionCursor &ExprCursor,
201                                               unsigned MachineReg,
202                                               unsigned FragmentOffsetInBits) {
203   auto Fragment = ExprCursor.getFragmentInfo();
204   if (!addMachineReg(TRI, MachineReg, Fragment ? Fragment->SizeInBits : ~1U)) {
205     LocationKind = Unknown;
206     return false;
207   }
208 
209   bool HasComplexExpression = false;
210   auto Op = ExprCursor.peek();
211   if (Op && Op->getOp() != dwarf::DW_OP_LLVM_fragment)
212     HasComplexExpression = true;
213 
214   // If the register can only be described by a complex expression (i.e.,
215   // multiple subregisters) it doesn't safely compose with another complex
216   // expression. For example, it is not possible to apply a DW_OP_deref
217   // operation to multiple DW_OP_pieces.
218   if (HasComplexExpression && DwarfRegs.size() > 1) {
219     DwarfRegs.clear();
220     LocationKind = Unknown;
221     return false;
222   }
223 
224   // Handle simple register locations.
225   if (LocationKind != Memory && !HasComplexExpression) {
226     for (auto &Reg : DwarfRegs) {
227       if (Reg.DwarfRegNo >= 0)
228         addReg(Reg.DwarfRegNo, Reg.Comment);
229       addOpPiece(Reg.Size);
230     }
231     DwarfRegs.clear();
232     return true;
233   }
234 
235   // Don't emit locations that cannot be expressed without DW_OP_stack_value.
236   if (DwarfVersion < 4)
237     if (std::any_of(ExprCursor.begin(), ExprCursor.end(),
238                     [](DIExpression::ExprOperand Op) -> bool {
239                       return Op.getOp() == dwarf::DW_OP_stack_value;
240                     })) {
241       DwarfRegs.clear();
242       LocationKind = Unknown;
243       return false;
244     }
245 
246   assert(DwarfRegs.size() == 1);
247   auto Reg = DwarfRegs[0];
248   bool FBReg = isFrameRegister(TRI, MachineReg);
249   int SignedOffset = 0;
250   assert(Reg.Size == 0 && "subregister has same size as superregister");
251 
252   // Pattern-match combinations for which more efficient representations exist.
253   // [Reg, DW_OP_plus_uconst, Offset] --> [DW_OP_breg, Offset].
254   if (Op && (Op->getOp() == dwarf::DW_OP_plus_uconst)) {
255     SignedOffset = Op->getArg(0);
256     ExprCursor.take();
257   }
258 
259   // [Reg, DW_OP_constu, Offset, DW_OP_plus]  --> [DW_OP_breg, Offset]
260   // [Reg, DW_OP_constu, Offset, DW_OP_minus] --> [DW_OP_breg,-Offset]
261   // If Reg is a subregister we need to mask it out before subtracting.
262   if (Op && Op->getOp() == dwarf::DW_OP_constu) {
263     auto N = ExprCursor.peekNext();
264     if (N && (N->getOp() == dwarf::DW_OP_plus ||
265              (N->getOp() == dwarf::DW_OP_minus && !SubRegisterSizeInBits))) {
266       int Offset = Op->getArg(0);
267       SignedOffset = (N->getOp() == dwarf::DW_OP_minus) ? -Offset : Offset;
268       ExprCursor.consume(2);
269     }
270   }
271 
272   if (FBReg)
273     addFBReg(SignedOffset);
274   else
275     addBReg(Reg.DwarfRegNo, SignedOffset);
276   DwarfRegs.clear();
277   return true;
278 }
279 
280 /// Assuming a well-formed expression, match "DW_OP_deref* DW_OP_LLVM_fragment?".
281 static bool isMemoryLocation(DIExpressionCursor ExprCursor) {
282   while (ExprCursor) {
283     auto Op = ExprCursor.take();
284     switch (Op->getOp()) {
285     case dwarf::DW_OP_deref:
286     case dwarf::DW_OP_LLVM_fragment:
287       break;
288     default:
289       return false;
290     }
291   }
292   return true;
293 }
294 
295 void DwarfExpression::addExpression(DIExpressionCursor &&ExprCursor,
296                                     unsigned FragmentOffsetInBits) {
297   // If we need to mask out a subregister, do it now, unless the next
298   // operation would emit an OpPiece anyway.
299   auto N = ExprCursor.peek();
300   if (SubRegisterSizeInBits && N && (N->getOp() != dwarf::DW_OP_LLVM_fragment))
301     maskSubRegister();
302 
303   while (ExprCursor) {
304     auto Op = ExprCursor.take();
305     switch (Op->getOp()) {
306     case dwarf::DW_OP_LLVM_fragment: {
307       unsigned SizeInBits = Op->getArg(1);
308       unsigned FragmentOffset = Op->getArg(0);
309       // The fragment offset must have already been adjusted by emitting an
310       // empty DW_OP_piece / DW_OP_bit_piece before we emitted the base
311       // location.
312       assert(OffsetInBits >= FragmentOffset && "fragment offset not added?");
313 
314       // If addMachineReg already emitted DW_OP_piece operations to represent
315       // a super-register by splicing together sub-registers, subtract the size
316       // of the pieces that was already emitted.
317       SizeInBits -= OffsetInBits - FragmentOffset;
318 
319       // If addMachineReg requested a DW_OP_bit_piece to stencil out a
320       // sub-register that is smaller than the current fragment's size, use it.
321       if (SubRegisterSizeInBits)
322         SizeInBits = std::min<unsigned>(SizeInBits, SubRegisterSizeInBits);
323 
324       // Emit a DW_OP_stack_value for implicit location descriptions.
325       if (LocationKind == Implicit)
326         addStackValue();
327 
328       // Emit the DW_OP_piece.
329       addOpPiece(SizeInBits, SubRegisterOffsetInBits);
330       setSubRegisterPiece(0, 0);
331       // Reset the location description kind.
332       LocationKind = Unknown;
333       return;
334     }
335     case dwarf::DW_OP_plus_uconst:
336       assert(LocationKind != Register);
337       emitOp(dwarf::DW_OP_plus_uconst);
338       emitUnsigned(Op->getArg(0));
339       break;
340     case dwarf::DW_OP_plus:
341     case dwarf::DW_OP_minus:
342       emitOp(Op->getOp());
343       break;
344     case dwarf::DW_OP_deref:
345       assert(LocationKind != Register);
346       if (LocationKind != Memory && isMemoryLocation(ExprCursor))
347         // Turning this into a memory location description makes the deref
348         // implicit.
349         LocationKind = Memory;
350       else
351         emitOp(dwarf::DW_OP_deref);
352       break;
353     case dwarf::DW_OP_constu:
354       assert(LocationKind != Register);
355       emitOp(dwarf::DW_OP_constu);
356       emitUnsigned(Op->getArg(0));
357       break;
358     case dwarf::DW_OP_stack_value:
359       LocationKind = Implicit;
360       break;
361     case dwarf::DW_OP_swap:
362       assert(LocationKind != Register);
363       emitOp(dwarf::DW_OP_swap);
364       break;
365     case dwarf::DW_OP_xderef:
366       assert(LocationKind != Register);
367       emitOp(dwarf::DW_OP_xderef);
368       break;
369     default:
370       llvm_unreachable("unhandled opcode found in expression");
371     }
372   }
373 
374   if (LocationKind == Implicit)
375     // Turn this into an implicit location description.
376     addStackValue();
377 }
378 
379 /// add masking operations to stencil out a subregister.
380 void DwarfExpression::maskSubRegister() {
381   assert(SubRegisterSizeInBits && "no subregister was registered");
382   if (SubRegisterOffsetInBits > 0)
383     addShr(SubRegisterOffsetInBits);
384   uint64_t Mask = (1ULL << (uint64_t)SubRegisterSizeInBits) - 1ULL;
385   addAnd(Mask);
386 }
387 
388 void DwarfExpression::finalize() {
389   assert(DwarfRegs.size() == 0 && "dwarf registers not emitted");
390   // Emit any outstanding DW_OP_piece operations to mask out subregisters.
391   if (SubRegisterSizeInBits == 0)
392     return;
393   // Don't emit a DW_OP_piece for a subregister at offset 0.
394   if (SubRegisterOffsetInBits == 0)
395     return;
396   addOpPiece(SubRegisterSizeInBits, SubRegisterOffsetInBits);
397 }
398 
399 void DwarfExpression::addFragmentOffset(const DIExpression *Expr) {
400   if (!Expr || !Expr->isFragment())
401     return;
402 
403   uint64_t FragmentOffset = Expr->getFragmentInfo()->OffsetInBits;
404   assert(FragmentOffset >= OffsetInBits &&
405          "overlapping or duplicate fragments");
406   if (FragmentOffset > OffsetInBits)
407     addOpPiece(FragmentOffset - OffsetInBits);
408   OffsetInBits = FragmentOffset;
409 }
410