xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/AsmPrinter/DIEHash.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
1 //===-- llvm/CodeGen/DIEHash.cpp - Dwarf Hashing 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 DWARF4 hashing of DIEs.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "DIEHash.h"
14 #include "ByteStreamer.h"
15 #include "DwarfCompileUnit.h"
16 #include "DwarfDebug.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/BinaryFormat/Dwarf.h"
20 #include "llvm/CodeGen/AsmPrinter.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/Endian.h"
23 #include "llvm/Support/raw_ostream.h"
24 
25 using namespace llvm;
26 
27 #define DEBUG_TYPE "dwarfdebug"
28 
29 /// Grabs the string in whichever attribute is passed in and returns
30 /// a reference to it.
31 static StringRef getDIEStringAttr(const DIE &Die, uint16_t Attr) {
32   // Iterate through all the attributes until we find the one we're
33   // looking for, if we can't find it return an empty string.
34   for (const auto &V : Die.values())
35     if (V.getAttribute() == Attr)
36       return V.getDIEString().getString();
37 
38   return StringRef("");
39 }
40 
41 /// Adds the string in \p Str to the hash. This also hashes
42 /// a trailing NULL with the string.
43 void DIEHash::addString(StringRef Str) {
44   LLVM_DEBUG(dbgs() << "Adding string " << Str << " to hash.\n");
45   Hash.update(Str);
46   Hash.update(makeArrayRef((uint8_t)'\0'));
47 }
48 
49 // FIXME: The LEB128 routines are copied and only slightly modified out of
50 // LEB128.h.
51 
52 /// Adds the unsigned in \p Value to the hash encoded as a ULEB128.
53 void DIEHash::addULEB128(uint64_t Value) {
54   LLVM_DEBUG(dbgs() << "Adding ULEB128 " << Value << " to hash.\n");
55   do {
56     uint8_t Byte = Value & 0x7f;
57     Value >>= 7;
58     if (Value != 0)
59       Byte |= 0x80; // Mark this byte to show that more bytes will follow.
60     Hash.update(Byte);
61   } while (Value != 0);
62 }
63 
64 void DIEHash::addSLEB128(int64_t Value) {
65   LLVM_DEBUG(dbgs() << "Adding ULEB128 " << Value << " to hash.\n");
66   bool More;
67   do {
68     uint8_t Byte = Value & 0x7f;
69     Value >>= 7;
70     More = !((((Value == 0) && ((Byte & 0x40) == 0)) ||
71               ((Value == -1) && ((Byte & 0x40) != 0))));
72     if (More)
73       Byte |= 0x80; // Mark this byte to show that more bytes will follow.
74     Hash.update(Byte);
75   } while (More);
76 }
77 
78 /// Including \p Parent adds the context of Parent to the hash..
79 void DIEHash::addParentContext(const DIE &Parent) {
80 
81   LLVM_DEBUG(dbgs() << "Adding parent context to hash...\n");
82 
83   // [7.27.2] For each surrounding type or namespace beginning with the
84   // outermost such construct...
85   SmallVector<const DIE *, 1> Parents;
86   const DIE *Cur = &Parent;
87   while (Cur->getParent()) {
88     Parents.push_back(Cur);
89     Cur = Cur->getParent();
90   }
91   assert(Cur->getTag() == dwarf::DW_TAG_compile_unit ||
92          Cur->getTag() == dwarf::DW_TAG_type_unit);
93 
94   // Reverse iterate over our list to go from the outermost construct to the
95   // innermost.
96   for (const DIE *Die : llvm::reverse(Parents)) {
97     // ... Append the letter "C" to the sequence...
98     addULEB128('C');
99 
100     // ... Followed by the DWARF tag of the construct...
101     addULEB128(Die->getTag());
102 
103     // ... Then the name, taken from the DW_AT_name attribute.
104     StringRef Name = getDIEStringAttr(*Die, dwarf::DW_AT_name);
105     LLVM_DEBUG(dbgs() << "... adding context: " << Name << "\n");
106     if (!Name.empty())
107       addString(Name);
108   }
109 }
110 
111 // Collect all of the attributes for a particular DIE in single structure.
112 void DIEHash::collectAttributes(const DIE &Die, DIEAttrs &Attrs) {
113 
114   for (const auto &V : Die.values()) {
115     LLVM_DEBUG(dbgs() << "Attribute: "
116                       << dwarf::AttributeString(V.getAttribute())
117                       << " added.\n");
118     switch (V.getAttribute()) {
119 #define HANDLE_DIE_HASH_ATTR(NAME)                                             \
120   case dwarf::NAME:                                                            \
121     Attrs.NAME = V;                                                            \
122     break;
123 #include "DIEHashAttributes.def"
124     default:
125       break;
126     }
127   }
128 }
129 
130 void DIEHash::hashShallowTypeReference(dwarf::Attribute Attribute,
131                                        const DIE &Entry, StringRef Name) {
132   // append the letter 'N'
133   addULEB128('N');
134 
135   // the DWARF attribute code (DW_AT_type or DW_AT_friend),
136   addULEB128(Attribute);
137 
138   // the context of the tag,
139   if (const DIE *Parent = Entry.getParent())
140     addParentContext(*Parent);
141 
142   // the letter 'E',
143   addULEB128('E');
144 
145   // and the name of the type.
146   addString(Name);
147 
148   // Currently DW_TAG_friends are not used by Clang, but if they do become so,
149   // here's the relevant spec text to implement:
150   //
151   // For DW_TAG_friend, if the referenced entry is the DW_TAG_subprogram,
152   // the context is omitted and the name to be used is the ABI-specific name
153   // of the subprogram (e.g., the mangled linker name).
154 }
155 
156 void DIEHash::hashRepeatedTypeReference(dwarf::Attribute Attribute,
157                                         unsigned DieNumber) {
158   // a) If T is in the list of [previously hashed types], use the letter
159   // 'R' as the marker
160   addULEB128('R');
161 
162   addULEB128(Attribute);
163 
164   // and use the unsigned LEB128 encoding of [the index of T in the
165   // list] as the attribute value;
166   addULEB128(DieNumber);
167 }
168 
169 void DIEHash::hashDIEEntry(dwarf::Attribute Attribute, dwarf::Tag Tag,
170                            const DIE &Entry) {
171   assert(Tag != dwarf::DW_TAG_friend && "No current LLVM clients emit friend "
172                                         "tags. Add support here when there's "
173                                         "a use case");
174   // Step 5
175   // If the tag in Step 3 is one of [the below tags]
176   if ((Tag == dwarf::DW_TAG_pointer_type ||
177        Tag == dwarf::DW_TAG_reference_type ||
178        Tag == dwarf::DW_TAG_rvalue_reference_type ||
179        Tag == dwarf::DW_TAG_ptr_to_member_type) &&
180       // and the referenced type (via the [below attributes])
181       // FIXME: This seems overly restrictive, and causes hash mismatches
182       // there's a decl/def difference in the containing type of a
183       // ptr_to_member_type, but it's what DWARF says, for some reason.
184       Attribute == dwarf::DW_AT_type) {
185     // ... has a DW_AT_name attribute,
186     StringRef Name = getDIEStringAttr(Entry, dwarf::DW_AT_name);
187     if (!Name.empty()) {
188       hashShallowTypeReference(Attribute, Entry, Name);
189       return;
190     }
191   }
192 
193   unsigned &DieNumber = Numbering[&Entry];
194   if (DieNumber) {
195     hashRepeatedTypeReference(Attribute, DieNumber);
196     return;
197   }
198 
199   // otherwise, b) use the letter 'T' as the marker, ...
200   addULEB128('T');
201 
202   addULEB128(Attribute);
203 
204   // ... process the type T recursively by performing Steps 2 through 7, and
205   // use the result as the attribute value.
206   DieNumber = Numbering.size();
207   computeHash(Entry);
208 }
209 
210 // Hash all of the values in a block like set of values. This assumes that
211 // all of the data is going to be added as integers.
212 void DIEHash::hashBlockData(const DIE::const_value_range &Values) {
213   for (const auto &V : Values)
214     if (V.getType() == DIEValue::isBaseTypeRef) {
215       const DIE &C =
216           *CU->ExprRefedBaseTypes[V.getDIEBaseTypeRef().getIndex()].Die;
217       StringRef Name = getDIEStringAttr(C, dwarf::DW_AT_name);
218       assert(!Name.empty() &&
219              "Base types referenced from DW_OP_convert should have a name");
220       hashNestedType(C, Name);
221     } else
222       Hash.update((uint64_t)V.getDIEInteger().getValue());
223 }
224 
225 // Hash the contents of a loclistptr class.
226 void DIEHash::hashLocList(const DIELocList &LocList) {
227   HashingByteStreamer Streamer(*this);
228   DwarfDebug &DD = *AP->getDwarfDebug();
229   const DebugLocStream &Locs = DD.getDebugLocs();
230   const DebugLocStream::List &List = Locs.getList(LocList.getValue());
231   for (const DebugLocStream::Entry &Entry : Locs.getEntries(List))
232     DD.emitDebugLocEntry(Streamer, Entry, List.CU);
233 }
234 
235 // Hash an individual attribute \param Attr based on the type of attribute and
236 // the form.
237 void DIEHash::hashAttribute(const DIEValue &Value, dwarf::Tag Tag) {
238   dwarf::Attribute Attribute = Value.getAttribute();
239 
240   // Other attribute values use the letter 'A' as the marker, and the value
241   // consists of the form code (encoded as an unsigned LEB128 value) followed by
242   // the encoding of the value according to the form code. To ensure
243   // reproducibility of the signature, the set of forms used in the signature
244   // computation is limited to the following: DW_FORM_sdata, DW_FORM_flag,
245   // DW_FORM_string, and DW_FORM_block.
246 
247   switch (Value.getType()) {
248   case DIEValue::isNone:
249     llvm_unreachable("Expected valid DIEValue");
250 
251     // 7.27 Step 3
252     // ... An attribute that refers to another type entry T is processed as
253     // follows:
254   case DIEValue::isEntry:
255     hashDIEEntry(Attribute, Tag, Value.getDIEEntry().getEntry());
256     break;
257   case DIEValue::isInteger: {
258     addULEB128('A');
259     addULEB128(Attribute);
260     switch (Value.getForm()) {
261     case dwarf::DW_FORM_data1:
262     case dwarf::DW_FORM_data2:
263     case dwarf::DW_FORM_data4:
264     case dwarf::DW_FORM_data8:
265     case dwarf::DW_FORM_udata:
266     case dwarf::DW_FORM_sdata:
267       addULEB128(dwarf::DW_FORM_sdata);
268       addSLEB128((int64_t)Value.getDIEInteger().getValue());
269       break;
270     // DW_FORM_flag_present is just flag with a value of one. We still give it a
271     // value so just use the value.
272     case dwarf::DW_FORM_flag_present:
273     case dwarf::DW_FORM_flag:
274       addULEB128(dwarf::DW_FORM_flag);
275       addULEB128((int64_t)Value.getDIEInteger().getValue());
276       break;
277     default:
278       llvm_unreachable("Unknown integer form!");
279     }
280     break;
281   }
282   case DIEValue::isString:
283     addULEB128('A');
284     addULEB128(Attribute);
285     addULEB128(dwarf::DW_FORM_string);
286     addString(Value.getDIEString().getString());
287     break;
288   case DIEValue::isInlineString:
289     addULEB128('A');
290     addULEB128(Attribute);
291     addULEB128(dwarf::DW_FORM_string);
292     addString(Value.getDIEInlineString().getString());
293     break;
294   case DIEValue::isBlock:
295   case DIEValue::isLoc:
296   case DIEValue::isLocList:
297     addULEB128('A');
298     addULEB128(Attribute);
299     addULEB128(dwarf::DW_FORM_block);
300     if (Value.getType() == DIEValue::isBlock) {
301       addULEB128(Value.getDIEBlock().ComputeSize(AP));
302       hashBlockData(Value.getDIEBlock().values());
303     } else if (Value.getType() == DIEValue::isLoc) {
304       addULEB128(Value.getDIELoc().ComputeSize(AP));
305       hashBlockData(Value.getDIELoc().values());
306     } else {
307       // We could add the block length, but that would take
308       // a bit of work and not add a lot of uniqueness
309       // to the hash in some way we could test.
310       hashLocList(Value.getDIELocList());
311     }
312     break;
313     // FIXME: It's uncertain whether or not we should handle this at the moment.
314   case DIEValue::isExpr:
315   case DIEValue::isLabel:
316   case DIEValue::isBaseTypeRef:
317   case DIEValue::isDelta:
318   case DIEValue::isAddrOffset:
319     llvm_unreachable("Add support for additional value types.");
320   }
321 }
322 
323 // Go through the attributes from \param Attrs in the order specified in 7.27.4
324 // and hash them.
325 void DIEHash::hashAttributes(const DIEAttrs &Attrs, dwarf::Tag Tag) {
326 #define HANDLE_DIE_HASH_ATTR(NAME)                                             \
327   {                                                                            \
328     if (Attrs.NAME)                                                           \
329       hashAttribute(Attrs.NAME, Tag);                                         \
330   }
331 #include "DIEHashAttributes.def"
332   // FIXME: Add the extended attributes.
333 }
334 
335 // Add all of the attributes for \param Die to the hash.
336 void DIEHash::addAttributes(const DIE &Die) {
337   DIEAttrs Attrs = {};
338   collectAttributes(Die, Attrs);
339   hashAttributes(Attrs, Die.getTag());
340 }
341 
342 void DIEHash::hashNestedType(const DIE &Die, StringRef Name) {
343   // 7.27 Step 7
344   // ... append the letter 'S',
345   addULEB128('S');
346 
347   // the tag of C,
348   addULEB128(Die.getTag());
349 
350   // and the name.
351   addString(Name);
352 }
353 
354 // Compute the hash of a DIE. This is based on the type signature computation
355 // given in section 7.27 of the DWARF4 standard. It is the md5 hash of a
356 // flattened description of the DIE.
357 void DIEHash::computeHash(const DIE &Die) {
358   // Append the letter 'D', followed by the DWARF tag of the DIE.
359   addULEB128('D');
360   addULEB128(Die.getTag());
361 
362   // Add each of the attributes of the DIE.
363   addAttributes(Die);
364 
365   // Then hash each of the children of the DIE.
366   for (auto &C : Die.children()) {
367     // 7.27 Step 7
368     // If C is a nested type entry or a member function entry, ...
369     if (isType(C.getTag()) || (C.getTag() == dwarf::DW_TAG_subprogram && isType(C.getParent()->getTag()))) {
370       StringRef Name = getDIEStringAttr(C, dwarf::DW_AT_name);
371       // ... and has a DW_AT_name attribute
372       if (!Name.empty()) {
373         hashNestedType(C, Name);
374         continue;
375       }
376     }
377     computeHash(C);
378   }
379 
380   // Following the last (or if there are no children), append a zero byte.
381   Hash.update(makeArrayRef((uint8_t)'\0'));
382 }
383 
384 /// This is based on the type signature computation given in section 7.27 of the
385 /// DWARF4 standard. It is an md5 hash of the flattened description of the DIE
386 /// with the inclusion of the full CU and all top level CU entities.
387 // TODO: Initialize the type chain at 0 instead of 1 for CU signatures.
388 uint64_t DIEHash::computeCUSignature(StringRef DWOName, const DIE &Die) {
389   Numbering.clear();
390   Numbering[&Die] = 1;
391 
392   if (!DWOName.empty())
393     Hash.update(DWOName);
394   // Hash the DIE.
395   computeHash(Die);
396 
397   // Now return the result.
398   MD5::MD5Result Result;
399   Hash.final(Result);
400 
401   // ... take the least significant 8 bytes and return those. Our MD5
402   // implementation always returns its results in little endian, so we actually
403   // need the "high" word.
404   return Result.high();
405 }
406 
407 /// This is based on the type signature computation given in section 7.27 of the
408 /// DWARF4 standard. It is an md5 hash of the flattened description of the DIE
409 /// with the inclusion of additional forms not specifically called out in the
410 /// standard.
411 uint64_t DIEHash::computeTypeSignature(const DIE &Die) {
412   Numbering.clear();
413   Numbering[&Die] = 1;
414 
415   if (const DIE *Parent = Die.getParent())
416     addParentContext(*Parent);
417 
418   // Hash the DIE.
419   computeHash(Die);
420 
421   // Now return the result.
422   MD5::MD5Result Result;
423   Hash.final(Result);
424 
425   // ... take the least significant 8 bytes and return those. Our MD5
426   // implementation always returns its results in little endian, so we actually
427   // need the "high" word.
428   return Result.high();
429 }
430