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::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals,
94 : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
95 NumOperands = NumVals;
96 Operands = new MDNodeElement[NumOperands];
97 MDNodeElement *Ptr = Operands;
98 for (unsigned i = 0; i != NumVals; ++i)
99 Ptr[i].set(Vals[i], this);
102 SubclassData |= FunctionLocalBit;
105 void MDNode::Profile(FoldingSetNodeID &ID) const {
106 for (unsigned i = 0, e = getNumElements(); i != e; ++i)
107 ID.AddPointer(getElement(i));
110 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals,
111 bool isFunctionLocal) {
112 LLVMContextImpl *pImpl = Context.pImpl;
114 for (unsigned i = 0; i != NumVals; ++i)
115 ID.AddPointer(Vals[i]);
118 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
120 // InsertPoint will have been set by the FindNodeOrInsertPos call.
121 N = new MDNode(Context, Vals, NumVals, isFunctionLocal);
122 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
127 /// ~MDNode - Destroy MDNode.
129 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
130 pImpl->MDNodeSet.RemoveNode(this);
135 /// getElement - Return specified element.
136 Value *MDNode::getElement(unsigned i) const {
137 assert(i < getNumElements() && "Invalid element number!");
143 // Replace value from this node's element list.
144 void MDNode::replaceElement(Value *From, Value *To) {
145 if (From == To || !getType())
147 LLVMContext &Context = getType()->getContext();
148 LLVMContextImpl *pImpl = Context.pImpl;
150 // Find value. This is a linear search, do something if it consumes
151 // lot of time. It is possible that to have multiple instances of
152 // From in this MDNode's element list.
153 SmallVector<unsigned, 4> Indexes;
155 for (unsigned i = 0, e = getNumElements(); i != e; ++i, ++Index) {
156 Value *V = getElement(i);
158 Indexes.push_back(Index);
164 // Remove "this" from the context map.
165 pImpl->MDNodeSet.RemoveNode(this);
167 // Replace From element(s) in place.
168 for (SmallVector<unsigned, 4>::iterator I = Indexes.begin(), E = Indexes.end();
170 Operands[*I].set(To, this);
172 // Insert updated "this" into the context's folding node set.
173 // If a node with same element list already exist then before inserting
174 // updated "this" into the folding node set, replace all uses of existing
175 // node with updated "this" node.
179 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
182 N->replaceAllUsesWith(this);
187 N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
189 // InsertPoint will have been set by the FindNodeOrInsertPos call.
191 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
195 //===----------------------------------------------------------------------===//
196 // NamedMDNode implementation.
198 static SmallVector<TrackingVH<MetadataBase>, 4> &getNMDOps(void *Operands) {
199 return *(SmallVector<TrackingVH<MetadataBase>, 4>*)Operands;
202 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
203 MetadataBase *const *MDs,
204 unsigned NumMDs, Module *ParentModule)
205 : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
208 Operands = new SmallVector<TrackingVH<MetadataBase>, 4>();
210 SmallVector<TrackingVH<MetadataBase>, 4> &Node = getNMDOps(Operands);
211 for (unsigned i = 0; i != NumMDs; ++i)
212 Node.push_back(TrackingVH<MetadataBase>(MDs[i]));
215 ParentModule->getNamedMDList().push_back(this);
218 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
219 assert(NMD && "Invalid source NamedMDNode!");
220 SmallVector<MetadataBase *, 4> Elems;
221 Elems.reserve(NMD->getNumElements());
223 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
224 Elems.push_back(NMD->getElement(i));
225 return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
226 Elems.data(), Elems.size(), M);
229 NamedMDNode::~NamedMDNode() {
231 delete &getNMDOps(Operands);
234 /// getNumElements - Return number of NamedMDNode elements.
235 unsigned NamedMDNode::getNumElements() const {
236 return (unsigned)getNMDOps(Operands).size();
239 /// getElement - Return specified element.
240 MetadataBase *NamedMDNode::getElement(unsigned i) const {
241 assert(i < getNumElements() && "Invalid element number!");
242 return getNMDOps(Operands)[i];
245 /// addElement - Add metadata element.
246 void NamedMDNode::addElement(MetadataBase *M) {
247 getNMDOps(Operands).push_back(TrackingVH<MetadataBase>(M));
250 /// eraseFromParent - Drop all references and remove the node from parent
252 void NamedMDNode::eraseFromParent() {
253 getParent()->getNamedMDList().erase(this);
256 /// dropAllReferences - Remove all uses and clear node vector.
257 void NamedMDNode::dropAllReferences() {
258 getNMDOps(Operands).clear();
262 //===----------------------------------------------------------------------===//
263 // MetadataContextImpl implementation.
266 class MetadataContextImpl {
268 typedef std::pair<unsigned, TrackingVH<MDNode> > MDPairTy;
269 typedef SmallVector<MDPairTy, 2> MDMapTy;
270 typedef DenseMap<const Instruction *, MDMapTy> MDStoreTy;
271 friend class BitcodeReader;
274 /// MetadataStore - Collection of metadata used in this context.
275 MDStoreTy MetadataStore;
277 /// MDHandlerNames - Map to hold metadata handler names.
278 StringMap<unsigned> MDHandlerNames;
281 /// registerMDKind - Register a new metadata kind and return its ID.
282 /// A metadata kind can be registered only once.
283 unsigned registerMDKind(StringRef Name);
285 /// getMDKind - Return metadata kind. If the requested metadata kind
286 /// is not registered then return 0.
287 unsigned getMDKind(StringRef Name) const;
289 /// getMD - Get the metadata of given kind attached to an Instruction.
290 /// If the metadata is not found then return 0.
291 MDNode *getMD(unsigned Kind, const Instruction *Inst);
293 /// getMDs - Get the metadata attached to an Instruction.
294 void getMDs(const Instruction *Inst,
295 SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs) const;
297 /// addMD - Attach the metadata of given kind to an Instruction.
298 void addMD(unsigned Kind, MDNode *Node, Instruction *Inst);
300 /// removeMD - Remove metadata of given kind attached with an instruction.
301 void removeMD(unsigned Kind, Instruction *Inst);
303 /// removeAllMetadata - Remove all metadata attached with an instruction.
304 void removeAllMetadata(Instruction *Inst);
306 /// copyMD - If metadata is attached with Instruction In1 then attach
307 /// the same metadata to In2.
308 void copyMD(Instruction *In1, Instruction *In2);
310 /// getHandlerNames - Populate client-supplied smallvector using custom
311 /// metadata name and ID.
312 void getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&) const;
314 /// ValueIsDeleted - This handler is used to update metadata store
315 /// when a value is deleted.
316 void ValueIsDeleted(const Value *) {}
317 void ValueIsDeleted(Instruction *Inst) {
318 removeAllMetadata(Inst);
320 void ValueIsRAUWd(Value *V1, Value *V2);
322 /// ValueIsCloned - This handler is used to update metadata store
323 /// when In1 is cloned to create In2.
324 void ValueIsCloned(const Instruction *In1, Instruction *In2);
328 /// registerMDKind - Register a new metadata kind and return its ID.
329 /// A metadata kind can be registered only once.
330 unsigned MetadataContextImpl::registerMDKind(StringRef Name) {
331 unsigned Count = MDHandlerNames.size();
332 assert(MDHandlerNames.count(Name) == 0 && "Already registered MDKind!");
333 return MDHandlerNames[Name] = Count + 1;
336 /// getMDKind - Return metadata kind. If the requested metadata kind
337 /// is not registered then return 0.
338 unsigned MetadataContextImpl::getMDKind(StringRef Name) const {
339 StringMap<unsigned>::const_iterator I = MDHandlerNames.find(Name);
340 if (I == MDHandlerNames.end())
343 return I->getValue();
346 /// addMD - Attach the metadata of given kind to an Instruction.
347 void MetadataContextImpl::addMD(unsigned MDKind, MDNode *Node,
349 assert(Node && "Invalid null MDNode");
350 Inst->HasMetadata = true;
351 MDMapTy &Info = MetadataStore[Inst];
353 Info.push_back(std::make_pair(MDKind, Node));
354 MetadataStore.insert(std::make_pair(Inst, Info));
358 // If there is an entry for this MDKind then replace it.
359 for (unsigned i = 0, e = Info.size(); i != e; ++i) {
360 MDPairTy &P = Info[i];
361 if (P.first == MDKind) {
362 Info[i] = std::make_pair(MDKind, Node);
367 // Otherwise add a new entry.
368 Info.push_back(std::make_pair(MDKind, Node));
371 /// removeMD - Remove metadata of given kind attached with an instruction.
372 void MetadataContextImpl::removeMD(unsigned Kind, Instruction *Inst) {
373 MDStoreTy::iterator I = MetadataStore.find(Inst);
374 if (I == MetadataStore.end())
377 MDMapTy &Info = I->second;
378 for (MDMapTy::iterator MI = Info.begin(), ME = Info.end(); MI != ME; ++MI) {
380 if (P.first == Kind) {
387 /// removeAllMetadata - Remove all metadata attached with an instruction.
388 void MetadataContextImpl::removeAllMetadata(Instruction *Inst) {
389 MetadataStore.erase(Inst);
390 Inst->HasMetadata = false;
393 /// copyMD - If metadata is attached with Instruction In1 then attach
394 /// the same metadata to In2.
395 void MetadataContextImpl::copyMD(Instruction *In1, Instruction *In2) {
396 assert(In1 && In2 && "Invalid instruction!");
397 MDMapTy &In1Info = MetadataStore[In1];
401 for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
402 addMD(I->first, I->second, In2);
405 /// getMD - Get the metadata of given kind attached to an Instruction.
406 /// If the metadata is not found then return 0.
407 MDNode *MetadataContextImpl::getMD(unsigned MDKind, const Instruction *Inst) {
408 MDMapTy &Info = MetadataStore[Inst];
412 for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I)
413 if (I->first == MDKind)
418 /// getMDs - Get the metadata attached to an Instruction.
419 void MetadataContextImpl::
420 getMDs(const Instruction *Inst,
421 SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs) const {
422 MDStoreTy::const_iterator I = MetadataStore.find(Inst);
423 if (I == MetadataStore.end())
425 MDs.resize(I->second.size());
426 for (MDMapTy::const_iterator MI = I->second.begin(), ME = I->second.end();
428 // MD kinds are numbered from 1.
429 MDs[MI->first - 1] = std::make_pair(MI->first, MI->second);
432 /// getHandlerNames - Populate client supplied smallvector using custome
433 /// metadata name and ID.
434 void MetadataContextImpl::
435 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&Names) const {
436 Names.resize(MDHandlerNames.size());
437 for (StringMap<unsigned>::const_iterator I = MDHandlerNames.begin(),
438 E = MDHandlerNames.end(); I != E; ++I)
439 // MD Handlers are numbered from 1.
440 Names[I->second - 1] = std::make_pair(I->second, I->first());
443 /// ValueIsCloned - This handler is used to update metadata store
444 /// when In1 is cloned to create In2.
445 void MetadataContextImpl::ValueIsCloned(const Instruction *In1,
447 // Find Metadata handles for In1.
448 MDStoreTy::iterator I = MetadataStore.find(In1);
449 assert(I != MetadataStore.end() && "Invalid custom metadata info!");
451 // FIXME : Give all metadata handlers a chance to adjust.
453 MDMapTy &In1Info = I->second;
455 for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
456 addMD(I->first, I->second, In2);
459 /// ValueIsRAUWd - This handler is used when V1's all uses are replaced by
461 void MetadataContextImpl::ValueIsRAUWd(Value *V1, Value *V2) {
462 Instruction *I1 = dyn_cast<Instruction>(V1);
463 Instruction *I2 = dyn_cast<Instruction>(V2);
467 // FIXME : Give custom handlers a chance to override this.
468 ValueIsCloned(I1, I2);
471 //===----------------------------------------------------------------------===//
472 // MetadataContext implementation.
474 MetadataContext::MetadataContext()
475 : pImpl(new MetadataContextImpl()) { }
476 MetadataContext::~MetadataContext() { delete pImpl; }
478 /// isValidName - Return true if Name is a valid custom metadata handler name.
479 bool MetadataContext::isValidName(StringRef MDName) {
483 if (!isalpha(MDName[0]))
486 for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
488 if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
494 /// registerMDKind - Register a new metadata kind and return its ID.
495 /// A metadata kind can be registered only once.
496 unsigned MetadataContext::registerMDKind(StringRef Name) {
497 assert(isValidName(Name) && "Invalid custome metadata name!");
498 return pImpl->registerMDKind(Name);
501 /// getMDKind - Return metadata kind. If the requested metadata kind
502 /// is not registered then return 0.
503 unsigned MetadataContext::getMDKind(StringRef Name) const {
504 return pImpl->getMDKind(Name);
507 /// getMD - Get the metadata of given kind attached to an Instruction.
508 /// If the metadata is not found then return 0.
509 MDNode *MetadataContext::getMD(unsigned Kind, const Instruction *Inst) {
510 return pImpl->getMD(Kind, Inst);
513 /// getMDs - Get the metadata attached to an Instruction.
514 void MetadataContext::
515 getMDs(const Instruction *Inst,
516 SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs) const {
517 return pImpl->getMDs(Inst, MDs);
520 /// addMD - Attach the metadata of given kind to an Instruction.
521 void MetadataContext::addMD(unsigned Kind, MDNode *Node, Instruction *Inst) {
522 pImpl->addMD(Kind, Node, Inst);
525 /// removeMD - Remove metadata of given kind attached with an instruction.
526 void MetadataContext::removeMD(unsigned Kind, Instruction *Inst) {
527 pImpl->removeMD(Kind, Inst);
530 /// removeAllMetadata - Remove all metadata attached with an instruction.
531 void MetadataContext::removeAllMetadata(Instruction *Inst) {
532 pImpl->removeAllMetadata(Inst);
535 /// copyMD - If metadata is attached with Instruction In1 then attach
536 /// the same metadata to In2.
537 void MetadataContext::copyMD(Instruction *In1, Instruction *In2) {
538 pImpl->copyMD(In1, In2);
541 /// getHandlerNames - Populate client supplied smallvector using custome
542 /// metadata name and ID.
543 void MetadataContext::
544 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&N) const {
545 pImpl->getHandlerNames(N);
548 /// ValueIsDeleted - This handler is used to update metadata store
549 /// when a value is deleted.
550 void MetadataContext::ValueIsDeleted(Instruction *Inst) {
551 pImpl->ValueIsDeleted(Inst);
553 void MetadataContext::ValueIsRAUWd(Value *V1, Value *V2) {
554 pImpl->ValueIsRAUWd(V1, V2);
557 /// ValueIsCloned - This handler is used to update metadata store
558 /// when In1 is cloned to create In2.
559 void MetadataContext::ValueIsCloned(const Instruction *In1, Instruction *In2) {
560 pImpl->ValueIsCloned(In1, In2);