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 // MetadataBase implementation.
29 //===----------------------------------------------------------------------===//
30 // MDString implementation.
33 MDString::MDString(LLVMContext &C, StringRef S)
34 : MetadataBase(Type::getMetadataTy(C), Value::MDStringVal), Str(S) {}
36 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
37 LLVMContextImpl *pImpl = Context.pImpl;
38 StringMapEntry<MDString *> &Entry =
39 pImpl->MDStringCache.GetOrCreateValue(Str);
40 MDString *&S = Entry.getValue();
41 if (!S) S = new MDString(Context, Entry.getKey());
45 MDString *MDString::get(LLVMContext &Context, const char *Str) {
46 LLVMContextImpl *pImpl = Context.pImpl;
47 StringMapEntry<MDString *> &Entry =
48 pImpl->MDStringCache.GetOrCreateValue(Str ? StringRef(Str) : StringRef());
49 MDString *&S = Entry.getValue();
50 if (!S) S = new MDString(Context, Entry.getKey());
54 //===----------------------------------------------------------------------===//
55 // MDNodeElement implementation.
58 // Use CallbackVH to hold MDNode elements.
60 class MDNodeElement : public CallbackVH {
64 MDNodeElement(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {}
67 void set(Value *V, MDNode *P) {
72 virtual void deleted();
73 virtual void allUsesReplacedWith(Value *NV);
75 } // end namespace llvm.
78 void MDNodeElement::deleted() {
79 Parent->replaceElement(this->operator Value*(), 0);
82 void MDNodeElement::allUsesReplacedWith(Value *NV) {
83 Parent->replaceElement(this->operator Value*(), NV);
88 //===----------------------------------------------------------------------===//
89 // MDNode implementation.
92 /// ~MDNode - Destroy MDNode.
94 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
95 pImpl->MDNodeSet.RemoveNode(this);
100 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals,
101 bool isFunctionLocal)
102 : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
103 NumOperands = NumVals;
104 Operands = new MDNodeElement[NumOperands];
106 for (unsigned i = 0; i != NumVals; ++i)
107 Operands[i].set(Vals[i], this);
110 SubclassData |= FunctionLocalBit;
113 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals,
114 bool isFunctionLocal) {
115 LLVMContextImpl *pImpl = Context.pImpl;
117 for (unsigned i = 0; i != NumVals; ++i)
118 ID.AddPointer(Vals[i]);
121 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
123 // InsertPoint will have been set by the FindNodeOrInsertPos call.
124 N = new MDNode(Context, Vals, NumVals, isFunctionLocal);
125 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
130 void MDNode::Profile(FoldingSetNodeID &ID) const {
131 for (unsigned i = 0, e = getNumElements(); i != e; ++i)
132 ID.AddPointer(getElement(i));
136 /// getElement - Return specified element.
137 Value *MDNode::getElement(unsigned i) const {
138 assert(i < getNumElements() && "Invalid element number!");
144 // Replace value from this node's element list.
145 void MDNode::replaceElement(Value *From, Value *To) {
146 if (From == To || !getType())
148 LLVMContext &Context = getType()->getContext();
149 LLVMContextImpl *pImpl = Context.pImpl;
151 // Find value. This is a linear search, do something if it consumes
152 // lot of time. It is possible that to have multiple instances of
153 // From in this MDNode's element list.
154 SmallVector<unsigned, 4> Indexes;
156 for (unsigned i = 0, e = getNumElements(); i != e; ++i, ++Index) {
157 Value *V = getElement(i);
159 Indexes.push_back(Index);
165 // Remove "this" from the context map.
166 pImpl->MDNodeSet.RemoveNode(this);
168 // Replace From element(s) in place.
169 for (SmallVector<unsigned, 4>::iterator I = Indexes.begin(), E = Indexes.end();
171 Operands[*I].set(To, this);
173 // Insert updated "this" into the context's folding node set.
174 // If a node with same element list already exist then before inserting
175 // updated "this" into the folding node set, replace all uses of existing
176 // node with updated "this" node.
180 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
183 N->replaceAllUsesWith(this);
188 N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
190 // InsertPoint will have been set by the FindNodeOrInsertPos call.
192 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
196 //===----------------------------------------------------------------------===//
197 // NamedMDNode implementation.
199 static SmallVector<TrackingVH<MetadataBase>, 4> &getNMDOps(void *Operands) {
200 return *(SmallVector<TrackingVH<MetadataBase>, 4>*)Operands;
203 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
204 MetadataBase *const *MDs,
205 unsigned NumMDs, Module *ParentModule)
206 : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
209 Operands = new SmallVector<TrackingVH<MetadataBase>, 4>();
211 SmallVector<TrackingVH<MetadataBase>, 4> &Node = getNMDOps(Operands);
212 for (unsigned i = 0; i != NumMDs; ++i)
213 Node.push_back(TrackingVH<MetadataBase>(MDs[i]));
216 ParentModule->getNamedMDList().push_back(this);
219 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
220 assert(NMD && "Invalid source NamedMDNode!");
221 SmallVector<MetadataBase *, 4> Elems;
222 Elems.reserve(NMD->getNumElements());
224 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
225 Elems.push_back(NMD->getElement(i));
226 return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
227 Elems.data(), Elems.size(), M);
230 NamedMDNode::~NamedMDNode() {
232 delete &getNMDOps(Operands);
235 /// getNumElements - Return number of NamedMDNode elements.
236 unsigned NamedMDNode::getNumElements() const {
237 return (unsigned)getNMDOps(Operands).size();
240 /// getElement - Return specified element.
241 MetadataBase *NamedMDNode::getElement(unsigned i) const {
242 assert(i < getNumElements() && "Invalid element number!");
243 return getNMDOps(Operands)[i];
246 /// addElement - Add metadata element.
247 void NamedMDNode::addElement(MetadataBase *M) {
248 getNMDOps(Operands).push_back(TrackingVH<MetadataBase>(M));
251 /// eraseFromParent - Drop all references and remove the node from parent
253 void NamedMDNode::eraseFromParent() {
254 getParent()->getNamedMDList().erase(this);
257 /// dropAllReferences - Remove all uses and clear node vector.
258 void NamedMDNode::dropAllReferences() {
259 getNMDOps(Operands).clear();
263 //===----------------------------------------------------------------------===//
264 // MetadataContextImpl implementation.
267 class MetadataContextImpl {
269 typedef std::pair<unsigned, TrackingVH<MDNode> > MDPairTy;
270 typedef SmallVector<MDPairTy, 2> MDMapTy;
271 typedef DenseMap<const Instruction *, MDMapTy> MDStoreTy;
272 friend class BitcodeReader;
275 /// MetadataStore - Collection of metadata used in this context.
276 MDStoreTy MetadataStore;
278 /// MDHandlerNames - Map to hold metadata handler names.
279 StringMap<unsigned> MDHandlerNames;
282 /// registerMDKind - Register a new metadata kind and return its ID.
283 /// A metadata kind can be registered only once.
284 unsigned registerMDKind(StringRef Name);
286 /// getMDKind - Return metadata kind. If the requested metadata kind
287 /// is not registered then return 0.
288 unsigned getMDKind(StringRef Name) const;
290 /// getMD - Get the metadata of given kind attached to an Instruction.
291 /// If the metadata is not found then return 0.
292 MDNode *getMD(unsigned Kind, const Instruction *Inst);
294 /// getMDs - Get the metadata attached to an Instruction.
295 void getMDs(const Instruction *Inst,
296 SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs) const;
298 /// addMD - Attach the metadata of given kind to an Instruction.
299 void addMD(unsigned Kind, MDNode *Node, Instruction *Inst);
301 /// removeMD - Remove metadata of given kind attached with an instruction.
302 void removeMD(unsigned Kind, Instruction *Inst);
304 /// removeAllMetadata - Remove all metadata attached with an instruction.
305 void removeAllMetadata(Instruction *Inst);
307 /// copyMD - If metadata is attached with Instruction In1 then attach
308 /// the same metadata to In2.
309 void copyMD(Instruction *In1, Instruction *In2);
311 /// getHandlerNames - Populate client-supplied smallvector using custom
312 /// metadata name and ID.
313 void getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&) const;
315 /// ValueIsDeleted - This handler is used to update metadata store
316 /// when a value is deleted.
317 void ValueIsDeleted(const Value *) {}
318 void ValueIsDeleted(Instruction *Inst) {
319 removeAllMetadata(Inst);
321 void ValueIsRAUWd(Value *V1, Value *V2);
323 /// ValueIsCloned - This handler is used to update metadata store
324 /// when In1 is cloned to create In2.
325 void ValueIsCloned(const Instruction *In1, Instruction *In2);
329 /// registerMDKind - Register a new metadata kind and return its ID.
330 /// A metadata kind can be registered only once.
331 unsigned MetadataContextImpl::registerMDKind(StringRef Name) {
332 unsigned Count = MDHandlerNames.size();
333 assert(MDHandlerNames.count(Name) == 0 && "Already registered MDKind!");
334 return MDHandlerNames[Name] = Count + 1;
337 /// getMDKind - Return metadata kind. If the requested metadata kind
338 /// is not registered then return 0.
339 unsigned MetadataContextImpl::getMDKind(StringRef Name) const {
340 StringMap<unsigned>::const_iterator I = MDHandlerNames.find(Name);
341 if (I == MDHandlerNames.end())
344 return I->getValue();
347 /// addMD - Attach the metadata of given kind to an Instruction.
348 void MetadataContextImpl::addMD(unsigned MDKind, MDNode *Node,
350 assert(Node && "Invalid null MDNode");
351 Inst->HasMetadata = true;
352 MDMapTy &Info = MetadataStore[Inst];
354 Info.push_back(std::make_pair(MDKind, Node));
355 MetadataStore.insert(std::make_pair(Inst, Info));
359 // If there is an entry for this MDKind then replace it.
360 for (unsigned i = 0, e = Info.size(); i != e; ++i) {
361 MDPairTy &P = Info[i];
362 if (P.first == MDKind) {
363 Info[i] = std::make_pair(MDKind, Node);
368 // Otherwise add a new entry.
369 Info.push_back(std::make_pair(MDKind, Node));
372 /// removeMD - Remove metadata of given kind attached with an instruction.
373 void MetadataContextImpl::removeMD(unsigned Kind, Instruction *Inst) {
374 MDStoreTy::iterator I = MetadataStore.find(Inst);
375 if (I == MetadataStore.end())
378 MDMapTy &Info = I->second;
379 for (MDMapTy::iterator MI = Info.begin(), ME = Info.end(); MI != ME; ++MI) {
381 if (P.first == Kind) {
388 /// removeAllMetadata - Remove all metadata attached with an instruction.
389 void MetadataContextImpl::removeAllMetadata(Instruction *Inst) {
390 MetadataStore.erase(Inst);
391 Inst->HasMetadata = false;
394 /// copyMD - If metadata is attached with Instruction In1 then attach
395 /// the same metadata to In2.
396 void MetadataContextImpl::copyMD(Instruction *In1, Instruction *In2) {
397 assert(In1 && In2 && "Invalid instruction!");
398 MDMapTy &In1Info = MetadataStore[In1];
402 for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
403 addMD(I->first, I->second, In2);
406 /// getMD - Get the metadata of given kind attached to an Instruction.
407 /// If the metadata is not found then return 0.
408 MDNode *MetadataContextImpl::getMD(unsigned MDKind, const Instruction *Inst) {
409 MDMapTy &Info = MetadataStore[Inst];
413 for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I)
414 if (I->first == MDKind)
419 /// getMDs - Get the metadata attached to an Instruction.
420 void MetadataContextImpl::
421 getMDs(const Instruction *Inst,
422 SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs) const {
423 MDStoreTy::const_iterator I = MetadataStore.find(Inst);
424 if (I == MetadataStore.end())
426 MDs.resize(I->second.size());
427 for (MDMapTy::const_iterator MI = I->second.begin(), ME = I->second.end();
429 // MD kinds are numbered from 1.
430 MDs[MI->first - 1] = std::make_pair(MI->first, MI->second);
433 /// getHandlerNames - Populate client supplied smallvector using custome
434 /// metadata name and ID.
435 void MetadataContextImpl::
436 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&Names) const {
437 Names.resize(MDHandlerNames.size());
438 for (StringMap<unsigned>::const_iterator I = MDHandlerNames.begin(),
439 E = MDHandlerNames.end(); I != E; ++I)
440 // MD Handlers are numbered from 1.
441 Names[I->second - 1] = std::make_pair(I->second, I->first());
444 /// ValueIsCloned - This handler is used to update metadata store
445 /// when In1 is cloned to create In2.
446 void MetadataContextImpl::ValueIsCloned(const Instruction *In1,
448 // Find Metadata handles for In1.
449 MDStoreTy::iterator I = MetadataStore.find(In1);
450 assert(I != MetadataStore.end() && "Invalid custom metadata info!");
452 // FIXME : Give all metadata handlers a chance to adjust.
454 MDMapTy &In1Info = I->second;
456 for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
457 addMD(I->first, I->second, In2);
460 /// ValueIsRAUWd - This handler is used when V1's all uses are replaced by
462 void MetadataContextImpl::ValueIsRAUWd(Value *V1, Value *V2) {
463 Instruction *I1 = dyn_cast<Instruction>(V1);
464 Instruction *I2 = dyn_cast<Instruction>(V2);
468 // FIXME : Give custom handlers a chance to override this.
469 ValueIsCloned(I1, I2);
472 //===----------------------------------------------------------------------===//
473 // MetadataContext implementation.
475 MetadataContext::MetadataContext()
476 : pImpl(new MetadataContextImpl()) { }
477 MetadataContext::~MetadataContext() { delete pImpl; }
479 /// isValidName - Return true if Name is a valid custom metadata handler name.
480 bool MetadataContext::isValidName(StringRef MDName) {
484 if (!isalpha(MDName[0]))
487 for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
489 if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
495 /// registerMDKind - Register a new metadata kind and return its ID.
496 /// A metadata kind can be registered only once.
497 unsigned MetadataContext::registerMDKind(StringRef Name) {
498 assert(isValidName(Name) && "Invalid custome metadata name!");
499 return pImpl->registerMDKind(Name);
502 /// getMDKind - Return metadata kind. If the requested metadata kind
503 /// is not registered then return 0.
504 unsigned MetadataContext::getMDKind(StringRef Name) const {
505 return pImpl->getMDKind(Name);
508 /// getMD - Get the metadata of given kind attached to an Instruction.
509 /// If the metadata is not found then return 0.
510 MDNode *MetadataContext::getMD(unsigned Kind, const Instruction *Inst) {
511 return pImpl->getMD(Kind, Inst);
514 /// getMDs - Get the metadata attached to an Instruction.
515 void MetadataContext::
516 getMDs(const Instruction *Inst,
517 SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs) const {
518 return pImpl->getMDs(Inst, MDs);
521 /// addMD - Attach the metadata of given kind to an Instruction.
522 void MetadataContext::addMD(unsigned Kind, MDNode *Node, Instruction *Inst) {
523 pImpl->addMD(Kind, Node, Inst);
526 /// removeMD - Remove metadata of given kind attached with an instruction.
527 void MetadataContext::removeMD(unsigned Kind, Instruction *Inst) {
528 pImpl->removeMD(Kind, Inst);
531 /// removeAllMetadata - Remove all metadata attached with an instruction.
532 void MetadataContext::removeAllMetadata(Instruction *Inst) {
533 pImpl->removeAllMetadata(Inst);
536 /// copyMD - If metadata is attached with Instruction In1 then attach
537 /// the same metadata to In2.
538 void MetadataContext::copyMD(Instruction *In1, Instruction *In2) {
539 pImpl->copyMD(In1, In2);
542 /// getHandlerNames - Populate client supplied smallvector using custome
543 /// metadata name and ID.
544 void MetadataContext::
545 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&N) const {
546 pImpl->getHandlerNames(N);
549 /// ValueIsDeleted - This handler is used to update metadata store
550 /// when a value is deleted.
551 void MetadataContext::ValueIsDeleted(Instruction *Inst) {
552 pImpl->ValueIsDeleted(Inst);
554 void MetadataContext::ValueIsRAUWd(Value *V1, Value *V2) {
555 pImpl->ValueIsRAUWd(V1, V2);
558 /// ValueIsCloned - This handler is used to update metadata store
559 /// when In1 is cloned to create In2.
560 void MetadataContext::ValueIsCloned(const Instruction *In1, Instruction *In2) {
561 pImpl->ValueIsCloned(In1, In2);