1 //===-- Metadata.cpp - Implement Metadata classes -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Metadata classes.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Metadata.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/LLVMContext.h"
17 #include "llvm/Module.h"
18 #include "llvm/Instruction.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "SymbolTableListTraitsImpl.h"
22 #include "llvm/Support/ValueHandle.h"
25 //===----------------------------------------------------------------------===//
26 // MDString implementation.
29 MDString::MDString(LLVMContext &C, StringRef S)
30 : MetadataBase(Type::getMetadataTy(C), Value::MDStringVal), Str(S) {}
32 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
33 LLVMContextImpl *pImpl = Context.pImpl;
34 StringMapEntry<MDString *> &Entry =
35 pImpl->MDStringCache.GetOrCreateValue(Str);
36 MDString *&S = Entry.getValue();
37 if (!S) S = new MDString(Context, Entry.getKey());
41 MDString *MDString::get(LLVMContext &Context, const char *Str) {
42 LLVMContextImpl *pImpl = Context.pImpl;
43 StringMapEntry<MDString *> &Entry =
44 pImpl->MDStringCache.GetOrCreateValue(Str ? StringRef(Str) : StringRef());
45 MDString *&S = Entry.getValue();
46 if (!S) S = new MDString(Context, Entry.getKey());
50 //===----------------------------------------------------------------------===//
51 // MDNodeElement implementation.
54 // Use CallbackVH to hold MDNode elements.
56 class MDNodeElement : public CallbackVH {
60 MDNodeElement(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {}
63 void set(Value *V, MDNode *P) {
68 virtual void deleted();
69 virtual void allUsesReplacedWith(Value *NV);
71 } // end namespace llvm.
74 void MDNodeElement::deleted() {
75 Parent->replaceElement(this, 0);
78 void MDNodeElement::allUsesReplacedWith(Value *NV) {
79 Parent->replaceElement(this, NV);
84 //===----------------------------------------------------------------------===//
85 // MDNode implementation.
88 /// ~MDNode - Destroy MDNode.
90 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
91 pImpl->MDNodeSet.RemoveNode(this);
96 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals,
98 : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
99 NumOperands = NumVals;
100 Operands = new MDNodeElement[NumOperands];
102 for (unsigned i = 0; i != NumVals; ++i)
103 Operands[i].set(Vals[i], this);
106 setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit);
109 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals,
110 bool isFunctionLocal) {
111 LLVMContextImpl *pImpl = Context.pImpl;
113 for (unsigned i = 0; i != NumVals; ++i)
114 ID.AddPointer(Vals[i]);
117 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
119 // InsertPoint will have been set by the FindNodeOrInsertPos call.
120 N = new MDNode(Context, Vals, NumVals, isFunctionLocal);
121 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
126 void MDNode::Profile(FoldingSetNodeID &ID) const {
127 for (unsigned i = 0, e = getNumElements(); i != e; ++i)
128 ID.AddPointer(getElement(i));
129 // HASH TABLE COLLISIONS?
130 // DO NOT REINSERT AFTER AN OPERAND DROPS TO NULL!
134 /// getElement - Return specified element.
135 Value *MDNode::getElement(unsigned i) const {
136 assert(i < getNumElements() && "Invalid element number!");
142 // Replace value from this node's element list.
143 void MDNode::replaceElement(MDNodeElement *Op, Value *To) {
149 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
151 // Remove "this" from the context map. FoldingSet doesn't have to reprofile
152 // this node to remove it, so we don't care what state the operands are in.
153 pImpl->MDNodeSet.RemoveNode(this);
155 // Update the operand.
158 // Insert updated "this" into the context's folding node set.
159 // If a node with same element list already exist then before inserting
160 // updated "this" into the folding node set, replace all uses of existing
161 // node with updated "this" node.
165 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
168 N->replaceAllUsesWith(this);
170 N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
171 assert(N == 0 && "shouldn't be in the map now!"); (void)N;
174 // InsertPoint will have been set by the FindNodeOrInsertPos call.
175 pImpl->MDNodeSet.InsertNode(this, InsertPoint);
178 //===----------------------------------------------------------------------===//
179 // NamedMDNode implementation.
181 static SmallVector<TrackingVH<MetadataBase>, 4> &getNMDOps(void *Operands) {
182 return *(SmallVector<TrackingVH<MetadataBase>, 4>*)Operands;
185 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
186 MetadataBase *const *MDs,
187 unsigned NumMDs, Module *ParentModule)
188 : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
191 Operands = new SmallVector<TrackingVH<MetadataBase>, 4>();
193 SmallVector<TrackingVH<MetadataBase>, 4> &Node = getNMDOps(Operands);
194 for (unsigned i = 0; i != NumMDs; ++i)
195 Node.push_back(TrackingVH<MetadataBase>(MDs[i]));
198 ParentModule->getNamedMDList().push_back(this);
201 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
202 assert(NMD && "Invalid source NamedMDNode!");
203 SmallVector<MetadataBase *, 4> Elems;
204 Elems.reserve(NMD->getNumElements());
206 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
207 Elems.push_back(NMD->getElement(i));
208 return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
209 Elems.data(), Elems.size(), M);
212 NamedMDNode::~NamedMDNode() {
214 delete &getNMDOps(Operands);
217 /// getNumElements - Return number of NamedMDNode elements.
218 unsigned NamedMDNode::getNumElements() const {
219 return (unsigned)getNMDOps(Operands).size();
222 /// getElement - Return specified element.
223 MetadataBase *NamedMDNode::getElement(unsigned i) const {
224 assert(i < getNumElements() && "Invalid element number!");
225 return getNMDOps(Operands)[i];
228 /// addElement - Add metadata element.
229 void NamedMDNode::addElement(MetadataBase *M) {
230 getNMDOps(Operands).push_back(TrackingVH<MetadataBase>(M));
233 /// eraseFromParent - Drop all references and remove the node from parent
235 void NamedMDNode::eraseFromParent() {
236 getParent()->getNamedMDList().erase(this);
239 /// dropAllReferences - Remove all uses and clear node vector.
240 void NamedMDNode::dropAllReferences() {
241 getNMDOps(Operands).clear();
245 //===----------------------------------------------------------------------===//
246 // MetadataContext implementation.
250 /// isValidName - Return true if Name is a valid custom metadata handler name.
251 static bool isValidName(StringRef MDName) {
255 if (!isalpha(MDName[0]))
258 for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
260 if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
267 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
268 unsigned LLVMContext::getMDKindID(StringRef Name) const {
269 assert(isValidName(Name) && "Invalid MDNode name");
271 unsigned &Entry = pImpl->CustomMDKindNames[Name];
273 // If this is new, assign it its ID.
274 if (Entry == 0) Entry = pImpl->CustomMDKindNames.size();
278 /// getHandlerNames - Populate client supplied smallvector using custome
279 /// metadata name and ID.
280 void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
281 Names.resize(pImpl->CustomMDKindNames.size()+1);
283 for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
284 E = pImpl->CustomMDKindNames.end(); I != E; ++I)
285 // MD Handlers are numbered from 1.
286 Names[I->second] = I->first();
289 //===----------------------------------------------------------------------===//
290 // Instruction Metadata method implementations.
293 void Instruction::setMetadata(const char *Kind, MDNode *Node) {
294 if (Node == 0 && !hasMetadata()) return;
295 setMetadata(getContext().getMDKindID(Kind), Node);
298 MDNode *Instruction::getMetadataImpl(const char *Kind) const {
299 return getMetadataImpl(getContext().getMDKindID(Kind));
302 /// setMetadata - Set the metadata of of the specified kind to the specified
303 /// node. This updates/replaces metadata if already present, or removes it if
305 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
306 if (Node == 0 && !hasMetadata()) return;
308 // Handle the case when we're adding/updating metadata on an instruction.
310 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
311 assert(!Info.empty() == hasMetadata() && "HasMetadata bit is wonked");
313 setHasMetadata(true);
315 // Handle replacement of an existing value.
316 for (unsigned i = 0, e = Info.size(); i != e; ++i)
317 if (Info[i].first == KindID) {
318 Info[i].second = Node;
323 // No replacement, just add it to the list.
324 Info.push_back(std::make_pair(KindID, Node));
328 // Otherwise, we're removing metadata from an instruction.
329 assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
330 "HasMetadata bit out of date!");
331 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
333 // Common case is removing the only entry.
334 if (Info.size() == 1 && Info[0].first == KindID) {
335 getContext().pImpl->MetadataStore.erase(this);
336 setHasMetadata(false);
340 // Handle replacement of an existing value.
341 for (unsigned i = 0, e = Info.size(); i != e; ++i)
342 if (Info[i].first == KindID) {
343 Info[i] = Info.back();
345 assert(!Info.empty() && "Removing last entry should be handled above");
348 // Otherwise, removing an entry that doesn't exist on the instruction.
351 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
352 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
353 assert(hasMetadata() && !Info.empty() && "Shouldn't have called this");
355 for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end();
357 if (I->first == KindID)
362 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
363 MDNode*> > &Result)const {
364 assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
365 "Shouldn't have called this");
366 const LLVMContextImpl::MDMapTy &Info =
367 getContext().pImpl->MetadataStore.find(this)->second;
368 assert(!Info.empty() && "Shouldn't have called this");
371 Result.append(Info.begin(), Info.end());
373 // Sort the resulting array so it is stable.
374 if (Result.size() > 1)
375 array_pod_sort(Result.begin(), Result.end());
378 /// removeAllMetadata - Remove all metadata from this instruction.
379 void Instruction::removeAllMetadata() {
380 assert(hasMetadata() && "Caller should check");
381 getContext().pImpl->MetadataStore.erase(this);
382 setHasMetadata(false);