1 //===- DebugTypes.cpp -----------------------------------------------------===//
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 #include "DebugTypes.h"
10 #include "Chunks.h"
11 #include "Driver.h"
12 #include "InputFiles.h"
13 #include "PDB.h"
14 #include "TypeMerger.h"
15 #include "lld/Common/ErrorHandler.h"
16 #include "lld/Common/Memory.h"
17 #include "lld/Common/Timer.h"
18 #include "llvm/DebugInfo/CodeView/TypeIndexDiscovery.h"
19 #include "llvm/DebugInfo/CodeView/TypeRecord.h"
20 #include "llvm/DebugInfo/CodeView/TypeRecordHelpers.h"
21 #include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
22 #include "llvm/DebugInfo/PDB/GenericError.h"
23 #include "llvm/DebugInfo/PDB/Native/InfoStream.h"
24 #include "llvm/DebugInfo/PDB/Native/NativeSession.h"
25 #include "llvm/DebugInfo/PDB/Native/PDBFile.h"
26 #include "llvm/DebugInfo/PDB/Native/TpiHashing.h"
27 #include "llvm/DebugInfo/PDB/Native/TpiStream.h"
28 #include "llvm/Support/FormatVariadic.h"
29 #include "llvm/Support/Parallel.h"
30 #include "llvm/Support/Path.h"
31 
32 using namespace llvm;
33 using namespace llvm::codeview;
34 using namespace lld;
35 using namespace lld::coff;
36 
37 namespace {
38 class TypeServerIpiSource;
39 
40 // The TypeServerSource class represents a PDB type server, a file referenced by
41 // OBJ files compiled with MSVC /Zi. A single PDB can be shared by several OBJ
42 // files, therefore there must be only once instance per OBJ lot. The file path
43 // is discovered from the dependent OBJ's debug type stream. The
44 // TypeServerSource object is then queued and loaded by the COFF Driver. The
45 // debug type stream for such PDB files will be merged first in the final PDB,
46 // before any dependent OBJ.
47 class TypeServerSource : public TpiSource {
48 public:
49   explicit TypeServerSource(PDBInputFile *f)
50       : TpiSource(PDB, nullptr), pdbInputFile(f) {
51     if (f->loadErr && *f->loadErr)
52       return;
53     pdb::PDBFile &file = f->session->getPDBFile();
54     auto expectedInfo = file.getPDBInfoStream();
55     if (!expectedInfo)
56       return;
57     auto it = mappings.emplace(expectedInfo->getGuid(), this);
58     assert(it.second);
59     (void)it;
60   }
61 
62   Error mergeDebugT(TypeMerger *m) override;
63 
64   void loadGHashes() override;
65   void remapTpiWithGHashes(GHashState *g) override;
66 
67   bool isDependency() const override { return true; }
68 
69   PDBInputFile *pdbInputFile = nullptr;
70 
71   // TpiSource for IPI stream.
72   TypeServerIpiSource *ipiSrc = nullptr;
73 
74   static std::map<codeview::GUID, TypeServerSource *> mappings;
75 };
76 
77 // Companion to TypeServerSource. Stores the index map for the IPI stream in the
78 // PDB. Modeling PDBs with two sources for TPI and IPI helps establish the
79 // invariant of one type index space per source.
80 class TypeServerIpiSource : public TpiSource {
81 public:
82   explicit TypeServerIpiSource() : TpiSource(PDBIpi, nullptr) {}
83 
84   friend class TypeServerSource;
85 
86   // All of the TpiSource methods are no-ops. The parent TypeServerSource
87   // handles both TPI and IPI.
88   Error mergeDebugT(TypeMerger *m) override { return Error::success(); }
89   void loadGHashes() override {}
90   void remapTpiWithGHashes(GHashState *g) override {}
91   bool isDependency() const override { return true; }
92 };
93 
94 // This class represents the debug type stream of an OBJ file that depends on a
95 // PDB type server (see TypeServerSource).
96 class UseTypeServerSource : public TpiSource {
97   Expected<TypeServerSource *> getTypeServerSource();
98 
99 public:
100   UseTypeServerSource(ObjFile *f, TypeServer2Record ts)
101       : TpiSource(UsingPDB, f), typeServerDependency(ts) {}
102 
103   Error mergeDebugT(TypeMerger *m) override;
104 
105   // No need to load ghashes from /Zi objects.
106   void loadGHashes() override {}
107   void remapTpiWithGHashes(GHashState *g) override;
108 
109   // Information about the PDB type server dependency, that needs to be loaded
110   // in before merging this OBJ.
111   TypeServer2Record typeServerDependency;
112 };
113 
114 // This class represents the debug type stream of a Microsoft precompiled
115 // headers OBJ (PCH OBJ). This OBJ kind needs to be merged first in the output
116 // PDB, before any other OBJs that depend on this. Note that only MSVC generate
117 // such files, clang does not.
118 class PrecompSource : public TpiSource {
119 public:
120   PrecompSource(ObjFile *f) : TpiSource(PCH, f) {
121     if (!f->pchSignature || !*f->pchSignature)
122       fatal(toString(f) +
123             " claims to be a PCH object, but does not have a valid signature");
124     auto it = mappings.emplace(*f->pchSignature, this);
125     if (!it.second)
126       fatal("a PCH object with the same signature has already been provided (" +
127             toString(it.first->second->file) + " and " + toString(file) + ")");
128   }
129 
130   void loadGHashes() override;
131 
132   bool isDependency() const override { return true; }
133 
134   static std::map<uint32_t, PrecompSource *> mappings;
135 };
136 
137 // This class represents the debug type stream of an OBJ file that depends on a
138 // Microsoft precompiled headers OBJ (see PrecompSource).
139 class UsePrecompSource : public TpiSource {
140 public:
141   UsePrecompSource(ObjFile *f, PrecompRecord precomp)
142       : TpiSource(UsingPCH, f), precompDependency(precomp) {}
143 
144   Error mergeDebugT(TypeMerger *m) override;
145 
146   void loadGHashes() override;
147   void remapTpiWithGHashes(GHashState *g) override;
148 
149 private:
150   Error mergeInPrecompHeaderObj();
151 
152 public:
153   // Information about the Precomp OBJ dependency, that needs to be loaded in
154   // before merging this OBJ.
155   PrecompRecord precompDependency;
156 };
157 } // namespace
158 
159 std::vector<TpiSource *> TpiSource::instances;
160 ArrayRef<TpiSource *> TpiSource::dependencySources;
161 ArrayRef<TpiSource *> TpiSource::objectSources;
162 
163 TpiSource::TpiSource(TpiKind k, ObjFile *f)
164     : kind(k), tpiSrcIdx(instances.size()), file(f) {
165   instances.push_back(this);
166 }
167 
168 // Vtable key method.
169 TpiSource::~TpiSource() = default;
170 
171 void TpiSource::sortDependencies() {
172   // Order dependencies first, but preserve the existing order.
173   std::vector<TpiSource *> deps;
174   std::vector<TpiSource *> objs;
175   for (TpiSource *s : instances)
176     (s->isDependency() ? deps : objs).push_back(s);
177   uint32_t numDeps = deps.size();
178   uint32_t numObjs = objs.size();
179   instances = std::move(deps);
180   instances.insert(instances.end(), objs.begin(), objs.end());
181   for (uint32_t i = 0, e = instances.size(); i < e; ++i)
182     instances[i]->tpiSrcIdx = i;
183   dependencySources = makeArrayRef(instances.data(), numDeps);
184   objectSources = makeArrayRef(instances.data() + numDeps, numObjs);
185 }
186 
187 TpiSource *lld::coff::makeTpiSource(ObjFile *file) {
188   return make<TpiSource>(TpiSource::Regular, file);
189 }
190 
191 TpiSource *lld::coff::makeTypeServerSource(PDBInputFile *pdbInputFile) {
192   // Type server sources come in pairs: the TPI stream, and the IPI stream.
193   auto *tpiSource = make<TypeServerSource>(pdbInputFile);
194   if (pdbInputFile->session->getPDBFile().hasPDBIpiStream())
195     tpiSource->ipiSrc = make<TypeServerIpiSource>();
196   return tpiSource;
197 }
198 
199 TpiSource *lld::coff::makeUseTypeServerSource(ObjFile *file,
200                                               TypeServer2Record ts) {
201   return make<UseTypeServerSource>(file, ts);
202 }
203 
204 TpiSource *lld::coff::makePrecompSource(ObjFile *file) {
205   return make<PrecompSource>(file);
206 }
207 
208 TpiSource *lld::coff::makeUsePrecompSource(ObjFile *file,
209                                            PrecompRecord precomp) {
210   return make<UsePrecompSource>(file, precomp);
211 }
212 
213 std::map<codeview::GUID, TypeServerSource *> TypeServerSource::mappings;
214 
215 std::map<uint32_t, PrecompSource *> PrecompSource::mappings;
216 
217 bool TpiSource::remapTypeIndex(TypeIndex &ti, TiRefKind refKind) const {
218   if (ti.isSimple())
219     return true;
220 
221   // This can be an item index or a type index. Choose the appropriate map.
222   ArrayRef<TypeIndex> tpiOrIpiMap =
223       (refKind == TiRefKind::IndexRef) ? ipiMap : tpiMap;
224   if (ti.toArrayIndex() >= tpiOrIpiMap.size())
225     return false;
226   ti = tpiOrIpiMap[ti.toArrayIndex()];
227   return true;
228 }
229 
230 void TpiSource::remapRecord(MutableArrayRef<uint8_t> rec,
231                             ArrayRef<TiReference> typeRefs) {
232   MutableArrayRef<uint8_t> contents = rec.drop_front(sizeof(RecordPrefix));
233   for (const TiReference &ref : typeRefs) {
234     unsigned byteSize = ref.Count * sizeof(TypeIndex);
235     if (contents.size() < ref.Offset + byteSize)
236       fatal("symbol record too short");
237 
238     MutableArrayRef<TypeIndex> indices(
239         reinterpret_cast<TypeIndex *>(contents.data() + ref.Offset), ref.Count);
240     for (TypeIndex &ti : indices) {
241       if (!remapTypeIndex(ti, ref.Kind)) {
242         if (config->verbose) {
243           uint16_t kind =
244               reinterpret_cast<const RecordPrefix *>(rec.data())->RecordKind;
245           StringRef fname = file ? file->getName() : "<unknown PDB>";
246           log("failed to remap type index in record of kind 0x" +
247               utohexstr(kind) + " in " + fname + " with bad " +
248               (ref.Kind == TiRefKind::IndexRef ? "item" : "type") +
249               " index 0x" + utohexstr(ti.getIndex()));
250         }
251         ti = TypeIndex(SimpleTypeKind::NotTranslated);
252         continue;
253       }
254     }
255   }
256 }
257 
258 void TpiSource::remapTypesInTypeRecord(MutableArrayRef<uint8_t> rec) {
259   // TODO: Handle errors similar to symbols.
260   SmallVector<TiReference, 32> typeRefs;
261   discoverTypeIndices(CVType(rec), typeRefs);
262   remapRecord(rec, typeRefs);
263 }
264 
265 bool TpiSource::remapTypesInSymbolRecord(MutableArrayRef<uint8_t> rec) {
266   // Discover type index references in the record. Skip it if we don't
267   // know where they are.
268   SmallVector<TiReference, 32> typeRefs;
269   if (!discoverTypeIndicesInSymbol(rec, typeRefs))
270     return false;
271   remapRecord(rec, typeRefs);
272   return true;
273 }
274 
275 // A COFF .debug$H section is currently a clang extension.  This function checks
276 // if a .debug$H section is in a format that we expect / understand, so that we
277 // can ignore any sections which are coincidentally also named .debug$H but do
278 // not contain a format we recognize.
279 static bool canUseDebugH(ArrayRef<uint8_t> debugH) {
280   if (debugH.size() < sizeof(object::debug_h_header))
281     return false;
282   auto *header =
283       reinterpret_cast<const object::debug_h_header *>(debugH.data());
284   debugH = debugH.drop_front(sizeof(object::debug_h_header));
285   return header->Magic == COFF::DEBUG_HASHES_SECTION_MAGIC &&
286          header->Version == 0 &&
287          header->HashAlgorithm == uint16_t(GlobalTypeHashAlg::SHA1_8) &&
288          (debugH.size() % 8 == 0);
289 }
290 
291 static Optional<ArrayRef<uint8_t>> getDebugH(ObjFile *file) {
292   SectionChunk *sec =
293       SectionChunk::findByName(file->getDebugChunks(), ".debug$H");
294   if (!sec)
295     return llvm::None;
296   ArrayRef<uint8_t> contents = sec->getContents();
297   if (!canUseDebugH(contents))
298     return None;
299   return contents;
300 }
301 
302 static ArrayRef<GloballyHashedType>
303 getHashesFromDebugH(ArrayRef<uint8_t> debugH) {
304   assert(canUseDebugH(debugH));
305   debugH = debugH.drop_front(sizeof(object::debug_h_header));
306   uint32_t count = debugH.size() / sizeof(GloballyHashedType);
307   return {reinterpret_cast<const GloballyHashedType *>(debugH.data()), count};
308 }
309 
310 // Merge .debug$T for a generic object file.
311 Error TpiSource::mergeDebugT(TypeMerger *m) {
312   assert(!config->debugGHashes &&
313          "use remapTpiWithGHashes when ghash is enabled");
314 
315   CVTypeArray types;
316   BinaryStreamReader reader(file->debugTypes, support::little);
317   cantFail(reader.readArray(types, reader.getLength()));
318 
319   if (auto err = mergeTypeAndIdRecords(
320           m->idTable, m->typeTable, indexMapStorage, types, file->pchSignature))
321     fatal("codeview::mergeTypeAndIdRecords failed: " +
322           toString(std::move(err)));
323 
324   // In an object, there is only one mapping for both types and items.
325   tpiMap = indexMapStorage;
326   ipiMap = indexMapStorage;
327 
328   if (config->showSummary) {
329     // Count how many times we saw each type record in our input. This
330     // calculation requires a second pass over the type records to classify each
331     // record as a type or index. This is slow, but this code executes when
332     // collecting statistics.
333     m->tpiCounts.resize(m->getTypeTable().size());
334     m->ipiCounts.resize(m->getIDTable().size());
335     uint32_t srcIdx = 0;
336     for (CVType &ty : types) {
337       TypeIndex dstIdx = tpiMap[srcIdx++];
338       // Type merging may fail, so a complex source type may become the simple
339       // NotTranslated type, which cannot be used as an array index.
340       if (dstIdx.isSimple())
341         continue;
342       SmallVectorImpl<uint32_t> &counts =
343           isIdRecord(ty.kind()) ? m->ipiCounts : m->tpiCounts;
344       ++counts[dstIdx.toArrayIndex()];
345     }
346   }
347 
348   return Error::success();
349 }
350 
351 // Merge types from a type server PDB.
352 Error TypeServerSource::mergeDebugT(TypeMerger *m) {
353   assert(!config->debugGHashes &&
354          "use remapTpiWithGHashes when ghash is enabled");
355 
356   pdb::PDBFile &pdbFile = pdbInputFile->session->getPDBFile();
357   Expected<pdb::TpiStream &> expectedTpi = pdbFile.getPDBTpiStream();
358   if (auto e = expectedTpi.takeError())
359     fatal("Type server does not have TPI stream: " + toString(std::move(e)));
360   pdb::TpiStream *maybeIpi = nullptr;
361   if (pdbFile.hasPDBIpiStream()) {
362     Expected<pdb::TpiStream &> expectedIpi = pdbFile.getPDBIpiStream();
363     if (auto e = expectedIpi.takeError())
364       fatal("Error getting type server IPI stream: " + toString(std::move(e)));
365     maybeIpi = &*expectedIpi;
366   }
367 
368   // Merge TPI first, because the IPI stream will reference type indices.
369   if (auto err = mergeTypeRecords(m->typeTable, indexMapStorage,
370                                   expectedTpi->typeArray()))
371     fatal("codeview::mergeTypeRecords failed: " + toString(std::move(err)));
372   tpiMap = indexMapStorage;
373 
374   // Merge IPI.
375   if (maybeIpi) {
376     if (auto err = mergeIdRecords(m->idTable, tpiMap, ipiSrc->indexMapStorage,
377                                   maybeIpi->typeArray()))
378       fatal("codeview::mergeIdRecords failed: " + toString(std::move(err)));
379     ipiMap = ipiSrc->indexMapStorage;
380   }
381 
382   if (config->showSummary) {
383     // Count how many times we saw each type record in our input. If a
384     // destination type index is present in the source to destination type index
385     // map, that means we saw it once in the input. Add it to our histogram.
386     m->tpiCounts.resize(m->getTypeTable().size());
387     m->ipiCounts.resize(m->getIDTable().size());
388     for (TypeIndex ti : tpiMap)
389       if (!ti.isSimple())
390         ++m->tpiCounts[ti.toArrayIndex()];
391     for (TypeIndex ti : ipiMap)
392       if (!ti.isSimple())
393         ++m->ipiCounts[ti.toArrayIndex()];
394   }
395 
396   return Error::success();
397 }
398 
399 Expected<TypeServerSource *> UseTypeServerSource::getTypeServerSource() {
400   const codeview::GUID &tsId = typeServerDependency.getGuid();
401   StringRef tsPath = typeServerDependency.getName();
402 
403   TypeServerSource *tsSrc;
404   auto it = TypeServerSource::mappings.find(tsId);
405   if (it != TypeServerSource::mappings.end()) {
406     tsSrc = it->second;
407   } else {
408     // The file failed to load, lookup by name
409     PDBInputFile *pdb = PDBInputFile::findFromRecordPath(tsPath, file);
410     if (!pdb)
411       return createFileError(tsPath, errorCodeToError(std::error_code(
412                                          ENOENT, std::generic_category())));
413     // If an error occurred during loading, throw it now
414     if (pdb->loadErr && *pdb->loadErr)
415       return createFileError(tsPath, std::move(*pdb->loadErr));
416 
417     tsSrc = (TypeServerSource *)pdb->debugTypesObj;
418   }
419   return tsSrc;
420 }
421 
422 Error UseTypeServerSource::mergeDebugT(TypeMerger *m) {
423   Expected<TypeServerSource *> tsSrc = getTypeServerSource();
424   if (!tsSrc)
425     return tsSrc.takeError();
426 
427   pdb::PDBFile &pdbSession = (*tsSrc)->pdbInputFile->session->getPDBFile();
428   auto expectedInfo = pdbSession.getPDBInfoStream();
429   if (!expectedInfo)
430     return expectedInfo.takeError();
431 
432   // Just because a file with a matching name was found and it was an actual
433   // PDB file doesn't mean it matches.  For it to match the InfoStream's GUID
434   // must match the GUID specified in the TypeServer2 record.
435   if (expectedInfo->getGuid() != typeServerDependency.getGuid())
436     return createFileError(
437         typeServerDependency.getName(),
438         make_error<pdb::PDBError>(pdb::pdb_error_code::signature_out_of_date));
439 
440   // Reuse the type index map of the type server.
441   tpiMap = (*tsSrc)->tpiMap;
442   ipiMap = (*tsSrc)->ipiMap;
443   return Error::success();
444 }
445 
446 static bool equalsPath(StringRef path1, StringRef path2) {
447 #if defined(_WIN32)
448   return path1.equals_lower(path2);
449 #else
450   return path1.equals(path2);
451 #endif
452 }
453 
454 // Find by name an OBJ provided on the command line
455 static PrecompSource *findObjByName(StringRef fileNameOnly) {
456   SmallString<128> currentPath;
457   for (auto kv : PrecompSource::mappings) {
458     StringRef currentFileName = sys::path::filename(kv.second->file->getName(),
459                                                     sys::path::Style::windows);
460 
461     // Compare based solely on the file name (link.exe behavior)
462     if (equalsPath(currentFileName, fileNameOnly))
463       return kv.second;
464   }
465   return nullptr;
466 }
467 
468 static PrecompSource *findPrecompSource(ObjFile *file, PrecompRecord &pr) {
469   // Cross-compile warning: given that Clang doesn't generate LF_PRECOMP
470   // records, we assume the OBJ comes from a Windows build of cl.exe. Thusly,
471   // the paths embedded in the OBJs are in the Windows format.
472   SmallString<128> prFileName =
473       sys::path::filename(pr.getPrecompFilePath(), sys::path::Style::windows);
474 
475   auto it = PrecompSource::mappings.find(pr.getSignature());
476   if (it != PrecompSource::mappings.end()) {
477     return it->second;
478   }
479   // Lookup by name
480   return findObjByName(prFileName);
481 }
482 
483 static Expected<PrecompSource *> findPrecompMap(ObjFile *file,
484                                                 PrecompRecord &pr) {
485   PrecompSource *precomp = findPrecompSource(file, pr);
486 
487   if (!precomp)
488     return createFileError(
489         pr.getPrecompFilePath(),
490         make_error<pdb::PDBError>(pdb::pdb_error_code::no_matching_pch));
491 
492   if (pr.getSignature() != file->pchSignature)
493     return createFileError(
494         toString(file),
495         make_error<pdb::PDBError>(pdb::pdb_error_code::no_matching_pch));
496 
497   if (pr.getSignature() != *precomp->file->pchSignature)
498     return createFileError(
499         toString(precomp->file),
500         make_error<pdb::PDBError>(pdb::pdb_error_code::no_matching_pch));
501 
502   return precomp;
503 }
504 
505 /// Merges a precompiled headers TPI map into the current TPI map. The
506 /// precompiled headers object will also be loaded and remapped in the
507 /// process.
508 Error UsePrecompSource::mergeInPrecompHeaderObj() {
509   auto e = findPrecompMap(file, precompDependency);
510   if (!e)
511     return e.takeError();
512 
513   PrecompSource *precompSrc = *e;
514   if (precompSrc->tpiMap.empty())
515     return Error::success();
516 
517   assert(precompDependency.getStartTypeIndex() ==
518          TypeIndex::FirstNonSimpleIndex);
519   assert(precompDependency.getTypesCount() <= precompSrc->tpiMap.size());
520   // Use the previously remapped index map from the precompiled headers.
521   indexMapStorage.append(precompSrc->tpiMap.begin(),
522                          precompSrc->tpiMap.begin() +
523                              precompDependency.getTypesCount());
524 
525   if (config->debugGHashes)
526     funcIdToType = precompSrc->funcIdToType; // FIXME: Save copy
527 
528   return Error::success();
529 }
530 
531 Error UsePrecompSource::mergeDebugT(TypeMerger *m) {
532   // This object was compiled with /Yu, so process the corresponding
533   // precompiled headers object (/Yc) first. Some type indices in the current
534   // object are referencing data in the precompiled headers object, so we need
535   // both to be loaded.
536   if (Error e = mergeInPrecompHeaderObj())
537     return e;
538 
539   return TpiSource::mergeDebugT(m);
540 }
541 
542 uint32_t TpiSource::countTypeServerPDBs() {
543   return TypeServerSource::mappings.size();
544 }
545 
546 uint32_t TpiSource::countPrecompObjs() {
547   return PrecompSource::mappings.size();
548 }
549 
550 void TpiSource::clear() {
551   // Clean up any owned ghash allocations.
552   clearGHashes();
553   TpiSource::instances.clear();
554   TypeServerSource::mappings.clear();
555   PrecompSource::mappings.clear();
556 }
557 
558 //===----------------------------------------------------------------------===//
559 // Parellel GHash type merging implementation.
560 //===----------------------------------------------------------------------===//
561 
562 void TpiSource::loadGHashes() {
563   if (Optional<ArrayRef<uint8_t>> debugH = getDebugH(file)) {
564     ghashes = getHashesFromDebugH(*debugH);
565     ownedGHashes = false;
566   } else {
567     CVTypeArray types;
568     BinaryStreamReader reader(file->debugTypes, support::little);
569     cantFail(reader.readArray(types, reader.getLength()));
570     assignGHashesFromVector(GloballyHashedType::hashTypes(types));
571   }
572 
573   fillIsItemIndexFromDebugT();
574 }
575 
576 // Copies ghashes from a vector into an array. These are long lived, so it's
577 // worth the time to copy these into an appropriately sized vector to reduce
578 // memory usage.
579 void TpiSource::assignGHashesFromVector(
580     std::vector<GloballyHashedType> &&hashVec) {
581   GloballyHashedType *hashes = new GloballyHashedType[hashVec.size()];
582   memcpy(hashes, hashVec.data(), hashVec.size() * sizeof(GloballyHashedType));
583   ghashes = makeArrayRef(hashes, hashVec.size());
584   ownedGHashes = true;
585 }
586 
587 // Faster way to iterate type records. forEachTypeChecked is faster than
588 // iterating CVTypeArray. It avoids virtual readBytes calls in inner loops.
589 static void forEachTypeChecked(ArrayRef<uint8_t> types,
590                                function_ref<void(const CVType &)> fn) {
591   checkError(
592       forEachCodeViewRecord<CVType>(types, [fn](const CVType &ty) -> Error {
593         fn(ty);
594         return Error::success();
595       }));
596 }
597 
598 // Walk over file->debugTypes and fill in the isItemIndex bit vector.
599 // TODO: Store this information in .debug$H so that we don't have to recompute
600 // it. This is the main bottleneck slowing down parallel ghashing with one
601 // thread over single-threaded ghashing.
602 void TpiSource::fillIsItemIndexFromDebugT() {
603   uint32_t index = 0;
604   isItemIndex.resize(ghashes.size());
605   forEachTypeChecked(file->debugTypes, [&](const CVType &ty) {
606     if (isIdRecord(ty.kind()))
607       isItemIndex.set(index);
608     ++index;
609   });
610 }
611 
612 void TpiSource::mergeTypeRecord(CVType ty) {
613   // Decide if the merged type goes into TPI or IPI.
614   bool isItem = isIdRecord(ty.kind());
615   MergedInfo &merged = isItem ? mergedIpi : mergedTpi;
616 
617   // Copy the type into our mutable buffer.
618   assert(ty.length() <= codeview::MaxRecordLength);
619   size_t offset = merged.recs.size();
620   size_t newSize = alignTo(ty.length(), 4);
621   merged.recs.resize(offset + newSize);
622   auto newRec = makeMutableArrayRef(&merged.recs[offset], newSize);
623   memcpy(newRec.data(), ty.data().data(), newSize);
624 
625   // Fix up the record prefix and padding bytes if it required resizing.
626   if (newSize != ty.length()) {
627     reinterpret_cast<RecordPrefix *>(newRec.data())->RecordLen = newSize - 2;
628     for (size_t i = ty.length(); i < newSize; ++i)
629       newRec[i] = LF_PAD0 + (newSize - i);
630   }
631 
632   // Remap the type indices in the new record.
633   remapTypesInTypeRecord(newRec);
634   uint32_t pdbHash = check(pdb::hashTypeRecord(CVType(newRec)));
635   merged.recSizes.push_back(static_cast<uint16_t>(newSize));
636   merged.recHashes.push_back(pdbHash);
637 }
638 
639 void TpiSource::mergeUniqueTypeRecords(ArrayRef<uint8_t> typeRecords,
640                                        TypeIndex beginIndex) {
641   // Re-sort the list of unique types by index.
642   if (kind == PDB)
643     assert(std::is_sorted(uniqueTypes.begin(), uniqueTypes.end()));
644   else
645     llvm::sort(uniqueTypes);
646 
647   // Accumulate all the unique types into one buffer in mergedTypes.
648   uint32_t ghashIndex = 0;
649   auto nextUniqueIndex = uniqueTypes.begin();
650   assert(mergedTpi.recs.empty());
651   assert(mergedIpi.recs.empty());
652   forEachTypeChecked(typeRecords, [&](const CVType &ty) {
653     if (nextUniqueIndex != uniqueTypes.end() &&
654         *nextUniqueIndex == ghashIndex) {
655       mergeTypeRecord(ty);
656       ++nextUniqueIndex;
657     }
658     if (ty.kind() == LF_FUNC_ID || ty.kind() == LF_MFUNC_ID) {
659       bool success = ty.length() >= 12;
660       TypeIndex srcFuncIdIndex = beginIndex + ghashIndex;
661       TypeIndex funcId = srcFuncIdIndex;
662       TypeIndex funcType;
663       if (success) {
664         funcType = *reinterpret_cast<const TypeIndex *>(&ty.data()[8]);
665         success &= remapTypeIndex(funcId, TiRefKind::IndexRef);
666         success &= remapTypeIndex(funcType, TiRefKind::TypeRef);
667       }
668       if (success) {
669         funcIdToType.insert({funcId, funcType});
670       } else {
671         StringRef fname = file ? file->getName() : "<unknown PDB>";
672         warn("corrupt LF_[M]FUNC_ID record 0x" +
673              utohexstr(srcFuncIdIndex.getIndex()) + " in " + fname);
674       }
675     }
676     ++ghashIndex;
677   });
678   assert(nextUniqueIndex == uniqueTypes.end() &&
679          "failed to merge all desired records");
680   assert(uniqueTypes.size() ==
681              mergedTpi.recSizes.size() + mergedIpi.recSizes.size() &&
682          "missing desired record");
683 }
684 
685 void TpiSource::remapTpiWithGHashes(GHashState *g) {
686   assert(config->debugGHashes && "ghashes must be enabled");
687   fillMapFromGHashes(g, indexMapStorage);
688   tpiMap = indexMapStorage;
689   ipiMap = indexMapStorage;
690   mergeUniqueTypeRecords(file->debugTypes);
691   // TODO: Free all unneeded ghash resources now that we have a full index map.
692 }
693 
694 // PDBs do not actually store global hashes, so when merging a type server
695 // PDB we have to synthesize global hashes.  To do this, we first synthesize
696 // global hashes for the TPI stream, since it is independent, then we
697 // synthesize hashes for the IPI stream, using the hashes for the TPI stream
698 // as inputs.
699 void TypeServerSource::loadGHashes() {
700   // Don't hash twice.
701   if (!ghashes.empty())
702     return;
703   pdb::PDBFile &pdbFile = pdbInputFile->session->getPDBFile();
704 
705   // Hash TPI stream.
706   Expected<pdb::TpiStream &> expectedTpi = pdbFile.getPDBTpiStream();
707   if (auto e = expectedTpi.takeError())
708     fatal("Type server does not have TPI stream: " + toString(std::move(e)));
709   assignGHashesFromVector(
710       GloballyHashedType::hashTypes(expectedTpi->typeArray()));
711   isItemIndex.resize(ghashes.size());
712 
713   // Hash IPI stream, which depends on TPI ghashes.
714   if (!pdbFile.hasPDBIpiStream())
715     return;
716   Expected<pdb::TpiStream &> expectedIpi = pdbFile.getPDBIpiStream();
717   if (auto e = expectedIpi.takeError())
718     fatal("error retreiving IPI stream: " + toString(std::move(e)));
719   ipiSrc->assignGHashesFromVector(
720       GloballyHashedType::hashIds(expectedIpi->typeArray(), ghashes));
721 
722   // The IPI stream isItemIndex bitvector should be all ones.
723   ipiSrc->isItemIndex.resize(ipiSrc->ghashes.size());
724   ipiSrc->isItemIndex.set(0, ipiSrc->ghashes.size());
725 }
726 
727 // Flatten discontiguous PDB type arrays to bytes so that we can use
728 // forEachTypeChecked instead of CVTypeArray iteration. Copying all types from
729 // type servers is faster than iterating all object files compiled with /Z7 with
730 // CVTypeArray, which has high overheads due to the virtual interface of
731 // BinaryStream::readBytes.
732 static ArrayRef<uint8_t> typeArrayToBytes(const CVTypeArray &types) {
733   BinaryStreamRef stream = types.getUnderlyingStream();
734   ArrayRef<uint8_t> debugTypes;
735   checkError(stream.readBytes(0, stream.getLength(), debugTypes));
736   return debugTypes;
737 }
738 
739 // Merge types from a type server PDB.
740 void TypeServerSource::remapTpiWithGHashes(GHashState *g) {
741   assert(config->debugGHashes && "ghashes must be enabled");
742 
743   // IPI merging depends on TPI, so do TPI first, then do IPI.  No need to
744   // propagate errors, those should've been handled during ghash loading.
745   pdb::PDBFile &pdbFile = pdbInputFile->session->getPDBFile();
746   pdb::TpiStream &tpi = check(pdbFile.getPDBTpiStream());
747   fillMapFromGHashes(g, indexMapStorage);
748   tpiMap = indexMapStorage;
749   mergeUniqueTypeRecords(typeArrayToBytes(tpi.typeArray()));
750   if (pdbFile.hasPDBIpiStream()) {
751     pdb::TpiStream &ipi = check(pdbFile.getPDBIpiStream());
752     ipiSrc->indexMapStorage.resize(ipiSrc->ghashes.size());
753     ipiSrc->fillMapFromGHashes(g, ipiSrc->indexMapStorage);
754     ipiMap = ipiSrc->indexMapStorage;
755     ipiSrc->tpiMap = tpiMap;
756     ipiSrc->ipiMap = ipiMap;
757     ipiSrc->mergeUniqueTypeRecords(typeArrayToBytes(ipi.typeArray()));
758     funcIdToType = ipiSrc->funcIdToType; // FIXME: Save copy
759   }
760 }
761 
762 void UseTypeServerSource::remapTpiWithGHashes(GHashState *g) {
763   // No remapping to do with /Zi objects. Simply use the index map from the type
764   // server. Errors should have been reported earlier. Symbols from this object
765   // will be ignored.
766   Expected<TypeServerSource *> maybeTsSrc = getTypeServerSource();
767   if (!maybeTsSrc) {
768     typeMergingError = maybeTsSrc.takeError();
769     return;
770   }
771   TypeServerSource *tsSrc = *maybeTsSrc;
772   tpiMap = tsSrc->tpiMap;
773   ipiMap = tsSrc->ipiMap;
774   funcIdToType = tsSrc->funcIdToType; // FIXME: Save copy
775 }
776 
777 void PrecompSource::loadGHashes() {
778   if (getDebugH(file)) {
779     warn("ignoring .debug$H section; pch with ghash is not implemented");
780   }
781 
782   uint32_t ghashIdx = 0;
783   std::vector<GloballyHashedType> hashVec;
784   forEachTypeChecked(file->debugTypes, [&](const CVType &ty) {
785     // Remember the index of the LF_ENDPRECOMP record so it can be excluded from
786     // the PDB. There must be an entry in the list of ghashes so that the type
787     // indexes of the following records in the /Yc PCH object line up.
788     if (ty.kind() == LF_ENDPRECOMP)
789       endPrecompGHashIdx = ghashIdx;
790 
791     hashVec.push_back(GloballyHashedType::hashType(ty, hashVec, hashVec));
792     isItemIndex.push_back(isIdRecord(ty.kind()));
793     ++ghashIdx;
794   });
795   assignGHashesFromVector(std::move(hashVec));
796 }
797 
798 void UsePrecompSource::loadGHashes() {
799   PrecompSource *pchSrc = findPrecompSource(file, precompDependency);
800   if (!pchSrc)
801     return;
802 
803   // To compute ghashes of a /Yu object file, we need to build on the the
804   // ghashes of the /Yc PCH object. After we are done hashing, discard the
805   // ghashes from the PCH source so we don't unnecessarily try to deduplicate
806   // them.
807   std::vector<GloballyHashedType> hashVec =
808       pchSrc->ghashes.take_front(precompDependency.getTypesCount());
809   forEachTypeChecked(file->debugTypes, [&](const CVType &ty) {
810     hashVec.push_back(GloballyHashedType::hashType(ty, hashVec, hashVec));
811     isItemIndex.push_back(isIdRecord(ty.kind()));
812   });
813   hashVec.erase(hashVec.begin(),
814                 hashVec.begin() + precompDependency.getTypesCount());
815   assignGHashesFromVector(std::move(hashVec));
816 }
817 
818 void UsePrecompSource::remapTpiWithGHashes(GHashState *g) {
819   // This object was compiled with /Yu, so process the corresponding
820   // precompiled headers object (/Yc) first. Some type indices in the current
821   // object are referencing data in the precompiled headers object, so we need
822   // both to be loaded.
823   if (Error e = mergeInPrecompHeaderObj()) {
824     typeMergingError = std::move(e);
825     return;
826   }
827 
828   fillMapFromGHashes(g, indexMapStorage);
829   tpiMap = indexMapStorage;
830   ipiMap = indexMapStorage;
831   mergeUniqueTypeRecords(file->debugTypes,
832                          TypeIndex(precompDependency.getStartTypeIndex() +
833                                    precompDependency.getTypesCount()));
834 }
835 
836 namespace {
837 /// A concurrent hash table for global type hashing. It is based on this paper:
838 /// Concurrent Hash Tables: Fast and General(?)!
839 /// https://dl.acm.org/doi/10.1145/3309206
840 ///
841 /// This hash table is meant to be used in two phases:
842 /// 1. concurrent insertions
843 /// 2. concurrent reads
844 /// It does not support lookup, deletion, or rehashing. It uses linear probing.
845 ///
846 /// The paper describes storing a key-value pair in two machine words.
847 /// Generally, the values stored in this map are type indices, and we can use
848 /// those values to recover the ghash key from a side table. This allows us to
849 /// shrink the table entries further at the cost of some loads, and sidesteps
850 /// the need for a 128 bit atomic compare-and-swap operation.
851 ///
852 /// During insertion, a priority function is used to decide which insertion
853 /// should be preferred. This ensures that the output is deterministic. For
854 /// ghashing, lower tpiSrcIdx values (earlier inputs) are preferred.
855 ///
856 class GHashCell;
857 struct GHashTable {
858   GHashCell *table = nullptr;
859   uint32_t tableSize = 0;
860 
861   GHashTable() = default;
862   ~GHashTable();
863 
864   /// Initialize the table with the given size. Because the table cannot be
865   /// resized, the initial size of the table must be large enough to contain all
866   /// inputs, or insertion may not be able to find an empty cell.
867   void init(uint32_t newTableSize);
868 
869   /// Insert the cell with the given ghash into the table. Return the insertion
870   /// position in the table. It is safe for the caller to store the insertion
871   /// position because the table cannot be resized.
872   uint32_t insert(GloballyHashedType ghash, GHashCell newCell);
873 };
874 
875 /// A ghash table cell for deduplicating types from TpiSources.
876 class GHashCell {
877   uint64_t data = 0;
878 
879 public:
880   GHashCell() = default;
881 
882   // Construct data most to least significant so that sorting works well:
883   // - isItem
884   // - tpiSrcIdx
885   // - ghashIdx
886   // Add one to the tpiSrcIdx so that the 0th record from the 0th source has a
887   // non-zero representation.
888   GHashCell(bool isItem, uint32_t tpiSrcIdx, uint32_t ghashIdx)
889       : data((uint64_t(isItem) << 63U) | (uint64_t(tpiSrcIdx + 1) << 32ULL) |
890              ghashIdx) {
891     assert(tpiSrcIdx == getTpiSrcIdx() && "round trip failure");
892     assert(ghashIdx == getGHashIdx() && "round trip failure");
893   }
894 
895   explicit GHashCell(uint64_t data) : data(data) {}
896 
897   // The empty cell is all zeros.
898   bool isEmpty() const { return data == 0ULL; }
899 
900   /// Extract the tpiSrcIdx.
901   uint32_t getTpiSrcIdx() const {
902     return ((uint32_t)(data >> 32U) & 0x7FFFFFFF) - 1;
903   }
904 
905   /// Extract the index into the ghash array of the TpiSource.
906   uint32_t getGHashIdx() const { return (uint32_t)data; }
907 
908   bool isItem() const { return data & (1ULL << 63U); }
909 
910   /// Get the ghash key for this cell.
911   GloballyHashedType getGHash() const {
912     return TpiSource::instances[getTpiSrcIdx()]->ghashes[getGHashIdx()];
913   }
914 
915   /// The priority function for the cell. The data is stored such that lower
916   /// tpiSrcIdx and ghashIdx values are preferred, which means that type record
917   /// from earlier sources are more likely to prevail.
918   friend inline bool operator<(const GHashCell &l, const GHashCell &r) {
919     return l.data < r.data;
920   }
921 };
922 } // namespace
923 
924 namespace lld {
925 namespace coff {
926 /// This type is just a wrapper around GHashTable with external linkage so it
927 /// can be used from a header.
928 struct GHashState {
929   GHashTable table;
930 };
931 } // namespace coff
932 } // namespace lld
933 
934 GHashTable::~GHashTable() { delete[] table; }
935 
936 void GHashTable::init(uint32_t newTableSize) {
937   table = new GHashCell[newTableSize];
938   memset(table, 0, newTableSize * sizeof(GHashCell));
939   tableSize = newTableSize;
940 }
941 
942 uint32_t GHashTable::insert(GloballyHashedType ghash, GHashCell newCell) {
943   assert(!newCell.isEmpty() && "cannot insert empty cell value");
944 
945   // FIXME: The low bytes of SHA1 have low entropy for short records, which
946   // type records are. Swap the byte order for better entropy. A better ghash
947   // won't need this.
948   uint32_t startIdx =
949       ByteSwap_64(*reinterpret_cast<uint64_t *>(&ghash)) % tableSize;
950 
951   // Do a linear probe starting at startIdx.
952   uint32_t idx = startIdx;
953   while (true) {
954     // Run a compare and swap loop. There are four cases:
955     // - cell is empty: CAS into place and return
956     // - cell has matching key, earlier priority: do nothing, return
957     // - cell has matching key, later priority: CAS into place and return
958     // - cell has non-matching key: hash collision, probe next cell
959     auto *cellPtr = reinterpret_cast<std::atomic<GHashCell> *>(&table[idx]);
960     GHashCell oldCell(cellPtr->load());
961     while (oldCell.isEmpty() || oldCell.getGHash() == ghash) {
962       // Check if there is an existing ghash entry with a higher priority
963       // (earlier ordering). If so, this is a duplicate, we are done.
964       if (!oldCell.isEmpty() && oldCell < newCell)
965         return idx;
966       // Either the cell is empty, or our value is higher priority. Try to
967       // compare and swap. If it succeeds, we are done.
968       if (cellPtr->compare_exchange_weak(oldCell, newCell))
969         return idx;
970       // If the CAS failed, check this cell again.
971     }
972 
973     // Advance the probe. Wrap around to the beginning if we run off the end.
974     ++idx;
975     idx = idx == tableSize ? 0 : idx;
976     if (idx == startIdx) {
977       // If this becomes an issue, we could mark failure and rehash from the
978       // beginning with a bigger table. There is no difference between rehashing
979       // internally and starting over.
980       report_fatal_error("ghash table is full");
981     }
982   }
983   llvm_unreachable("left infloop");
984 }
985 
986 TypeMerger::TypeMerger(llvm::BumpPtrAllocator &alloc)
987     : typeTable(alloc), idTable(alloc) {}
988 
989 TypeMerger::~TypeMerger() = default;
990 
991 void TypeMerger::mergeTypesWithGHash() {
992   // Load ghashes. Do type servers and PCH objects first.
993   {
994     ScopedTimer t1(loadGHashTimer);
995     parallelForEach(TpiSource::dependencySources,
996                     [&](TpiSource *source) { source->loadGHashes(); });
997     parallelForEach(TpiSource::objectSources,
998                     [&](TpiSource *source) { source->loadGHashes(); });
999   }
1000 
1001   ScopedTimer t2(mergeGHashTimer);
1002   GHashState ghashState;
1003 
1004   // Estimate the size of hash table needed to deduplicate ghashes. This *must*
1005   // be larger than the number of unique types, or hash table insertion may not
1006   // be able to find a vacant slot. Summing the input types guarantees this, but
1007   // it is a gross overestimate. The table size could be reduced to save memory,
1008   // but it would require implementing rehashing, and this table is generally
1009   // small compared to total memory usage, at eight bytes per input type record,
1010   // and most input type records are larger than eight bytes.
1011   size_t tableSize = 0;
1012   for (TpiSource *source : TpiSource::instances)
1013     tableSize += source->ghashes.size();
1014 
1015   // Cap the table size so that we can use 32-bit cell indices. Type indices are
1016   // also 32-bit, so this is an inherent PDB file format limit anyway.
1017   tableSize = std::min(size_t(INT32_MAX), tableSize);
1018   ghashState.table.init(static_cast<uint32_t>(tableSize));
1019 
1020   // Insert ghashes in parallel. During concurrent insertion, we cannot observe
1021   // the contents of the hash table cell, but we can remember the insertion
1022   // position. Because the table does not rehash, the position will not change
1023   // under insertion. After insertion is done, the value of the cell can be read
1024   // to retreive the final PDB type index.
1025   parallelForEachN(0, TpiSource::instances.size(), [&](size_t tpiSrcIdx) {
1026     TpiSource *source = TpiSource::instances[tpiSrcIdx];
1027     source->indexMapStorage.resize(source->ghashes.size());
1028     for (uint32_t i = 0, e = source->ghashes.size(); i < e; i++) {
1029       if (source->shouldOmitFromPdb(i)) {
1030         source->indexMapStorage[i] = TypeIndex(SimpleTypeKind::NotTranslated);
1031         continue;
1032       }
1033       GloballyHashedType ghash = source->ghashes[i];
1034       bool isItem = source->isItemIndex.test(i);
1035       uint32_t cellIdx =
1036           ghashState.table.insert(ghash, GHashCell(isItem, tpiSrcIdx, i));
1037 
1038       // Store the ghash cell index as a type index in indexMapStorage. Later
1039       // we will replace it with the PDB type index.
1040       source->indexMapStorage[i] = TypeIndex::fromArrayIndex(cellIdx);
1041     }
1042   });
1043 
1044   // Collect all non-empty cells and sort them. This will implicitly assign
1045   // destination type indices, and partition the entries into type records and
1046   // item records. It arranges types in this order:
1047   // - type records
1048   //   - source 0, type 0...
1049   //   - source 1, type 1...
1050   // - item records
1051   //   - source 0, type 1...
1052   //   - source 1, type 0...
1053   std::vector<GHashCell> entries;
1054   for (const GHashCell &cell :
1055        makeArrayRef(ghashState.table.table, tableSize)) {
1056     if (!cell.isEmpty())
1057       entries.push_back(cell);
1058   }
1059   parallelSort(entries, std::less<GHashCell>());
1060   log(formatv("ghash table load factor: {0:p} (size {1} / capacity {2})\n",
1061               double(entries.size()) / tableSize, entries.size(), tableSize));
1062 
1063   // Find out how many type and item indices there are.
1064   auto mid =
1065       std::lower_bound(entries.begin(), entries.end(), GHashCell(true, 0, 0));
1066   assert((mid == entries.end() || mid->isItem()) &&
1067          (mid == entries.begin() || !std::prev(mid)->isItem()) &&
1068          "midpoint is not midpoint");
1069   uint32_t numTypes = std::distance(entries.begin(), mid);
1070   uint32_t numItems = std::distance(mid, entries.end());
1071   log("Tpi record count: " + Twine(numTypes));
1072   log("Ipi record count: " + Twine(numItems));
1073 
1074   // Make a list of the "unique" type records to merge for each tpi source. Type
1075   // merging will skip indices not on this list. Store the destination PDB type
1076   // index for these unique types in the tpiMap for each source. The entries for
1077   // non-unique types will be filled in prior to type merging.
1078   for (uint32_t i = 0, e = entries.size(); i < e; ++i) {
1079     auto &cell = entries[i];
1080     uint32_t tpiSrcIdx = cell.getTpiSrcIdx();
1081     TpiSource *source = TpiSource::instances[tpiSrcIdx];
1082     source->uniqueTypes.push_back(cell.getGHashIdx());
1083 
1084     // Update the ghash table to store the destination PDB type index in the
1085     // table.
1086     uint32_t pdbTypeIndex = i < numTypes ? i : i - numTypes;
1087     uint32_t ghashCellIndex =
1088         source->indexMapStorage[cell.getGHashIdx()].toArrayIndex();
1089     ghashState.table.table[ghashCellIndex] =
1090         GHashCell(cell.isItem(), cell.getTpiSrcIdx(), pdbTypeIndex);
1091   }
1092 
1093   // In parallel, remap all types.
1094   for_each(TpiSource::dependencySources, [&](TpiSource *source) {
1095     source->remapTpiWithGHashes(&ghashState);
1096   });
1097   parallelForEach(TpiSource::objectSources, [&](TpiSource *source) {
1098     source->remapTpiWithGHashes(&ghashState);
1099   });
1100 
1101   TpiSource::clearGHashes();
1102 }
1103 
1104 /// Given the index into the ghash table for a particular type, return the type
1105 /// index for that type in the output PDB.
1106 static TypeIndex loadPdbTypeIndexFromCell(GHashState *g,
1107                                           uint32_t ghashCellIdx) {
1108   GHashCell cell = g->table.table[ghashCellIdx];
1109   return TypeIndex::fromArrayIndex(cell.getGHashIdx());
1110 }
1111 
1112 // Fill in a TPI or IPI index map using ghashes. For each source type, use its
1113 // ghash to lookup its final type index in the PDB, and store that in the map.
1114 void TpiSource::fillMapFromGHashes(GHashState *g,
1115                                    SmallVectorImpl<TypeIndex> &mapToFill) {
1116   for (size_t i = 0, e = ghashes.size(); i < e; ++i) {
1117     TypeIndex fakeCellIndex = indexMapStorage[i];
1118     if (fakeCellIndex.isSimple())
1119       mapToFill[i] = fakeCellIndex;
1120     else
1121       mapToFill[i] = loadPdbTypeIndexFromCell(g, fakeCellIndex.toArrayIndex());
1122   }
1123 }
1124 
1125 void TpiSource::clearGHashes() {
1126   for (TpiSource *src : TpiSource::instances) {
1127     if (src->ownedGHashes)
1128       delete[] src->ghashes.data();
1129     src->ghashes = {};
1130     src->isItemIndex.clear();
1131     src->uniqueTypes.clear();
1132   }
1133 }
1134