blob: 24e600a5c469a8820d9c56074938ef9b2ed160a8 [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;
Erik Pilkington5094e5e2019-01-17 20:37:51 +000025using llvm::itanium_demangle::StringView;
Richard Smith2ae84682018-08-24 22:31:51 +000026
27namespace {
28struct FoldingSetNodeIDBuilder {
29 llvm::FoldingSetNodeID &ID;
30 void operator()(const Node *P) { ID.AddPointer(P); }
31 void operator()(StringView Str) {
32 ID.AddString(llvm::StringRef(Str.begin(), Str.size()));
33 }
34 template<typename T>
35 typename std::enable_if<std::is_integral<T>::value ||
36 std::is_enum<T>::value>::type
37 operator()(T V) {
38 ID.AddInteger((unsigned long long)V);
39 }
40 void operator()(itanium_demangle::NodeOrString NS) {
41 if (NS.isNode()) {
42 ID.AddInteger(0);
43 (*this)(NS.asNode());
44 } else if (NS.isString()) {
45 ID.AddInteger(1);
46 (*this)(NS.asString());
47 } else {
48 ID.AddInteger(2);
49 }
50 }
51 void operator()(itanium_demangle::NodeArray A) {
52 ID.AddInteger(A.size());
53 for (const Node *N : A)
54 (*this)(N);
55 }
56};
57
58template<typename ...T>
59void profileCtor(llvm::FoldingSetNodeID &ID, Node::Kind K, T ...V) {
60 FoldingSetNodeIDBuilder Builder = {ID};
61 Builder(K);
62 int VisitInOrder[] = {
63 (Builder(V), 0) ...,
64 0 // Avoid empty array if there are no arguments.
65 };
66 (void)VisitInOrder;
67}
68
69// FIXME: Convert this to a generic lambda when possible.
70template<typename NodeT> struct ProfileSpecificNode {
71 FoldingSetNodeID &ID;
72 template<typename ...T> void operator()(T ...V) {
73 profileCtor(ID, NodeKind<NodeT>::Kind, V...);
74 }
75};
76
77struct ProfileNode {
78 FoldingSetNodeID &ID;
79 template<typename NodeT> void operator()(const NodeT *N) {
80 N->match(ProfileSpecificNode<NodeT>{ID});
81 }
82};
83
84template<> void ProfileNode::operator()(const ForwardTemplateReference *N) {
85 llvm_unreachable("should never canonicalize a ForwardTemplateReference");
Simon Pilgrim98947332018-08-25 16:49:35 +000086}
Richard Smith2ae84682018-08-24 22:31:51 +000087
88void profileNode(llvm::FoldingSetNodeID &ID, const Node *N) {
89 N->visit(ProfileNode{ID});
90}
91
92class FoldingNodeAllocator {
93 class alignas(alignof(Node *)) NodeHeader : public llvm::FoldingSetNode {
94 public:
95 // 'Node' in this context names the injected-class-name of the base class.
96 itanium_demangle::Node *getNode() {
97 return reinterpret_cast<itanium_demangle::Node *>(this + 1);
98 }
99 void Profile(llvm::FoldingSetNodeID &ID) { profileNode(ID, getNode()); }
100 };
101
102 BumpPtrAllocator RawAlloc;
103 llvm::FoldingSet<NodeHeader> Nodes;
104
105public:
106 void reset() {}
107
Chandler Carruthd38d9502018-08-26 09:17:49 +0000108 template <typename T, typename... Args>
109 std::pair<Node *, bool> getOrCreateNode(bool CreateNewNodes, Args &&... As) {
110 // FIXME: Don't canonicalize forward template references for now, because
111 // they contain state (the resolved template node) that's not known at their
112 // point of creation.
113 if (std::is_same<T, ForwardTemplateReference>::value) {
114 // Note that we don't use if-constexpr here and so we must still write
115 // this code in a generic form.
116 return {new (RawAlloc.Allocate(sizeof(T), alignof(T)))
117 T(std::forward<Args>(As)...),
118 true};
119 }
120
Richard Smith2ae84682018-08-24 22:31:51 +0000121 llvm::FoldingSetNodeID ID;
122 profileCtor(ID, NodeKind<T>::Kind, As...);
123
124 void *InsertPos;
125 if (NodeHeader *Existing = Nodes.FindNodeOrInsertPos(ID, InsertPos))
126 return {static_cast<T*>(Existing->getNode()), false};
127
Richard Smith9c2e4f32018-08-24 23:26:05 +0000128 if (!CreateNewNodes)
129 return {nullptr, true};
130
Richard Smith2ae84682018-08-24 22:31:51 +0000131 static_assert(alignof(T) <= alignof(NodeHeader),
132 "underaligned node header for specific node kind");
133 void *Storage =
134 RawAlloc.Allocate(sizeof(NodeHeader) + sizeof(T), alignof(NodeHeader));
135 NodeHeader *New = new (Storage) NodeHeader;
136 T *Result = new (New->getNode()) T(std::forward<Args>(As)...);
137 Nodes.InsertNode(New, InsertPos);
138 return {Result, true};
139 }
140
141 template<typename T, typename... Args>
142 Node *makeNode(Args &&...As) {
Richard Smith9c2e4f32018-08-24 23:26:05 +0000143 return getOrCreateNode<T>(true, std::forward<Args>(As)...).first;
Richard Smith2ae84682018-08-24 22:31:51 +0000144 }
145
146 void *allocateNodeArray(size_t sz) {
147 return RawAlloc.Allocate(sizeof(Node *) * sz, alignof(Node *));
148 }
149};
150
Richard Smith2ae84682018-08-24 22:31:51 +0000151class CanonicalizerAllocator : public FoldingNodeAllocator {
152 Node *MostRecentlyCreated = nullptr;
153 Node *TrackedNode = nullptr;
154 bool TrackedNodeIsUsed = false;
Richard Smith9c2e4f32018-08-24 23:26:05 +0000155 bool CreateNewNodes = true;
Richard Smith2ae84682018-08-24 22:31:51 +0000156 llvm::SmallDenseMap<Node*, Node*, 32> Remappings;
157
158 template<typename T, typename ...Args> Node *makeNodeSimple(Args &&...As) {
159 std::pair<Node *, bool> Result =
Richard Smith9c2e4f32018-08-24 23:26:05 +0000160 getOrCreateNode<T>(CreateNewNodes, std::forward<Args>(As)...);
Richard Smith2ae84682018-08-24 22:31:51 +0000161 if (Result.second) {
162 // Node is new. Make a note of that.
163 MostRecentlyCreated = Result.first;
Richard Smith9c2e4f32018-08-24 23:26:05 +0000164 } else if (Result.first) {
Richard Smith2ae84682018-08-24 22:31:51 +0000165 // Node is pre-existing; check if it's in our remapping table.
166 if (auto *N = Remappings.lookup(Result.first)) {
167 Result.first = N;
168 assert(Remappings.find(Result.first) == Remappings.end() &&
169 "should never need multiple remap steps");
170 }
171 if (Result.first == TrackedNode)
172 TrackedNodeIsUsed = true;
173 }
174 return Result.first;
175 }
176
177 /// Helper to allow makeNode to be partially-specialized on T.
178 template<typename T> struct MakeNodeImpl {
179 CanonicalizerAllocator &Self;
180 template<typename ...Args> Node *make(Args &&...As) {
181 return Self.makeNodeSimple<T>(std::forward<Args>(As)...);
182 }
183 };
184
185public:
186 template<typename T, typename ...Args> Node *makeNode(Args &&...As) {
187 return MakeNodeImpl<T>{*this}.make(std::forward<Args>(As)...);
188 }
189
190 void reset() { MostRecentlyCreated = nullptr; }
191
Richard Smith9c2e4f32018-08-24 23:26:05 +0000192 void setCreateNewNodes(bool CNN) { CreateNewNodes = CNN; }
193
Richard Smith2ae84682018-08-24 22:31:51 +0000194 void addRemapping(Node *A, Node *B) {
195 // Note, we don't need to check whether B is also remapped, because if it
196 // was we would have already remapped it when building it.
197 Remappings.insert(std::make_pair(A, B));
198 }
199
200 bool isMostRecentlyCreated(Node *N) const { return MostRecentlyCreated == N; }
201
202 void trackUsesOf(Node *N) {
203 TrackedNode = N;
204 TrackedNodeIsUsed = false;
205 }
206 bool trackedNodeIsUsed() const { return TrackedNodeIsUsed; }
207};
208
209/// Convert St3foo to NSt3fooE so that equivalences naming one also affect the
210/// other.
211template<>
212struct CanonicalizerAllocator::MakeNodeImpl<
213 itanium_demangle::StdQualifiedName> {
214 CanonicalizerAllocator &Self;
215 Node *make(Node *Child) {
216 Node *StdNamespace = Self.makeNode<itanium_demangle::NameType>("std");
217 if (!StdNamespace)
218 return nullptr;
219 return Self.makeNode<itanium_demangle::NestedName>(StdNamespace, Child);
220 }
221};
222
223// FIXME: Also expand built-in substitutions?
224
Pavel Labathf4c15822018-10-17 18:50:25 +0000225using CanonicalizingDemangler =
226 itanium_demangle::ManglingParser<CanonicalizerAllocator>;
Richard Smith2ae84682018-08-24 22:31:51 +0000227}
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}