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 SubclassData |= 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 // MetadataContextImpl implementation.
249 class MetadataContextImpl {
251 typedef std::pair<unsigned, TrackingVH<MDNode> > MDPairTy;
252 typedef SmallVector<MDPairTy, 2> MDMapTy;
253 typedef DenseMap<const Instruction *, MDMapTy> MDStoreTy;
254 friend class BitcodeReader;
257 /// MetadataStore - Collection of metadata used in this context.
258 MDStoreTy MetadataStore;
260 /// MDHandlerNames - Map to hold metadata handler names.
261 StringMap<unsigned> MDHandlerNames;
264 unsigned getMDKindID(StringRef Name);
266 /// getMD - Get the metadata of given kind attached to an Instruction.
267 /// If the metadata is not found then return 0.
268 MDNode *getMD(unsigned Kind, const Instruction *Inst);
270 /// getMDs - Get the metadata attached to an Instruction.
271 void getMDs(const Instruction *Inst,
272 SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs) const;
274 /// addMD - Attach the metadata of given kind to an Instruction.
275 void addMD(unsigned Kind, MDNode *Node, Instruction *Inst);
277 /// removeMD - Remove metadata of given kind attached with an instruction.
278 void removeMD(unsigned Kind, Instruction *Inst);
280 /// removeAllMetadata - Remove all metadata attached with an instruction.
281 void removeAllMetadata(Instruction *Inst);
283 /// copyMD - If metadata is attached with Instruction In1 then attach
284 /// the same metadata to In2.
285 void copyMD(Instruction *In1, Instruction *In2);
287 /// getMDKindNames - Populate client-supplied smallvector using custom
288 /// metadata name and ID.
289 void getMDKindNames(SmallVectorImpl<StringRef> &) const;
291 /// ValueIsDeleted - This handler is used to update metadata store
292 /// when a value is deleted.
293 void ValueIsDeleted(const Value *) {}
294 void ValueIsDeleted(Instruction *Inst) {
295 removeAllMetadata(Inst);
297 void ValueIsRAUWd(Value *V1, Value *V2);
299 /// ValueIsCloned - This handler is used to update metadata store
300 /// when In1 is cloned to create In2.
301 void ValueIsCloned(const Instruction *In1, Instruction *In2);
305 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
306 unsigned MetadataContextImpl::getMDKindID(StringRef Name) {
307 unsigned &Entry = MDHandlerNames[Name];
309 // If this is new, assign it its ID.
310 if (Entry == 0) Entry = MDHandlerNames.size();
315 /// addMD - Attach the metadata of given kind to an Instruction.
316 void MetadataContextImpl::addMD(unsigned MDKind, MDNode *Node,
318 assert(Node && "Invalid null MDNode");
319 Inst->HasMetadata = true;
320 MDMapTy &Info = MetadataStore[Inst];
322 Info.push_back(std::make_pair(MDKind, Node));
323 MetadataStore.insert(std::make_pair(Inst, Info));
327 // If there is an entry for this MDKind then replace it.
328 for (unsigned i = 0, e = Info.size(); i != e; ++i) {
329 MDPairTy &P = Info[i];
330 if (P.first == MDKind) {
331 Info[i] = std::make_pair(MDKind, Node);
336 // Otherwise add a new entry.
337 Info.push_back(std::make_pair(MDKind, Node));
340 /// removeMD - Remove metadata of given kind attached with an instruction.
341 void MetadataContextImpl::removeMD(unsigned Kind, Instruction *Inst) {
342 MDStoreTy::iterator I = MetadataStore.find(Inst);
343 if (I == MetadataStore.end())
346 MDMapTy &Info = I->second;
347 for (MDMapTy::iterator MI = Info.begin(), ME = Info.end(); MI != ME; ++MI) {
349 if (P.first == Kind) {
356 /// removeAllMetadata - Remove all metadata attached with an instruction.
357 void MetadataContextImpl::removeAllMetadata(Instruction *Inst) {
358 MetadataStore.erase(Inst);
359 Inst->HasMetadata = false;
362 /// copyMD - If metadata is attached with Instruction In1 then attach
363 /// the same metadata to In2.
364 void MetadataContextImpl::copyMD(Instruction *In1, Instruction *In2) {
365 assert(In1 && In2 && "Invalid instruction!");
366 MDMapTy &In1Info = MetadataStore[In1];
370 for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
371 addMD(I->first, I->second, In2);
374 /// getMD - Get the metadata of given kind attached to an Instruction.
375 /// If the metadata is not found then return 0.
376 MDNode *MetadataContextImpl::getMD(unsigned MDKind, const Instruction *Inst) {
377 MDMapTy &Info = MetadataStore[Inst];
381 for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I)
382 if (I->first == MDKind)
387 /// getMDs - Get the metadata attached to an Instruction.
388 void MetadataContextImpl::
389 getMDs(const Instruction *Inst,
390 SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs) const {
391 MDStoreTy::const_iterator I = MetadataStore.find(Inst);
392 if (I == MetadataStore.end())
394 MDs.resize(I->second.size());
395 for (MDMapTy::const_iterator MI = I->second.begin(), ME = I->second.end();
397 // MD kinds are numbered from 1.
398 MDs[MI->first - 1] = std::make_pair(MI->first, MI->second);
401 /// getHandlerNames - Populate client supplied smallvector using custome
402 /// metadata name and ID.
403 void MetadataContextImpl::
404 getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
405 Names.resize(MDHandlerNames.size()+1);
407 for (StringMap<unsigned>::const_iterator I = MDHandlerNames.begin(),
408 E = MDHandlerNames.end(); I != E; ++I)
409 // MD Handlers are numbered from 1.
410 Names[I->second] = I->first();
413 /// ValueIsCloned - This handler is used to update metadata store
414 /// when In1 is cloned to create In2.
415 void MetadataContextImpl::ValueIsCloned(const Instruction *In1,
417 // Find Metadata handles for In1.
418 MDStoreTy::iterator I = MetadataStore.find(In1);
419 assert(I != MetadataStore.end() && "Invalid custom metadata info!");
421 // FIXME: Give all metadata handlers a chance to adjust.
422 MDMapTy &In1Info = I->second;
423 for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
424 addMD(I->first, I->second, In2);
427 /// ValueIsRAUWd - This handler is used when V1's all uses are replaced by
429 void MetadataContextImpl::ValueIsRAUWd(Value *V1, Value *V2) {
430 Instruction *I1 = dyn_cast<Instruction>(V1);
431 Instruction *I2 = dyn_cast<Instruction>(V2);
435 // FIXME: Give custom handlers a chance to override this.
436 ValueIsCloned(I1, I2);
439 //===----------------------------------------------------------------------===//
440 // MetadataContext implementation.
442 MetadataContext::MetadataContext() : pImpl(new MetadataContextImpl()) { }
443 MetadataContext::~MetadataContext() { delete pImpl; }
445 /// isValidName - Return true if Name is a valid custom metadata handler name.
446 bool MetadataContext::isValidName(StringRef MDName) {
450 if (!isalpha(MDName[0]))
453 for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
455 if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
461 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
462 unsigned MetadataContext::getMDKindID(StringRef Name) const {
463 return pImpl->getMDKindID(Name);
466 /// getMD - Get the metadata of given kind attached to an Instruction.
467 /// If the metadata is not found then return 0.
468 MDNode *MetadataContext::getMD(unsigned Kind, const Instruction *Inst) {
469 return pImpl->getMD(Kind, Inst);
472 /// getMDs - Get the metadata attached to an Instruction.
473 void MetadataContext::
474 getMDs(const Instruction *Inst,
475 SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs) const {
476 return pImpl->getMDs(Inst, MDs);
479 /// addMD - Attach the metadata of given kind to an Instruction.
480 void MetadataContext::addMD(unsigned Kind, MDNode *Node, Instruction *Inst) {
481 pImpl->addMD(Kind, Node, Inst);
484 /// removeMD - Remove metadata of given kind attached with an instruction.
485 void MetadataContext::removeMD(unsigned Kind, Instruction *Inst) {
486 pImpl->removeMD(Kind, Inst);
489 /// removeAllMetadata - Remove all metadata attached with an instruction.
490 void MetadataContext::removeAllMetadata(Instruction *Inst) {
491 pImpl->removeAllMetadata(Inst);
494 /// copyMD - If metadata is attached with Instruction In1 then attach
495 /// the same metadata to In2.
496 void MetadataContext::copyMD(Instruction *In1, Instruction *In2) {
497 pImpl->copyMD(In1, In2);
500 /// getHandlerNames - Populate client supplied smallvector using custome
501 /// metadata name and ID.
502 void MetadataContext::getMDKindNames(SmallVectorImpl<StringRef> &N) const {
503 pImpl->getMDKindNames(N);
506 /// ValueIsDeleted - This handler is used to update metadata store
507 /// when a value is deleted.
508 void MetadataContext::ValueIsDeleted(Instruction *Inst) {
509 pImpl->ValueIsDeleted(Inst);
511 void MetadataContext::ValueIsRAUWd(Value *V1, Value *V2) {
512 pImpl->ValueIsRAUWd(V1, V2);
515 /// ValueIsCloned - This handler is used to update metadata store
516 /// when In1 is cloned to create In2.
517 void MetadataContext::ValueIsCloned(const Instruction *In1, Instruction *In2) {
518 pImpl->ValueIsCloned(In1, In2);