blob: 7023305774e3f1cca2b1eb356e5f1fa29f3cee39 [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");
Simon Pilgrim98947332018-08-25 16:49:35 +000085}
Richard Smith2ae84682018-08-24 22:31:51 +000086
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>
Richard Smith9c2e4f32018-08-24 23:26:05 +0000108 std::pair<Node*, bool> getOrCreateNode(bool CreateNewNodes, Args &&...As) {
Richard Smith2ae84682018-08-24 22:31:51 +0000109 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
Richard Smith9c2e4f32018-08-24 23:26:05 +0000116 if (!CreateNewNodes)
117 return {nullptr, true};
118
Richard Smith2ae84682018-08-24 22:31:51 +0000119 static_assert(alignof(T) <= alignof(NodeHeader),
120 "underaligned node header for specific node kind");
121 void *Storage =
122 RawAlloc.Allocate(sizeof(NodeHeader) + sizeof(T), alignof(NodeHeader));
123 NodeHeader *New = new (Storage) NodeHeader;
124 T *Result = new (New->getNode()) T(std::forward<Args>(As)...);
125 Nodes.InsertNode(New, InsertPos);
126 return {Result, true};
127 }
128
129 template<typename T, typename... Args>
130 Node *makeNode(Args &&...As) {
Richard Smith9c2e4f32018-08-24 23:26:05 +0000131 return getOrCreateNode<T>(true, std::forward<Args>(As)...).first;
Richard Smith2ae84682018-08-24 22:31:51 +0000132 }
133
134 void *allocateNodeArray(size_t sz) {
135 return RawAlloc.Allocate(sizeof(Node *) * sz, alignof(Node *));
136 }
137};
138
139// FIXME: Don't canonicalize forward template references for now, because they
140// contain state (the resolved template node) that's not known at their point
141// of creation.
142template<>
143std::pair<Node *, bool>
Richard Smith9c2e4f32018-08-24 23:26:05 +0000144FoldingNodeAllocator::getOrCreateNode<ForwardTemplateReference>(bool,
145 size_t &Index) {
Richard Smith2ae84682018-08-24 22:31:51 +0000146 return {new (RawAlloc.Allocate(sizeof(ForwardTemplateReference),
147 alignof(ForwardTemplateReference)))
148 ForwardTemplateReference(Index),
149 true};
150}
151
152class CanonicalizerAllocator : public FoldingNodeAllocator {
153 Node *MostRecentlyCreated = nullptr;
154 Node *TrackedNode = nullptr;
155 bool TrackedNodeIsUsed = false;
Richard Smith9c2e4f32018-08-24 23:26:05 +0000156 bool CreateNewNodes = true;
Richard Smith2ae84682018-08-24 22:31:51 +0000157 llvm::SmallDenseMap<Node*, Node*, 32> Remappings;
158
159 template<typename T, typename ...Args> Node *makeNodeSimple(Args &&...As) {
160 std::pair<Node *, bool> Result =
Richard Smith9c2e4f32018-08-24 23:26:05 +0000161 getOrCreateNode<T>(CreateNewNodes, std::forward<Args>(As)...);
Richard Smith2ae84682018-08-24 22:31:51 +0000162 if (Result.second) {
163 // Node is new. Make a note of that.
164 MostRecentlyCreated = Result.first;
Richard Smith9c2e4f32018-08-24 23:26:05 +0000165 } else if (Result.first) {
Richard Smith2ae84682018-08-24 22:31:51 +0000166 // Node is pre-existing; check if it's in our remapping table.
167 if (auto *N = Remappings.lookup(Result.first)) {
168 Result.first = N;
169 assert(Remappings.find(Result.first) == Remappings.end() &&
170 "should never need multiple remap steps");
171 }
172 if (Result.first == TrackedNode)
173 TrackedNodeIsUsed = true;
174 }
175 return Result.first;
176 }
177
178 /// Helper to allow makeNode to be partially-specialized on T.
179 template<typename T> struct MakeNodeImpl {
180 CanonicalizerAllocator &Self;
181 template<typename ...Args> Node *make(Args &&...As) {
182 return Self.makeNodeSimple<T>(std::forward<Args>(As)...);
183 }
184 };
185
186public:
187 template<typename T, typename ...Args> Node *makeNode(Args &&...As) {
188 return MakeNodeImpl<T>{*this}.make(std::forward<Args>(As)...);
189 }
190
191 void reset() { MostRecentlyCreated = nullptr; }
192
Richard Smith9c2e4f32018-08-24 23:26:05 +0000193 void setCreateNewNodes(bool CNN) { CreateNewNodes = CNN; }
194
Richard Smith2ae84682018-08-24 22:31:51 +0000195 void addRemapping(Node *A, Node *B) {
196 // Note, we don't need to check whether B is also remapped, because if it
197 // was we would have already remapped it when building it.
198 Remappings.insert(std::make_pair(A, B));
199 }
200
201 bool isMostRecentlyCreated(Node *N) const { return MostRecentlyCreated == N; }
202
203 void trackUsesOf(Node *N) {
204 TrackedNode = N;
205 TrackedNodeIsUsed = false;
206 }
207 bool trackedNodeIsUsed() const { return TrackedNodeIsUsed; }
208};
209
210/// Convert St3foo to NSt3fooE so that equivalences naming one also affect the
211/// other.
212template<>
213struct CanonicalizerAllocator::MakeNodeImpl<
214 itanium_demangle::StdQualifiedName> {
215 CanonicalizerAllocator &Self;
216 Node *make(Node *Child) {
217 Node *StdNamespace = Self.makeNode<itanium_demangle::NameType>("std");
218 if (!StdNamespace)
219 return nullptr;
220 return Self.makeNode<itanium_demangle::NestedName>(StdNamespace, Child);
221 }
222};
223
224// FIXME: Also expand built-in substitutions?
225
226using CanonicalizingDemangler = itanium_demangle::Db<CanonicalizerAllocator>;
227}
228
229struct ItaniumManglingCanonicalizer::Impl {
230 CanonicalizingDemangler Demangler = {nullptr, nullptr};
231};
232
233ItaniumManglingCanonicalizer::ItaniumManglingCanonicalizer() : P(new Impl) {}
234ItaniumManglingCanonicalizer::~ItaniumManglingCanonicalizer() { delete P; }
235
236ItaniumManglingCanonicalizer::EquivalenceError
237ItaniumManglingCanonicalizer::addEquivalence(FragmentKind Kind, StringRef First,
238 StringRef Second) {
239 auto &Alloc = P->Demangler.ASTAllocator;
Richard Smith9c2e4f32018-08-24 23:26:05 +0000240 Alloc.setCreateNewNodes(true);
Richard Smith2ae84682018-08-24 22:31:51 +0000241
242 auto Parse = [&](StringRef Str) {
243 P->Demangler.reset(Str.begin(), Str.end());
244 Node *N = nullptr;
245 switch (Kind) {
246 // A <name>, with minor extensions to allow arbitrary namespace and
247 // template names that can't easily be written as <name>s.
248 case FragmentKind::Name:
249 // Very special case: allow "St" as a shorthand for "3std". It's not
250 // valid as a <name> mangling, but is nonetheless the most natural
251 // way to name the 'std' namespace.
252 if (Str.size() == 2 && P->Demangler.consumeIf("St"))
253 N = P->Demangler.make<itanium_demangle::NameType>("std");
254 // We permit substitutions to name templates without their template
255 // arguments. This mostly just falls out, as almost all template names
256 // are valid as <name>s, but we also want to parse <substitution>s as
257 // <name>s, even though they're not.
258 else if (Str.startswith("S"))
259 // Parse the substitution and optional following template arguments.
260 N = P->Demangler.parseType();
261 else
262 N = P->Demangler.parseName();
263 break;
264
265 // A <type>.
266 case FragmentKind::Type:
267 N = P->Demangler.parseType();
268 break;
269
270 // An <encoding>.
271 case FragmentKind::Encoding:
272 N = P->Demangler.parseEncoding();
273 break;
274 }
275
276 // If we have trailing junk, the mangling is invalid.
277 if (P->Demangler.numLeft() != 0)
278 N = nullptr;
279
280 // If any node was created after N, then we cannot safely remap it because
281 // it might already be in use by another node.
282 return std::make_pair(N, Alloc.isMostRecentlyCreated(N));
283 };
284
285 Node *FirstNode, *SecondNode;
286 bool FirstIsNew, SecondIsNew;
287
288 std::tie(FirstNode, FirstIsNew) = Parse(First);
289 if (!FirstNode)
290 return EquivalenceError::InvalidFirstMangling;
291
292 Alloc.trackUsesOf(FirstNode);
293 std::tie(SecondNode, SecondIsNew) = Parse(Second);
294 if (!SecondNode)
295 return EquivalenceError::InvalidSecondMangling;
296
297 // If they're already equivalent, there's nothing to do.
298 if (FirstNode == SecondNode)
299 return EquivalenceError::Success;
300
301 if (FirstIsNew && !Alloc.trackedNodeIsUsed())
302 Alloc.addRemapping(FirstNode, SecondNode);
303 else if (SecondIsNew)
304 Alloc.addRemapping(SecondNode, FirstNode);
305 else
306 return EquivalenceError::ManglingAlreadyUsed;
307
308 return EquivalenceError::Success;
309}
310
311ItaniumManglingCanonicalizer::Key
312ItaniumManglingCanonicalizer::canonicalize(StringRef Mangling) {
Richard Smith9c2e4f32018-08-24 23:26:05 +0000313 P->Demangler.ASTAllocator.setCreateNewNodes(true);
314 P->Demangler.reset(Mangling.begin(), Mangling.end());
315 return reinterpret_cast<Key>(P->Demangler.parse());
316}
317
318ItaniumManglingCanonicalizer::Key
319ItaniumManglingCanonicalizer::lookup(StringRef Mangling) {
320 P->Demangler.ASTAllocator.setCreateNewNodes(false);
Richard Smith2ae84682018-08-24 22:31:51 +0000321 P->Demangler.reset(Mangling.begin(), Mangling.end());
322 return reinterpret_cast<Key>(P->Demangler.parse());
323}