xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/AsmPrinter/DIEHash.cpp (revision c7a063741720ef81d4caa4613242579d12f1d605)
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 void DIEHash::hashRawTypeReference(const DIE &Entry) {
211   unsigned &DieNumber = Numbering[&Entry];
212   if (DieNumber) {
213     addULEB128('R');
214     addULEB128(DieNumber);
215     return;
216   }
217   DieNumber = Numbering.size();
218   addULEB128('T');
219   computeHash(Entry);
220 }
221 
222 // Hash all of the values in a block like set of values. This assumes that
223 // all of the data is going to be added as integers.
224 void DIEHash::hashBlockData(const DIE::const_value_range &Values) {
225   for (const auto &V : Values)
226     if (V.getType() == DIEValue::isBaseTypeRef) {
227       const DIE &C =
228           *CU->ExprRefedBaseTypes[V.getDIEBaseTypeRef().getIndex()].Die;
229       StringRef Name = getDIEStringAttr(C, dwarf::DW_AT_name);
230       assert(!Name.empty() &&
231              "Base types referenced from DW_OP_convert should have a name");
232       hashNestedType(C, Name);
233     } else
234       Hash.update((uint64_t)V.getDIEInteger().getValue());
235 }
236 
237 // Hash the contents of a loclistptr class.
238 void DIEHash::hashLocList(const DIELocList &LocList) {
239   HashingByteStreamer Streamer(*this);
240   DwarfDebug &DD = *AP->getDwarfDebug();
241   const DebugLocStream &Locs = DD.getDebugLocs();
242   const DebugLocStream::List &List = Locs.getList(LocList.getValue());
243   for (const DebugLocStream::Entry &Entry : Locs.getEntries(List))
244     DD.emitDebugLocEntry(Streamer, Entry, List.CU);
245 }
246 
247 // Hash an individual attribute \param Attr based on the type of attribute and
248 // the form.
249 void DIEHash::hashAttribute(const DIEValue &Value, dwarf::Tag Tag) {
250   dwarf::Attribute Attribute = Value.getAttribute();
251 
252   // Other attribute values use the letter 'A' as the marker, and the value
253   // consists of the form code (encoded as an unsigned LEB128 value) followed by
254   // the encoding of the value according to the form code. To ensure
255   // reproducibility of the signature, the set of forms used in the signature
256   // computation is limited to the following: DW_FORM_sdata, DW_FORM_flag,
257   // DW_FORM_string, and DW_FORM_block.
258 
259   switch (Value.getType()) {
260   case DIEValue::isNone:
261     llvm_unreachable("Expected valid DIEValue");
262 
263     // 7.27 Step 3
264     // ... An attribute that refers to another type entry T is processed as
265     // follows:
266   case DIEValue::isEntry:
267     hashDIEEntry(Attribute, Tag, Value.getDIEEntry().getEntry());
268     break;
269   case DIEValue::isInteger: {
270     addULEB128('A');
271     addULEB128(Attribute);
272     switch (Value.getForm()) {
273     case dwarf::DW_FORM_data1:
274     case dwarf::DW_FORM_data2:
275     case dwarf::DW_FORM_data4:
276     case dwarf::DW_FORM_data8:
277     case dwarf::DW_FORM_udata:
278     case dwarf::DW_FORM_sdata:
279       addULEB128(dwarf::DW_FORM_sdata);
280       addSLEB128((int64_t)Value.getDIEInteger().getValue());
281       break;
282     // DW_FORM_flag_present is just flag with a value of one. We still give it a
283     // value so just use the value.
284     case dwarf::DW_FORM_flag_present:
285     case dwarf::DW_FORM_flag:
286       addULEB128(dwarf::DW_FORM_flag);
287       addULEB128((int64_t)Value.getDIEInteger().getValue());
288       break;
289     default:
290       llvm_unreachable("Unknown integer form!");
291     }
292     break;
293   }
294   case DIEValue::isString:
295     addULEB128('A');
296     addULEB128(Attribute);
297     addULEB128(dwarf::DW_FORM_string);
298     addString(Value.getDIEString().getString());
299     break;
300   case DIEValue::isInlineString:
301     addULEB128('A');
302     addULEB128(Attribute);
303     addULEB128(dwarf::DW_FORM_string);
304     addString(Value.getDIEInlineString().getString());
305     break;
306   case DIEValue::isBlock:
307   case DIEValue::isLoc:
308   case DIEValue::isLocList:
309     addULEB128('A');
310     addULEB128(Attribute);
311     addULEB128(dwarf::DW_FORM_block);
312     if (Value.getType() == DIEValue::isBlock) {
313       addULEB128(Value.getDIEBlock().computeSize(AP->getDwarfFormParams()));
314       hashBlockData(Value.getDIEBlock().values());
315     } else if (Value.getType() == DIEValue::isLoc) {
316       addULEB128(Value.getDIELoc().computeSize(AP->getDwarfFormParams()));
317       hashBlockData(Value.getDIELoc().values());
318     } else {
319       // We could add the block length, but that would take
320       // a bit of work and not add a lot of uniqueness
321       // to the hash in some way we could test.
322       hashLocList(Value.getDIELocList());
323     }
324     break;
325     // FIXME: It's uncertain whether or not we should handle this at the moment.
326   case DIEValue::isExpr:
327   case DIEValue::isLabel:
328   case DIEValue::isBaseTypeRef:
329   case DIEValue::isDelta:
330   case DIEValue::isAddrOffset:
331     llvm_unreachable("Add support for additional value types.");
332   }
333 }
334 
335 // Go through the attributes from \param Attrs in the order specified in 7.27.4
336 // and hash them.
337 void DIEHash::hashAttributes(const DIEAttrs &Attrs, dwarf::Tag Tag) {
338 #define HANDLE_DIE_HASH_ATTR(NAME)                                             \
339   {                                                                            \
340     if (Attrs.NAME)                                                           \
341       hashAttribute(Attrs.NAME, Tag);                                         \
342   }
343 #include "DIEHashAttributes.def"
344   // FIXME: Add the extended attributes.
345 }
346 
347 // Add all of the attributes for \param Die to the hash.
348 void DIEHash::addAttributes(const DIE &Die) {
349   DIEAttrs Attrs = {};
350   collectAttributes(Die, Attrs);
351   hashAttributes(Attrs, Die.getTag());
352 }
353 
354 void DIEHash::hashNestedType(const DIE &Die, StringRef Name) {
355   // 7.27 Step 7
356   // ... append the letter 'S',
357   addULEB128('S');
358 
359   // the tag of C,
360   addULEB128(Die.getTag());
361 
362   // and the name.
363   addString(Name);
364 }
365 
366 // Compute the hash of a DIE. This is based on the type signature computation
367 // given in section 7.27 of the DWARF4 standard. It is the md5 hash of a
368 // flattened description of the DIE.
369 void DIEHash::computeHash(const DIE &Die) {
370   // Append the letter 'D', followed by the DWARF tag of the DIE.
371   addULEB128('D');
372   addULEB128(Die.getTag());
373 
374   // Add each of the attributes of the DIE.
375   addAttributes(Die);
376 
377   // Then hash each of the children of the DIE.
378   for (auto &C : Die.children()) {
379     // 7.27 Step 7
380     // If C is a nested type entry or a member function entry, ...
381     if (isType(C.getTag()) || (C.getTag() == dwarf::DW_TAG_subprogram && isType(C.getParent()->getTag()))) {
382       StringRef Name = getDIEStringAttr(C, dwarf::DW_AT_name);
383       // ... and has a DW_AT_name attribute
384       if (!Name.empty()) {
385         hashNestedType(C, Name);
386         continue;
387       }
388     }
389     computeHash(C);
390   }
391 
392   // Following the last (or if there are no children), append a zero byte.
393   Hash.update(makeArrayRef((uint8_t)'\0'));
394 }
395 
396 /// This is based on the type signature computation given in section 7.27 of the
397 /// DWARF4 standard. It is an md5 hash of the flattened description of the DIE
398 /// with the inclusion of the full CU and all top level CU entities.
399 // TODO: Initialize the type chain at 0 instead of 1 for CU signatures.
400 uint64_t DIEHash::computeCUSignature(StringRef DWOName, const DIE &Die) {
401   Numbering.clear();
402   Numbering[&Die] = 1;
403 
404   if (!DWOName.empty())
405     Hash.update(DWOName);
406   // Hash the DIE.
407   computeHash(Die);
408 
409   // Now return the result.
410   MD5::MD5Result Result;
411   Hash.final(Result);
412 
413   // ... take the least significant 8 bytes and return those. Our MD5
414   // implementation always returns its results in little endian, so we actually
415   // need the "high" word.
416   return Result.high();
417 }
418 
419 /// This is based on the type signature computation given in section 7.27 of the
420 /// DWARF4 standard. It is an md5 hash of the flattened description of the DIE
421 /// with the inclusion of additional forms not specifically called out in the
422 /// standard.
423 uint64_t DIEHash::computeTypeSignature(const DIE &Die) {
424   Numbering.clear();
425   Numbering[&Die] = 1;
426 
427   if (const DIE *Parent = Die.getParent())
428     addParentContext(*Parent);
429 
430   // Hash the DIE.
431   computeHash(Die);
432 
433   // Now return the result.
434   MD5::MD5Result Result;
435   Hash.final(Result);
436 
437   // ... take the least significant 8 bytes and return those. Our MD5
438   // implementation always returns its results in little endian, so we actually
439   // need the "high" word.
440   return Result.high();
441 }
442