LLVM 24.0.0git
TypePool.h
Go to the documentation of this file.
1//===- TypePool.h -----------------------------------------------*- C++ -*-===//
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#ifndef LLVM_DWARFLINKER_PARALLEL_TYPEPOOL_H
10#define LLVM_DWARFLINKER_PARALLEL_TYPEPOOL_H
11
12#include "ArrayList.h"
15#include "llvm/ADT/StringMap.h"
16#include "llvm/CodeGen/DIE.h"
19#include <atomic>
20#include <limits>
21#include <variant>
22
23namespace llvm {
24namespace dwarf_linker {
25namespace parallel {
26
27class TypePool;
28class TypeEntryBody;
29
31
32/// A type key is text interleaved with references to other type entries. A
33/// reference stands for the referenced entry's key without copying it. Keys
34/// are interned, so equal references mean equal keys.
35class TypeKey {
36public:
37 /// A maximal run of text, or a reference.
38 using Part = std::variant<StringRef, const TypeEntry *>;
39
40 /// Remove the first part of the non-empty key \p Key and return it.
41 static Part takePart(StringRef &Key);
42
43 /// Compare \p LHS and \p RHS as if every reference were replaced by the key
44 /// it refers to, so the result does not depend on pointer values.
45 static int compare(StringRef LHS, StringRef RHS);
46
47 /// \returns \p Key with every reference replaced by the key it refers to.
48 static std::string expand(StringRef Key);
49
51 assert(!Text.contains(RefMarker) && "text would read as a reference");
52 Bytes += Text;
53 return *this;
54 }
56 assert(C != RefMarker && "text would read as a reference");
57 Bytes += C;
58 return *this;
59 }
60 void appendRef(const TypeEntry *Entry);
61
62 size_t size() const { return Bytes.size(); }
63 void truncate(size_t Size) { Bytes.truncate(Size); }
64 StringRef str() const { return Bytes; }
65
66private:
67 /// DWARF strings cannot contain NUL, so the marker is unambiguous.
68 static constexpr char RefMarker = '\0';
69 static constexpr size_t RefSize = 1 + sizeof(const TypeEntry *);
70
72};
73
74/// Keeps cloned data for the type DIE.
76public:
77 /// Returns copy of type DIE which should be emitted into resulting file.
78 DIE &getFinalDie() const {
79 if (Die)
80 return *Die;
81
83 return *DeclarationDie;
84 }
85
86 /// Returns true if type die entry has only declaration die.
87 bool hasOnlyDeclaration() const { return Die == nullptr; }
88
89 /// Creates type DIE for the specified name.
90 static TypeEntryBody *
92 TypeEntryBody *Result = Allocator.Allocate<TypeEntryBody>();
93 new (Result) TypeEntryBody(Allocator);
94 return Result;
95 }
96
97 /// TypeEntryBody keeps partially cloned DIEs corresponding to this type.
98 /// The two kinds of DIE can be kept: declaration and definition.
99 /// If definition DIE was met while parsing input DWARF then this DIE would
100 /// be used as a final DIE for this type. If definition DIE is not met then
101 /// declaration DIE would be used as a final DIE.
102
103 // Keeps definition die.
104 std::atomic<DIE *> Die = {nullptr};
105
106 // Keeps declaration die.
107 std::atomic<DIE *> DeclarationDie = {nullptr};
108
109 // True if the declaration winner's parent is itself a declaration.
111
112 // Priority of the CU that set Die (lower wins, for deterministic output).
113 // Atomic so it can be read outside the lock for a fast pre-check; the
114 // definitive comparison still happens under the spinlock.
115 std::atomic<uint64_t> DiePriority = {std::numeric_limits<uint64_t>::max()};
116
117 // Priority of the CU that set DeclarationDie (lower wins).
118 uint64_t DeclarationDiePriority = std::numeric_limits<uint64_t>::max();
119
120 // Spinlock for deterministic type DIE allocation.
121 std::atomic_flag Lock = {};
122
123 // Primary key for the comparator: ordinal of this child in its parent's
124 // child list, min-merged across CUs to keep record-like type members in
125 // source order. Sentinel UINT32_MAX sorts after any real observation.
126 // When set, overwrites the default getKey() in TypeComparator.
127 std::atomic<uint32_t> SortKey = {std::numeric_limits<uint32_t>::max()};
128
129 /// Children for current type.
131
132protected:
133 TypeEntryBody() = delete;
138
141};
142
143/// TypePool keeps type descriptors which contain partially cloned DIE
144/// correspinding to each type. Types are identified by names.
146 : ConcurrentHashTableByPtr<StringRef, TypeEntry,
147 llvm::parallel::PerThreadBumpPtrAllocator> {
148public:
151 llvm::parallel::PerThreadBumpPtrAllocator>(
152 Allocator) {
153 Root = TypeEntry::create("", Allocator);
154 Root->getValue().store(TypeEntryBody::create(Allocator));
155 }
156
163
164 /// Create or return existing type entry body for the specified \p Entry.
165 /// Link that entry as child for the specified \p ParentEntry.
166 /// The returned body's \c SortKey starts at the sentinel; callers that want
167 /// the entry to participate in source-order sorting must min-merge their
168 /// per-CU observation into it.
169 /// \returns The existing or created type entry body.
171 TypeEntry *ParentEntry) {
172 TypeEntryBody *DIE = Entry->getValue().load();
173 if (DIE)
174 return DIE;
175
176 TypeEntryBody *NewDIE = TypeEntryBody::create(Allocator);
177 if (Entry->getValue().compare_exchange_strong(DIE, NewDIE)) {
178 ParentEntry->getValue().load()->Children.add(Entry);
179 return NewDIE;
180 }
181
182 return DIE;
183 }
184
185 /// Sort children for each kept type entry.
186 void sortTypes() {
188 SmallVector<TypeEntry *> Worklist = {getRoot()};
189 while (!Worklist.empty()) {
190 TypeEntry *Entry = Worklist.pop_back_val();
191 Entries.push_back(Entry);
192 Entry->getValue().load()->Children.forEach(
193 [&](TypeEntry *Child) { Worklist.push_back(Child); });
194 }
195
196 // The comparator is a total order, so the result does not depend on
197 // scheduling.
198 parallelForEach(Entries, [&](TypeEntry *Entry) {
199 Entry->getValue().load()->Children.sort(TypesComparator,
200 /*Parallel=*/true);
201 });
202 }
203
204 /// Return root for all type entries.
205 TypeEntry *getRoot() const { return Root; }
206
207 /// Return thread local allocator used by pool.
209 return Allocator.getThreadLocalAllocator();
210 }
211
212protected:
213 std::function<bool(const TypeEntry *LHS, const TypeEntry *RHS)>
214 TypesComparator = [](const TypeEntry *LHS, const TypeEntry *RHS) -> bool {
215 uint32_t LK =
216 LHS->getValue().load()->SortKey.load(std::memory_order_relaxed);
217 uint32_t RK =
218 RHS->getValue().load()->SortKey.load(std::memory_order_relaxed);
219 if (LK != RK)
220 return LK < RK;
221 return TypeKey::compare(LHS->getKey(), RHS->getKey()) < 0;
222 };
223
224 // Root of all type entries.
225 TypeEntry *Root = nullptr;
226
227private:
229};
230
231} // end of namespace parallel
232} // end of namespace dwarf_linker
233} // end of namespace llvm
234
235#endif // LLVM_DWARFLINKER_PARALLEL_TYPEPOOL_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
uint64_t uint64_t
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
Basic Register Allocator
This file defines the SmallString class.
Value * RHS
Value * LHS
ConcurrentHashTableByPtr(llvm::parallel::PerThreadBumpPtrAllocator &Allocator, uint64_t EstimatedSize=100000, size_t ThreadsNum=parallel::strategy.compute_thread_count(), size_t InitialNumberOfBuckets=128)
A structured debug information entry.
Definition DIE.h:835
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
const ValueTy & getValue() const
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
static StringMapEntry * create(StringRef key, AllocatorTy &allocator, InitTy &&...initVals)
StringRef first() const
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
This class is a simple list of T structures.
Definition ArrayList.h:24
Keeps cloned data for the type DIE.
Definition TypePool.h:75
ArrayList< TypeEntry *, 5 > Children
Children for current type.
Definition TypePool.h:130
DIE & getFinalDie() const
Returns copy of type DIE which should be emitted into resulting file.
Definition TypePool.h:78
TypeEntryBody(TypeEntryBody &&RHS)=delete
bool hasOnlyDeclaration() const
Returns true if type die entry has only declaration die.
Definition TypePool.h:87
TypeEntryBody(const TypeEntryBody &RHS)=delete
TypeEntryBody(llvm::parallel::PerThreadBumpPtrAllocator &Allocator)
Definition TypePool.h:139
TypeEntryBody & operator=(const TypeEntryBody &RHS)=delete
std::atomic< DIE * > Die
TypeEntryBody keeps partially cloned DIEs corresponding to this type.
Definition TypePool.h:104
static TypeEntryBody * create(llvm::parallel::PerThreadBumpPtrAllocator &Allocator)
Creates type DIE for the specified name.
Definition TypePool.h:91
TypeEntryBody & operator=(const TypeEntryBody &&RHS)=delete
A type key is text interleaved with references to other type entries.
Definition TypePool.h:35
void appendRef(const TypeEntry *Entry)
Definition TypePool.cpp:17
TypeKey & operator+=(StringRef Text)
Definition TypePool.h:50
static Part takePart(StringRef &Key)
Remove the first part of the non-empty key Key and return it.
Definition TypePool.cpp:24
static std::string expand(StringRef Key)
Definition TypePool.cpp:144
std::variant< StringRef, const TypeEntry * > Part
A maximal run of text, or a reference.
Definition TypePool.h:38
static int compare(StringRef LHS, StringRef RHS)
Compare LHS and RHS as if every reference were replaced by the key it refers to, so the result does n...
Definition TypePool.cpp:104
TypePool keeps type descriptors which contain partially cloned DIE correspinding to each type.
Definition TypePool.h:147
BumpPtrAllocator & getThreadLocalAllocator()
Return thread local allocator used by pool.
Definition TypePool.h:208
TypeEntryBody * getOrCreateTypeEntryBody(TypeEntry *Entry, TypeEntry *ParentEntry)
Create or return existing type entry body for the specified Entry.
Definition TypePool.h:170
TypeEntry * insert(StringRef Name)
Definition TypePool.h:157
TypeEntry * getRoot() const
Return root for all type entries.
Definition TypePool.h:205
std::function< bool(const TypeEntry *LHS, const TypeEntry *RHS)> TypesComparator
Definition TypePool.h:214
void sortTypes()
Sort children for each kept type entry.
Definition TypePool.h:186
StringMapEntry< std::atomic< TypeEntryBody * > > TypeEntry
Definition TypePool.h:30
PerThreadAllocator< BumpPtrAllocator > PerThreadBumpPtrAllocator
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
void parallelForEach(IterTy Begin, IterTy End, FuncTy Fn)
Definition Parallel.h:209