blob: 9d78ddc0b8bfa93ae54ffb86f9ec0773ee5cc867 [file] [log] [blame]
Richard Smith2ae84682018-08-24 22:31:51 +00001//===----------------- ItaniumManglingCanonicalizer.cpp -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is dual licensed under the MIT and the University of Illinois Open
6// Source Licenses. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/Support/ItaniumManglingCanonicalizer.h"
11
12#include "llvm/ADT/FoldingSet.h"
13#include "llvm/ADT/StringRef.h"
14#include "llvm/Demangle/ItaniumDemangle.h"
15#include "llvm/Support/Allocator.h"
16
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/FoldingSet.h"
19#include "llvm/ADT/StringRef.h"
20
21using namespace llvm;
22using llvm::itanium_demangle::ForwardTemplateReference;
23using llvm::itanium_demangle::Node;
24using llvm::itanium_demangle::NodeKind;
25
26namespace {
27struct FoldingSetNodeIDBuilder {
28 llvm::FoldingSetNodeID &ID;
29 void operator()(const Node *P) { ID.AddPointer(P); }
30 void operator()(StringView Str) {
31 ID.AddString(llvm::StringRef(Str.begin(), Str.size()));
32 }
33 template<typename T>
34 typename std::enable_if<std::is_integral<T>::value ||
35 std::is_enum<T>::value>::type
36 operator()(T V) {
37 ID.AddInteger((unsigned long long)V);
38 }
39 void operator()(itanium_demangle::NodeOrString NS) {
40 if (NS.isNode()) {
41 ID.AddInteger(0);
42 (*this)(NS.asNode());
43 } else if (NS.isString()) {
44 ID.AddInteger(1);
45 (*this)(NS.asString());
46 } else {
47 ID.AddInteger(2);
48 }
49 }
50 void operator()(itanium_demangle::NodeArray A) {
51 ID.AddInteger(A.size());
52 for (const Node *N : A)
53 (*this)(N);
54 }
55};
56
57template<typename ...T>
58void profileCtor(llvm::FoldingSetNodeID &ID, Node::Kind K, T ...V) {
59 FoldingSetNodeIDBuilder Builder = {ID};
60 Builder(K);
61 int VisitInOrder[] = {
62 (Builder(V), 0) ...,
63 0 // Avoid empty array if there are no arguments.
64 };
65 (void)VisitInOrder;
66}
67
68// FIXME: Convert this to a generic lambda when possible.
69template<typename NodeT> struct ProfileSpecificNode {
70 FoldingSetNodeID &ID;
71 template<typename ...T> void operator()(T ...V) {
72 profileCtor(ID, NodeKind<NodeT>::Kind, V...);
73 }
74};
75
76struct ProfileNode {
77 FoldingSetNodeID &ID;
78 template<typename NodeT> void operator()(const NodeT *N) {
79 N->match(ProfileSpecificNode<NodeT>{ID});
80 }
81};
82
83template<> void ProfileNode::operator()(const ForwardTemplateReference *N) {
84 llvm_unreachable("should never canonicalize a ForwardTemplateReference");
85};
86
87void profileNode(llvm::FoldingSetNodeID &ID, const Node *N) {
88 N->visit(ProfileNode{ID});
89}
90
91class FoldingNodeAllocator {
92 class alignas(alignof(Node *)) NodeHeader : public llvm::FoldingSetNode {
93 public:
94 // 'Node' in this context names the injected-class-name of the base class.
95 itanium_demangle::Node *getNode() {
96 return reinterpret_cast<itanium_demangle::Node *>(this + 1);
97 }
98 void Profile(llvm::FoldingSetNodeID &ID) { profileNode(ID, getNode()); }
99 };
100
101 BumpPtrAllocator RawAlloc;
102 llvm::FoldingSet<NodeHeader> Nodes;
103
104public:
105 void reset() {}
106
107 template<typename T, typename ...Args>
108 std::pair<Node*, bool> getOrCreateNode(Args &&...As) {
109 llvm::FoldingSetNodeID ID;
110 profileCtor(ID, NodeKind<T>::Kind, As...);
111
112 void *InsertPos;
113 if (NodeHeader *Existing = Nodes.FindNodeOrInsertPos(ID, InsertPos))
114 return {static_cast<T*>(Existing->getNode()), false};
115
116 static_assert(alignof(T) <= alignof(NodeHeader),
117 "underaligned node header for specific node kind");
118 void *Storage =
119 RawAlloc.Allocate(sizeof(NodeHeader) + sizeof(T), alignof(NodeHeader));
120 NodeHeader *New = new (Storage) NodeHeader;
121 T *Result = new (New->getNode()) T(std::forward<Args>(As)...);
122 Nodes.InsertNode(New, InsertPos);
123 return {Result, true};
124 }
125
126 template<typename T, typename... Args>
127 Node *makeNode(Args &&...As) {
128 return getOrCreateNode<T>(std::forward<Args>(As)...).first;
129 }
130
131 void *allocateNodeArray(size_t sz) {
132 return RawAlloc.Allocate(sizeof(Node *) * sz, alignof(Node *));
133 }
134};
135
136// FIXME: Don't canonicalize forward template references for now, because they
137// contain state (the resolved template node) that's not known at their point
138// of creation.
139template<>
140std::pair<Node *, bool>
141FoldingNodeAllocator::getOrCreateNode<ForwardTemplateReference>(size_t &Index) {
142 return {new (RawAlloc.Allocate(sizeof(ForwardTemplateReference),
143 alignof(ForwardTemplateReference)))
144 ForwardTemplateReference(Index),
145 true};
146}
147
148class CanonicalizerAllocator : public FoldingNodeAllocator {
149 Node *MostRecentlyCreated = nullptr;
150 Node *TrackedNode = nullptr;
151 bool TrackedNodeIsUsed = false;
152 llvm::SmallDenseMap<Node*, Node*, 32> Remappings;
153
154 template<typename T, typename ...Args> Node *makeNodeSimple(Args &&...As) {
155 std::pair<Node *, bool> Result =
156 getOrCreateNode<T>(std::forward<Args>(As)...);
157 if (Result.second) {
158 // Node is new. Make a note of that.
159 MostRecentlyCreated = Result.first;
160 } else {
161 // Node is pre-existing; check if it's in our remapping table.
162 if (auto *N = Remappings.lookup(Result.first)) {
163 Result.first = N;
164 assert(Remappings.find(Result.first) == Remappings.end() &&
165 "should never need multiple remap steps");
166 }
167 if (Result.first == TrackedNode)
168 TrackedNodeIsUsed = true;
169 }
170 return Result.first;
171 }
172
173 /// Helper to allow makeNode to be partially-specialized on T.
174 template<typename T> struct MakeNodeImpl {
175 CanonicalizerAllocator &Self;
176 template<typename ...Args> Node *make(Args &&...As) {
177 return Self.makeNodeSimple<T>(std::forward<Args>(As)...);
178 }
179 };
180
181public:
182 template<typename T, typename ...Args> Node *makeNode(Args &&...As) {
183 return MakeNodeImpl<T>{*this}.make(std::forward<Args>(As)...);
184 }
185
186 void reset() { MostRecentlyCreated = nullptr; }
187
188 void addRemapping(Node *A, Node *B) {
189 // Note, we don't need to check whether B is also remapped, because if it
190 // was we would have already remapped it when building it.
191 Remappings.insert(std::make_pair(A, B));
192 }
193
194 bool isMostRecentlyCreated(Node *N) const { return MostRecentlyCreated == N; }
195
196 void trackUsesOf(Node *N) {
197 TrackedNode = N;
198 TrackedNodeIsUsed = false;
199 }
200 bool trackedNodeIsUsed() const { return TrackedNodeIsUsed; }
201};
202
203/// Convert St3foo to NSt3fooE so that equivalences naming one also affect the
204/// other.
205template<>
206struct CanonicalizerAllocator::MakeNodeImpl<
207 itanium_demangle::StdQualifiedName> {
208 CanonicalizerAllocator &Self;
209 Node *make(Node *Child) {
210 Node *StdNamespace = Self.makeNode<itanium_demangle::NameType>("std");
211 if (!StdNamespace)
212 return nullptr;
213 return Self.makeNode<itanium_demangle::NestedName>(StdNamespace, Child);
214 }
215};
216
217// FIXME: Also expand built-in substitutions?
218
219using CanonicalizingDemangler = itanium_demangle::Db<CanonicalizerAllocator>;
220}
221
222struct ItaniumManglingCanonicalizer::Impl {
223 CanonicalizingDemangler Demangler = {nullptr, nullptr};
224};
225
226ItaniumManglingCanonicalizer::ItaniumManglingCanonicalizer() : P(new Impl) {}
227ItaniumManglingCanonicalizer::~ItaniumManglingCanonicalizer() { delete P; }
228
229ItaniumManglingCanonicalizer::EquivalenceError
230ItaniumManglingCanonicalizer::addEquivalence(FragmentKind Kind, StringRef First,
231 StringRef Second) {
232 auto &Alloc = P->Demangler.ASTAllocator;
233
234 auto Parse = [&](StringRef Str) {
235 P->Demangler.reset(Str.begin(), Str.end());
236 Node *N = nullptr;
237 switch (Kind) {
238 // A <name>, with minor extensions to allow arbitrary namespace and
239 // template names that can't easily be written as <name>s.
240 case FragmentKind::Name:
241 // Very special case: allow "St" as a shorthand for "3std". It's not
242 // valid as a <name> mangling, but is nonetheless the most natural
243 // way to name the 'std' namespace.
244 if (Str.size() == 2 && P->Demangler.consumeIf("St"))
245 N = P->Demangler.make<itanium_demangle::NameType>("std");
246 // We permit substitutions to name templates without their template
247 // arguments. This mostly just falls out, as almost all template names
248 // are valid as <name>s, but we also want to parse <substitution>s as
249 // <name>s, even though they're not.
250 else if (Str.startswith("S"))
251 // Parse the substitution and optional following template arguments.
252 N = P->Demangler.parseType();
253 else
254 N = P->Demangler.parseName();
255 break;
256
257 // A <type>.
258 case FragmentKind::Type:
259 N = P->Demangler.parseType();
260 break;
261
262 // An <encoding>.
263 case FragmentKind::Encoding:
264 N = P->Demangler.parseEncoding();
265 break;
266 }
267
268 // If we have trailing junk, the mangling is invalid.
269 if (P->Demangler.numLeft() != 0)
270 N = nullptr;
271
272 // If any node was created after N, then we cannot safely remap it because
273 // it might already be in use by another node.
274 return std::make_pair(N, Alloc.isMostRecentlyCreated(N));
275 };
276
277 Node *FirstNode, *SecondNode;
278 bool FirstIsNew, SecondIsNew;
279
280 std::tie(FirstNode, FirstIsNew) = Parse(First);
281 if (!FirstNode)
282 return EquivalenceError::InvalidFirstMangling;
283
284 Alloc.trackUsesOf(FirstNode);
285 std::tie(SecondNode, SecondIsNew) = Parse(Second);
286 if (!SecondNode)
287 return EquivalenceError::InvalidSecondMangling;
288
289 // If they're already equivalent, there's nothing to do.
290 if (FirstNode == SecondNode)
291 return EquivalenceError::Success;
292
293 if (FirstIsNew && !Alloc.trackedNodeIsUsed())
294 Alloc.addRemapping(FirstNode, SecondNode);
295 else if (SecondIsNew)
296 Alloc.addRemapping(SecondNode, FirstNode);
297 else
298 return EquivalenceError::ManglingAlreadyUsed;
299
300 return EquivalenceError::Success;
301}
302
303ItaniumManglingCanonicalizer::Key
304ItaniumManglingCanonicalizer::canonicalize(StringRef Mangling) {
305 P->Demangler.reset(Mangling.begin(), Mangling.end());
306 return reinterpret_cast<Key>(P->Demangler.parse());
307}