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())
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 // Find value. This is a linear search, do something if it consumes
156 // lot of time. It is possible that to have multiple instances of
157 // From in this MDNode's element list.
158 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
159 if (Operands[i] == From)
160 Operands[i].set(To, this);
163 // Insert updated "this" into the context's folding node set.
164 // If a node with same element list already exist then before inserting
165 // updated "this" into the folding node set, replace all uses of existing
166 // node with updated "this" node.
170 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
173 N->replaceAllUsesWith(this);
175 N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
176 assert(N == 0 && "shouldn't be in the map now!"); (void)N;
179 // InsertPoint will have been set by the FindNodeOrInsertPos call.
180 pImpl->MDNodeSet.InsertNode(this, InsertPoint);
183 //===----------------------------------------------------------------------===//
184 // NamedMDNode implementation.
186 static SmallVector<TrackingVH<MetadataBase>, 4> &getNMDOps(void *Operands) {
187 return *(SmallVector<TrackingVH<MetadataBase>, 4>*)Operands;
190 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
191 MetadataBase *const *MDs,
192 unsigned NumMDs, Module *ParentModule)
193 : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
196 Operands = new SmallVector<TrackingVH<MetadataBase>, 4>();
198 SmallVector<TrackingVH<MetadataBase>, 4> &Node = getNMDOps(Operands);
199 for (unsigned i = 0; i != NumMDs; ++i)
200 Node.push_back(TrackingVH<MetadataBase>(MDs[i]));
203 ParentModule->getNamedMDList().push_back(this);
206 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
207 assert(NMD && "Invalid source NamedMDNode!");
208 SmallVector<MetadataBase *, 4> Elems;
209 Elems.reserve(NMD->getNumElements());
211 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
212 Elems.push_back(NMD->getElement(i));
213 return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
214 Elems.data(), Elems.size(), M);
217 NamedMDNode::~NamedMDNode() {
219 delete &getNMDOps(Operands);
222 /// getNumElements - Return number of NamedMDNode elements.
223 unsigned NamedMDNode::getNumElements() const {
224 return (unsigned)getNMDOps(Operands).size();
227 /// getElement - Return specified element.
228 MetadataBase *NamedMDNode::getElement(unsigned i) const {
229 assert(i < getNumElements() && "Invalid element number!");
230 return getNMDOps(Operands)[i];
233 /// addElement - Add metadata element.
234 void NamedMDNode::addElement(MetadataBase *M) {
235 getNMDOps(Operands).push_back(TrackingVH<MetadataBase>(M));
238 /// eraseFromParent - Drop all references and remove the node from parent
240 void NamedMDNode::eraseFromParent() {
241 getParent()->getNamedMDList().erase(this);
244 /// dropAllReferences - Remove all uses and clear node vector.
245 void NamedMDNode::dropAllReferences() {
246 getNMDOps(Operands).clear();
250 //===----------------------------------------------------------------------===//
251 // MetadataContextImpl implementation.
254 class MetadataContextImpl {
256 typedef std::pair<unsigned, TrackingVH<MDNode> > MDPairTy;
257 typedef SmallVector<MDPairTy, 2> MDMapTy;
258 typedef DenseMap<const Instruction *, MDMapTy> MDStoreTy;
259 friend class BitcodeReader;
262 /// MetadataStore - Collection of metadata used in this context.
263 MDStoreTy MetadataStore;
265 /// MDHandlerNames - Map to hold metadata handler names.
266 StringMap<unsigned> MDHandlerNames;
269 /// registerMDKind - Register a new metadata kind and return its ID.
270 /// A metadata kind can be registered only once.
271 unsigned registerMDKind(StringRef Name);
273 /// getMDKind - Return metadata kind. If the requested metadata kind
274 /// is not registered then return 0.
275 unsigned getMDKind(StringRef Name) const;
277 /// getMD - Get the metadata of given kind attached to an Instruction.
278 /// If the metadata is not found then return 0.
279 MDNode *getMD(unsigned Kind, const Instruction *Inst);
281 /// getMDs - Get the metadata attached to an Instruction.
282 void getMDs(const Instruction *Inst,
283 SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs) const;
285 /// addMD - Attach the metadata of given kind to an Instruction.
286 void addMD(unsigned Kind, MDNode *Node, Instruction *Inst);
288 /// removeMD - Remove metadata of given kind attached with an instruction.
289 void removeMD(unsigned Kind, Instruction *Inst);
291 /// removeAllMetadata - Remove all metadata attached with an instruction.
292 void removeAllMetadata(Instruction *Inst);
294 /// copyMD - If metadata is attached with Instruction In1 then attach
295 /// the same metadata to In2.
296 void copyMD(Instruction *In1, Instruction *In2);
298 /// getHandlerNames - Populate client-supplied smallvector using custom
299 /// metadata name and ID.
300 void getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&) const;
302 /// ValueIsDeleted - This handler is used to update metadata store
303 /// when a value is deleted.
304 void ValueIsDeleted(const Value *) {}
305 void ValueIsDeleted(Instruction *Inst) {
306 removeAllMetadata(Inst);
308 void ValueIsRAUWd(Value *V1, Value *V2);
310 /// ValueIsCloned - This handler is used to update metadata store
311 /// when In1 is cloned to create In2.
312 void ValueIsCloned(const Instruction *In1, Instruction *In2);
316 /// registerMDKind - Register a new metadata kind and return its ID.
317 /// A metadata kind can be registered only once.
318 unsigned MetadataContextImpl::registerMDKind(StringRef Name) {
319 unsigned Count = MDHandlerNames.size();
320 assert(MDHandlerNames.count(Name) == 0 && "Already registered MDKind!");
321 return MDHandlerNames[Name] = Count + 1;
324 /// getMDKind - Return metadata kind. If the requested metadata kind
325 /// is not registered then return 0.
326 unsigned MetadataContextImpl::getMDKind(StringRef Name) const {
327 StringMap<unsigned>::const_iterator I = MDHandlerNames.find(Name);
328 if (I == MDHandlerNames.end())
331 return I->getValue();
334 /// addMD - Attach the metadata of given kind to an Instruction.
335 void MetadataContextImpl::addMD(unsigned MDKind, MDNode *Node,
337 assert(Node && "Invalid null MDNode");
338 Inst->HasMetadata = true;
339 MDMapTy &Info = MetadataStore[Inst];
341 Info.push_back(std::make_pair(MDKind, Node));
342 MetadataStore.insert(std::make_pair(Inst, Info));
346 // If there is an entry for this MDKind then replace it.
347 for (unsigned i = 0, e = Info.size(); i != e; ++i) {
348 MDPairTy &P = Info[i];
349 if (P.first == MDKind) {
350 Info[i] = std::make_pair(MDKind, Node);
355 // Otherwise add a new entry.
356 Info.push_back(std::make_pair(MDKind, Node));
359 /// removeMD - Remove metadata of given kind attached with an instruction.
360 void MetadataContextImpl::removeMD(unsigned Kind, Instruction *Inst) {
361 MDStoreTy::iterator I = MetadataStore.find(Inst);
362 if (I == MetadataStore.end())
365 MDMapTy &Info = I->second;
366 for (MDMapTy::iterator MI = Info.begin(), ME = Info.end(); MI != ME; ++MI) {
368 if (P.first == Kind) {
375 /// removeAllMetadata - Remove all metadata attached with an instruction.
376 void MetadataContextImpl::removeAllMetadata(Instruction *Inst) {
377 MetadataStore.erase(Inst);
378 Inst->HasMetadata = false;
381 /// copyMD - If metadata is attached with Instruction In1 then attach
382 /// the same metadata to In2.
383 void MetadataContextImpl::copyMD(Instruction *In1, Instruction *In2) {
384 assert(In1 && In2 && "Invalid instruction!");
385 MDMapTy &In1Info = MetadataStore[In1];
389 for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
390 addMD(I->first, I->second, In2);
393 /// getMD - Get the metadata of given kind attached to an Instruction.
394 /// If the metadata is not found then return 0.
395 MDNode *MetadataContextImpl::getMD(unsigned MDKind, const Instruction *Inst) {
396 MDMapTy &Info = MetadataStore[Inst];
400 for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I)
401 if (I->first == MDKind)
406 /// getMDs - Get the metadata attached to an Instruction.
407 void MetadataContextImpl::
408 getMDs(const Instruction *Inst,
409 SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs) const {
410 MDStoreTy::const_iterator I = MetadataStore.find(Inst);
411 if (I == MetadataStore.end())
413 MDs.resize(I->second.size());
414 for (MDMapTy::const_iterator MI = I->second.begin(), ME = I->second.end();
416 // MD kinds are numbered from 1.
417 MDs[MI->first - 1] = std::make_pair(MI->first, MI->second);
420 /// getHandlerNames - Populate client supplied smallvector using custome
421 /// metadata name and ID.
422 void MetadataContextImpl::
423 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&Names) const {
424 Names.resize(MDHandlerNames.size());
425 for (StringMap<unsigned>::const_iterator I = MDHandlerNames.begin(),
426 E = MDHandlerNames.end(); I != E; ++I)
427 // MD Handlers are numbered from 1.
428 Names[I->second - 1] = std::make_pair(I->second, I->first());
431 /// ValueIsCloned - This handler is used to update metadata store
432 /// when In1 is cloned to create In2.
433 void MetadataContextImpl::ValueIsCloned(const Instruction *In1,
435 // Find Metadata handles for In1.
436 MDStoreTy::iterator I = MetadataStore.find(In1);
437 assert(I != MetadataStore.end() && "Invalid custom metadata info!");
439 // FIXME : Give all metadata handlers a chance to adjust.
441 MDMapTy &In1Info = I->second;
443 for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
444 addMD(I->first, I->second, In2);
447 /// ValueIsRAUWd - This handler is used when V1's all uses are replaced by
449 void MetadataContextImpl::ValueIsRAUWd(Value *V1, Value *V2) {
450 Instruction *I1 = dyn_cast<Instruction>(V1);
451 Instruction *I2 = dyn_cast<Instruction>(V2);
455 // FIXME : Give custom handlers a chance to override this.
456 ValueIsCloned(I1, I2);
459 //===----------------------------------------------------------------------===//
460 // MetadataContext implementation.
462 MetadataContext::MetadataContext()
463 : pImpl(new MetadataContextImpl()) { }
464 MetadataContext::~MetadataContext() { delete pImpl; }
466 /// isValidName - Return true if Name is a valid custom metadata handler name.
467 bool MetadataContext::isValidName(StringRef MDName) {
471 if (!isalpha(MDName[0]))
474 for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
476 if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
482 /// registerMDKind - Register a new metadata kind and return its ID.
483 /// A metadata kind can be registered only once.
484 unsigned MetadataContext::registerMDKind(StringRef Name) {
485 assert(isValidName(Name) && "Invalid custome metadata name!");
486 return pImpl->registerMDKind(Name);
489 /// getMDKind - Return metadata kind. If the requested metadata kind
490 /// is not registered then return 0.
491 unsigned MetadataContext::getMDKind(StringRef Name) const {
492 return pImpl->getMDKind(Name);
495 /// getMD - Get the metadata of given kind attached to an Instruction.
496 /// If the metadata is not found then return 0.
497 MDNode *MetadataContext::getMD(unsigned Kind, const Instruction *Inst) {
498 return pImpl->getMD(Kind, Inst);
501 /// getMDs - Get the metadata attached to an Instruction.
502 void MetadataContext::
503 getMDs(const Instruction *Inst,
504 SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs) const {
505 return pImpl->getMDs(Inst, MDs);
508 /// addMD - Attach the metadata of given kind to an Instruction.
509 void MetadataContext::addMD(unsigned Kind, MDNode *Node, Instruction *Inst) {
510 pImpl->addMD(Kind, Node, Inst);
513 /// removeMD - Remove metadata of given kind attached with an instruction.
514 void MetadataContext::removeMD(unsigned Kind, Instruction *Inst) {
515 pImpl->removeMD(Kind, Inst);
518 /// removeAllMetadata - Remove all metadata attached with an instruction.
519 void MetadataContext::removeAllMetadata(Instruction *Inst) {
520 pImpl->removeAllMetadata(Inst);
523 /// copyMD - If metadata is attached with Instruction In1 then attach
524 /// the same metadata to In2.
525 void MetadataContext::copyMD(Instruction *In1, Instruction *In2) {
526 pImpl->copyMD(In1, In2);
529 /// getHandlerNames - Populate client supplied smallvector using custome
530 /// metadata name and ID.
531 void MetadataContext::
532 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&N) const {
533 pImpl->getHandlerNames(N);
536 /// ValueIsDeleted - This handler is used to update metadata store
537 /// when a value is deleted.
538 void MetadataContext::ValueIsDeleted(Instruction *Inst) {
539 pImpl->ValueIsDeleted(Inst);
541 void MetadataContext::ValueIsRAUWd(Value *V1, Value *V2) {
542 pImpl->ValueIsRAUWd(V1, V2);
545 /// ValueIsCloned - This handler is used to update metadata store
546 /// when In1 is cloned to create In2.
547 void MetadataContext::ValueIsCloned(const Instruction *In1, Instruction *In2) {
548 pImpl->ValueIsCloned(In1, In2);