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 {
59 MDNodeElement(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {}
66 virtual void deleted();
67 virtual void allUsesReplacedWith(Value *NV);
69 } // end namespace llvm.
72 void MDNodeElement::deleted() {
73 Parent->replaceElement(this, 0);
76 void MDNodeElement::allUsesReplacedWith(Value *NV) {
77 Parent->replaceElement(this, NV);
82 //===----------------------------------------------------------------------===//
83 // MDNode implementation.
86 /// getOperandPtr - Helper function to get the MDNodeElement's coallocated on
87 /// the end of the MDNode.
88 static MDNodeElement *getOperandPtr(MDNode *N, unsigned Op) {
89 assert(Op < N->getNumElements() && "Invalid operand number");
90 return reinterpret_cast<MDNodeElement*>(N+1)+Op;
93 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals,
95 : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
96 NumOperands = NumVals;
99 setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit);
101 // Initialize the operand list, which is co-allocated on the end of the node.
102 for (MDNodeElement *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
103 Op != E; ++Op, ++Vals)
104 new (Op) MDNodeElement(*Vals, this);
108 /// ~MDNode - Destroy MDNode.
110 assert((getSubclassDataFromValue() & DestroyFlag) != 0 &&
111 "Not being destroyed through destroy()?");
112 if (!isNotUniqued()) {
113 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
114 pImpl->MDNodeSet.RemoveNode(this);
117 // Destroy the operands.
118 for (MDNodeElement *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
120 Op->~MDNodeElement();
123 // destroy - Delete this node. Only when there are no uses.
124 void MDNode::destroy() {
125 setValueSubclassData(getSubclassDataFromValue() | DestroyFlag);
126 // Placement delete, the free the memory.
132 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals,
133 bool isFunctionLocal) {
134 LLVMContextImpl *pImpl = Context.pImpl;
136 for (unsigned i = 0; i != NumVals; ++i)
137 ID.AddPointer(Vals[i]);
140 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
142 // Coallocate space for the node and elements together, then placement new.
143 void *Ptr = malloc(sizeof(MDNode)+NumVals*sizeof(MDNodeElement));
144 N = new (Ptr) MDNode(Context, Vals, NumVals, isFunctionLocal);
146 // InsertPoint will have been set by the FindNodeOrInsertPos call.
147 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
152 /// getElement - Return specified element.
153 Value *MDNode::getElement(unsigned i) const {
154 return *getOperandPtr(const_cast<MDNode*>(this), i);
157 void MDNode::Profile(FoldingSetNodeID &ID) const {
158 for (unsigned i = 0, e = getNumElements(); i != e; ++i)
159 ID.AddPointer(getElement(i));
163 // Replace value from this node's element list.
164 void MDNode::replaceElement(MDNodeElement *Op, Value *To) {
170 // Update the operand.
173 // If this node is already not being uniqued (because one of the operands
174 // already went to null), then there is nothing else to do here.
175 if (isNotUniqued()) return;
177 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
179 // Remove "this" from the context map. FoldingSet doesn't have to reprofile
180 // this node to remove it, so we don't care what state the operands are in.
181 pImpl->MDNodeSet.RemoveNode(this);
183 // If we are dropping an argument to null, we choose to not unique the MDNode
184 // anymore. This commonly occurs during destruction, and uniquing these
185 // brings little reuse.
191 // Now that the node is out of the folding set, get ready to reinsert it.
192 // First, check to see if another node with the same operands already exists
193 // in the set. If it doesn't exist, this returns the position to insert it.
197 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
200 N->replaceAllUsesWith(this);
202 N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
203 assert(N == 0 && "shouldn't be in the map now!"); (void)N;
206 // InsertPoint will have been set by the FindNodeOrInsertPos call.
207 pImpl->MDNodeSet.InsertNode(this, InsertPoint);
210 //===----------------------------------------------------------------------===//
211 // NamedMDNode implementation.
213 static SmallVector<TrackingVH<MetadataBase>, 4> &getNMDOps(void *Operands) {
214 return *(SmallVector<TrackingVH<MetadataBase>, 4>*)Operands;
217 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
218 MetadataBase *const *MDs,
219 unsigned NumMDs, Module *ParentModule)
220 : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
223 Operands = new SmallVector<TrackingVH<MetadataBase>, 4>();
225 SmallVector<TrackingVH<MetadataBase>, 4> &Node = getNMDOps(Operands);
226 for (unsigned i = 0; i != NumMDs; ++i)
227 Node.push_back(TrackingVH<MetadataBase>(MDs[i]));
230 ParentModule->getNamedMDList().push_back(this);
233 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
234 assert(NMD && "Invalid source NamedMDNode!");
235 SmallVector<MetadataBase *, 4> Elems;
236 Elems.reserve(NMD->getNumElements());
238 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
239 Elems.push_back(NMD->getElement(i));
240 return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
241 Elems.data(), Elems.size(), M);
244 NamedMDNode::~NamedMDNode() {
246 delete &getNMDOps(Operands);
249 /// getNumElements - Return number of NamedMDNode elements.
250 unsigned NamedMDNode::getNumElements() const {
251 return (unsigned)getNMDOps(Operands).size();
254 /// getElement - Return specified element.
255 MetadataBase *NamedMDNode::getElement(unsigned i) const {
256 assert(i < getNumElements() && "Invalid element number!");
257 return getNMDOps(Operands)[i];
260 /// addElement - Add metadata element.
261 void NamedMDNode::addElement(MetadataBase *M) {
262 getNMDOps(Operands).push_back(TrackingVH<MetadataBase>(M));
265 /// eraseFromParent - Drop all references and remove the node from parent
267 void NamedMDNode::eraseFromParent() {
268 getParent()->getNamedMDList().erase(this);
271 /// dropAllReferences - Remove all uses and clear node vector.
272 void NamedMDNode::dropAllReferences() {
273 getNMDOps(Operands).clear();
277 //===----------------------------------------------------------------------===//
278 // LLVMContext MDKind naming implementation.
282 /// isValidName - Return true if Name is a valid custom metadata handler name.
283 static bool isValidName(StringRef MDName) {
287 if (!isalpha(MDName[0]))
290 for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
292 if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
299 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
300 unsigned LLVMContext::getMDKindID(StringRef Name) const {
301 assert(isValidName(Name) && "Invalid MDNode name");
303 unsigned &Entry = pImpl->CustomMDKindNames[Name];
305 // If this is new, assign it its ID.
306 if (Entry == 0) Entry = pImpl->CustomMDKindNames.size();
310 /// getHandlerNames - Populate client supplied smallvector using custome
311 /// metadata name and ID.
312 void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
313 Names.resize(pImpl->CustomMDKindNames.size()+1);
315 for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
316 E = pImpl->CustomMDKindNames.end(); I != E; ++I)
317 // MD Handlers are numbered from 1.
318 Names[I->second] = I->first();
321 //===----------------------------------------------------------------------===//
322 // Instruction Metadata method implementations.
325 void Instruction::setMetadata(const char *Kind, MDNode *Node) {
326 if (Node == 0 && !hasMetadata()) return;
327 setMetadata(getContext().getMDKindID(Kind), Node);
330 MDNode *Instruction::getMetadataImpl(const char *Kind) const {
331 return getMetadataImpl(getContext().getMDKindID(Kind));
334 /// setMetadata - Set the metadata of of the specified kind to the specified
335 /// node. This updates/replaces metadata if already present, or removes it if
337 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
338 if (Node == 0 && !hasMetadata()) return;
340 // Handle the case when we're adding/updating metadata on an instruction.
342 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
343 assert(!Info.empty() == hasMetadata() && "HasMetadata bit is wonked");
345 setHasMetadata(true);
347 // Handle replacement of an existing value.
348 for (unsigned i = 0, e = Info.size(); i != e; ++i)
349 if (Info[i].first == KindID) {
350 Info[i].second = Node;
355 // No replacement, just add it to the list.
356 Info.push_back(std::make_pair(KindID, Node));
360 // Otherwise, we're removing metadata from an instruction.
361 assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
362 "HasMetadata bit out of date!");
363 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
365 // Common case is removing the only entry.
366 if (Info.size() == 1 && Info[0].first == KindID) {
367 getContext().pImpl->MetadataStore.erase(this);
368 setHasMetadata(false);
372 // Handle replacement of an existing value.
373 for (unsigned i = 0, e = Info.size(); i != e; ++i)
374 if (Info[i].first == KindID) {
375 Info[i] = Info.back();
377 assert(!Info.empty() && "Removing last entry should be handled above");
380 // Otherwise, removing an entry that doesn't exist on the instruction.
383 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
384 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
385 assert(hasMetadata() && !Info.empty() && "Shouldn't have called this");
387 for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end();
389 if (I->first == KindID)
394 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
395 MDNode*> > &Result)const {
396 assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
397 "Shouldn't have called this");
398 const LLVMContextImpl::MDMapTy &Info =
399 getContext().pImpl->MetadataStore.find(this)->second;
400 assert(!Info.empty() && "Shouldn't have called this");
403 Result.append(Info.begin(), Info.end());
405 // Sort the resulting array so it is stable.
406 if (Result.size() > 1)
407 array_pod_sort(Result.begin(), Result.end());
410 /// removeAllMetadata - Remove all metadata from this instruction.
411 void Instruction::removeAllMetadata() {
412 assert(hasMetadata() && "Caller should check");
413 getContext().pImpl->MetadataStore.erase(this);
414 setHasMetadata(false);