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 "LLVMContextImpl.h"
15 #include "llvm/Metadata.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"
24 //===----------------------------------------------------------------------===//
25 // MetadataBase implementation.
28 //===----------------------------------------------------------------------===//
29 // MDString implementation.
31 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
32 LLVMContextImpl *pImpl = Context.pImpl;
33 StringMapEntry<MDString *> &Entry =
34 pImpl->MDStringCache.GetOrCreateValue(Str);
35 MDString *&S = Entry.getValue();
36 if (!S) S = new MDString(Context, Entry.getKey());
40 MDString *MDString::get(LLVMContext &Context, const char *Str) {
41 LLVMContextImpl *pImpl = Context.pImpl;
42 StringMapEntry<MDString *> &Entry =
43 pImpl->MDStringCache.GetOrCreateValue(Str ? StringRef(Str) : StringRef());
44 MDString *&S = Entry.getValue();
45 if (!S) S = new MDString(Context, Entry.getKey());
49 //===----------------------------------------------------------------------===//
50 // MDNode implementation.
52 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals,
54 : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
56 Node = new ElementVH[NodeSize];
57 ElementVH *Ptr = Node;
58 for (unsigned i = 0; i != NumVals; ++i)
59 *Ptr++ = ElementVH(Vals[i], this);
61 SubclassData |= FunctionLocalBit;
64 void MDNode::Profile(FoldingSetNodeID &ID) const {
65 for (unsigned i = 0, e = getNumElements(); i != e; ++i)
66 ID.AddPointer(getElement(i));
69 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals,
70 bool isFunctionLocal) {
71 LLVMContextImpl *pImpl = Context.pImpl;
73 for (unsigned i = 0; i != NumVals; ++i)
74 ID.AddPointer(Vals[i]);
77 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
79 // InsertPoint will have been set by the FindNodeOrInsertPos call.
80 N = new MDNode(Context, Vals, NumVals, isFunctionLocal);
81 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
86 /// ~MDNode - Destroy MDNode.
88 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
89 pImpl->MDNodeSet.RemoveNode(this);
94 // Replace value from this node's element list.
95 void MDNode::replaceElement(Value *From, Value *To) {
96 if (From == To || !getType())
98 LLVMContext &Context = getType()->getContext();
99 LLVMContextImpl *pImpl = Context.pImpl;
101 // Find value. This is a linear search, do something if it consumes
102 // lot of time. It is possible that to have multiple instances of
103 // From in this MDNode's element list.
104 SmallVector<unsigned, 4> Indexes;
106 for (unsigned i = 0, e = getNumElements(); i != e; ++i, ++Index) {
107 Value *V = getElement(i);
109 Indexes.push_back(Index);
115 // Remove "this" from the context map.
116 pImpl->MDNodeSet.RemoveNode(this);
118 // Replace From element(s) in place.
119 for (SmallVector<unsigned, 4>::iterator I = Indexes.begin(), E = Indexes.end();
122 Node[Index] = ElementVH(To, this);
125 // Insert updated "this" into the context's folding node set.
126 // If a node with same element list already exist then before inserting
127 // updated "this" into the folding node set, replace all uses of existing
128 // node with updated "this" node.
132 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
135 N->replaceAllUsesWith(this);
140 N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
142 // InsertPoint will have been set by the FindNodeOrInsertPos call.
144 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
148 // getLocalFunction - Return false if MDNode's recursive function-localness is
149 // invalid (local to more than one function). Return true otherwise. If MDNode
150 // has one function to which it is local, set LocalFunction to that function.
151 bool MDNode::getLocalFunction(Function *LocalFunction,
152 SmallPtrSet<MDNode *, 32> *VisitedMDNodes) {
153 if (!isFunctionLocal())
157 VisitedMDNodes = new SmallPtrSet<MDNode *, 32>();
159 if (!VisitedMDNodes->insert(this))
160 // MDNode has already been visited, nothing to do.
163 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
164 Value *V = getElement(i);
167 Function *LocalFunctionTemp = NULL;
168 if (Instruction *I = dyn_cast<Instruction>(V))
169 LocalFunctionTemp = I->getParent()->getParent();
170 else if (MDNode *MD = dyn_cast<MDNode>(V))
171 if (!MD->getLocalFunction(LocalFunctionTemp, VisitedMDNodes))
172 // This MDNode's operand is function-locally invalid or local to a
173 // different function.
176 if (LocalFunctionTemp) {
178 LocalFunction = LocalFunctionTemp;
179 else if (LocalFunction != LocalFunctionTemp)
180 // This MDNode contains operands that are local to different functions.
188 //===----------------------------------------------------------------------===//
189 // NamedMDNode implementation.
191 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
192 MetadataBase *const *MDs,
193 unsigned NumMDs, Module *ParentModule)
194 : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
197 for (unsigned i = 0; i != NumMDs; ++i)
198 Node.push_back(TrackingVH<MetadataBase>(MDs[i]));
201 ParentModule->getNamedMDList().push_back(this);
204 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
205 assert(NMD && "Invalid source NamedMDNode!");
206 SmallVector<MetadataBase *, 4> Elems;
207 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
208 Elems.push_back(NMD->getElement(i));
209 return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
210 Elems.data(), Elems.size(), M);
213 /// eraseFromParent - Drop all references and remove the node from parent
215 void NamedMDNode::eraseFromParent() {
216 getParent()->getNamedMDList().erase(this);
219 /// dropAllReferences - Remove all uses and clear node vector.
220 void NamedMDNode::dropAllReferences() {
224 NamedMDNode::~NamedMDNode() {
228 //===----------------------------------------------------------------------===//
229 // MetadataContextImpl implementation.
232 class MetadataContextImpl {
234 typedef std::pair<unsigned, TrackingVH<MDNode> > MDPairTy;
235 typedef SmallVector<MDPairTy, 2> MDMapTy;
236 typedef DenseMap<const Instruction *, MDMapTy> MDStoreTy;
237 friend class BitcodeReader;
240 /// MetadataStore - Collection of metadata used in this context.
241 MDStoreTy MetadataStore;
243 /// MDHandlerNames - Map to hold metadata handler names.
244 StringMap<unsigned> MDHandlerNames;
247 /// registerMDKind - Register a new metadata kind and return its ID.
248 /// A metadata kind can be registered only once.
249 unsigned registerMDKind(StringRef Name);
251 /// getMDKind - Return metadata kind. If the requested metadata kind
252 /// is not registered then return 0.
253 unsigned getMDKind(StringRef Name) const;
255 /// getMD - Get the metadata of given kind attached to an Instruction.
256 /// If the metadata is not found then return 0.
257 MDNode *getMD(unsigned Kind, const Instruction *Inst);
259 /// getMDs - Get the metadata attached to an Instruction.
260 void getMDs(const Instruction *Inst, SmallVectorImpl<MDPairTy> &MDs) const;
262 /// addMD - Attach the metadata of given kind to an Instruction.
263 void addMD(unsigned Kind, MDNode *Node, Instruction *Inst);
265 /// removeMD - Remove metadata of given kind attached with an instruction.
266 void removeMD(unsigned Kind, Instruction *Inst);
268 /// removeAllMetadata - Remove all metadata attached with an instruction.
269 void removeAllMetadata(Instruction *Inst);
271 /// copyMD - If metadata is attached with Instruction In1 then attach
272 /// the same metadata to In2.
273 void copyMD(Instruction *In1, Instruction *In2);
275 /// getHandlerNames - Populate client-supplied smallvector using custom
276 /// metadata name and ID.
277 void getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&) const;
279 /// ValueIsDeleted - This handler is used to update metadata store
280 /// when a value is deleted.
281 void ValueIsDeleted(const Value *) {}
282 void ValueIsDeleted(Instruction *Inst) {
283 removeAllMetadata(Inst);
285 void ValueIsRAUWd(Value *V1, Value *V2);
287 /// ValueIsCloned - This handler is used to update metadata store
288 /// when In1 is cloned to create In2.
289 void ValueIsCloned(const Instruction *In1, Instruction *In2);
293 /// registerMDKind - Register a new metadata kind and return its ID.
294 /// A metadata kind can be registered only once.
295 unsigned MetadataContextImpl::registerMDKind(StringRef Name) {
296 unsigned Count = MDHandlerNames.size();
297 assert(MDHandlerNames.count(Name) == 0 && "Already registered MDKind!");
298 return MDHandlerNames[Name] = Count + 1;
301 /// getMDKind - Return metadata kind. If the requested metadata kind
302 /// is not registered then return 0.
303 unsigned MetadataContextImpl::getMDKind(StringRef Name) const {
304 StringMap<unsigned>::const_iterator I = MDHandlerNames.find(Name);
305 if (I == MDHandlerNames.end())
308 return I->getValue();
311 /// addMD - Attach the metadata of given kind to an Instruction.
312 void MetadataContextImpl::addMD(unsigned MDKind, MDNode *Node,
314 assert(Node && "Invalid null MDNode");
315 Inst->HasMetadata = true;
316 MDMapTy &Info = MetadataStore[Inst];
318 Info.push_back(std::make_pair(MDKind, Node));
319 MetadataStore.insert(std::make_pair(Inst, Info));
323 // If there is an entry for this MDKind then replace it.
324 for (unsigned i = 0, e = Info.size(); i != e; ++i) {
325 MDPairTy &P = Info[i];
326 if (P.first == MDKind) {
327 Info[i] = std::make_pair(MDKind, Node);
332 // Otherwise add a new entry.
333 Info.push_back(std::make_pair(MDKind, Node));
336 /// removeMD - Remove metadata of given kind attached with an instruction.
337 void MetadataContextImpl::removeMD(unsigned Kind, Instruction *Inst) {
338 MDStoreTy::iterator I = MetadataStore.find(Inst);
339 if (I == MetadataStore.end())
342 MDMapTy &Info = I->second;
343 for (MDMapTy::iterator MI = Info.begin(), ME = Info.end(); MI != ME; ++MI) {
345 if (P.first == Kind) {
352 /// removeAllMetadata - Remove all metadata attached with an instruction.
353 void MetadataContextImpl::removeAllMetadata(Instruction *Inst) {
354 MetadataStore.erase(Inst);
355 Inst->HasMetadata = false;
358 /// copyMD - If metadata is attached with Instruction In1 then attach
359 /// the same metadata to In2.
360 void MetadataContextImpl::copyMD(Instruction *In1, Instruction *In2) {
361 assert(In1 && In2 && "Invalid instruction!");
362 MDMapTy &In1Info = MetadataStore[In1];
366 for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
367 addMD(I->first, I->second, In2);
370 /// getMD - Get the metadata of given kind attached to an Instruction.
371 /// If the metadata is not found then return 0.
372 MDNode *MetadataContextImpl::getMD(unsigned MDKind, const Instruction *Inst) {
373 MDMapTy &Info = MetadataStore[Inst];
377 for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I)
378 if (I->first == MDKind)
383 /// getMDs - Get the metadata attached to an Instruction.
384 void MetadataContextImpl::
385 getMDs(const Instruction *Inst, SmallVectorImpl<MDPairTy> &MDs) const {
386 MDStoreTy::const_iterator I = MetadataStore.find(Inst);
387 if (I == MetadataStore.end())
389 MDs.resize(I->second.size());
390 for (MDMapTy::const_iterator MI = I->second.begin(), ME = I->second.end();
392 // MD kinds are numbered from 1.
393 MDs[MI->first - 1] = std::make_pair(MI->first, MI->second);
396 /// getHandlerNames - Populate client supplied smallvector using custome
397 /// metadata name and ID.
398 void MetadataContextImpl::
399 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&Names) const {
400 Names.resize(MDHandlerNames.size());
401 for (StringMap<unsigned>::const_iterator I = MDHandlerNames.begin(),
402 E = MDHandlerNames.end(); I != E; ++I)
403 // MD Handlers are numbered from 1.
404 Names[I->second - 1] = std::make_pair(I->second, I->first());
407 /// ValueIsCloned - This handler is used to update metadata store
408 /// when In1 is cloned to create In2.
409 void MetadataContextImpl::ValueIsCloned(const Instruction *In1,
411 // Find Metadata handles for In1.
412 MDStoreTy::iterator I = MetadataStore.find(In1);
413 assert(I != MetadataStore.end() && "Invalid custom metadata info!");
415 // FIXME : Give all metadata handlers a chance to adjust.
417 MDMapTy &In1Info = I->second;
419 for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
420 addMD(I->first, I->second, In2);
423 /// ValueIsRAUWd - This handler is used when V1's all uses are replaced by
425 void MetadataContextImpl::ValueIsRAUWd(Value *V1, Value *V2) {
426 Instruction *I1 = dyn_cast<Instruction>(V1);
427 Instruction *I2 = dyn_cast<Instruction>(V2);
431 // FIXME : Give custom handlers a chance to override this.
432 ValueIsCloned(I1, I2);
435 //===----------------------------------------------------------------------===//
436 // MetadataContext implementation.
438 MetadataContext::MetadataContext()
439 : pImpl(new MetadataContextImpl()) { }
440 MetadataContext::~MetadataContext() { delete pImpl; }
442 /// isValidName - Return true if Name is a valid custom metadata handler name.
443 bool MetadataContext::isValidName(StringRef MDName) {
447 if (!isalpha(MDName[0]))
450 for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
452 if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
458 /// registerMDKind - Register a new metadata kind and return its ID.
459 /// A metadata kind can be registered only once.
460 unsigned MetadataContext::registerMDKind(StringRef Name) {
461 assert(isValidName(Name) && "Invalid custome metadata name!");
462 return pImpl->registerMDKind(Name);
465 /// getMDKind - Return metadata kind. If the requested metadata kind
466 /// is not registered then return 0.
467 unsigned MetadataContext::getMDKind(StringRef Name) const {
468 return pImpl->getMDKind(Name);
471 /// getMD - Get the metadata of given kind attached to an Instruction.
472 /// If the metadata is not found then return 0.
473 MDNode *MetadataContext::getMD(unsigned Kind, const Instruction *Inst) {
474 return pImpl->getMD(Kind, Inst);
477 /// getMDs - Get the metadata attached to an Instruction.
478 void MetadataContext::
479 getMDs(const Instruction *Inst,
480 SmallVectorImpl<std::pair<unsigned, TrackingVH<MDNode> > > &MDs) const {
481 return pImpl->getMDs(Inst, MDs);
484 /// addMD - Attach the metadata of given kind to an Instruction.
485 void MetadataContext::addMD(unsigned Kind, MDNode *Node, Instruction *Inst) {
486 pImpl->addMD(Kind, Node, Inst);
489 /// removeMD - Remove metadata of given kind attached with an instruction.
490 void MetadataContext::removeMD(unsigned Kind, Instruction *Inst) {
491 pImpl->removeMD(Kind, Inst);
494 /// removeAllMetadata - Remove all metadata attached with an instruction.
495 void MetadataContext::removeAllMetadata(Instruction *Inst) {
496 pImpl->removeAllMetadata(Inst);
499 /// copyMD - If metadata is attached with Instruction In1 then attach
500 /// the same metadata to In2.
501 void MetadataContext::copyMD(Instruction *In1, Instruction *In2) {
502 pImpl->copyMD(In1, In2);
505 /// getHandlerNames - Populate client supplied smallvector using custome
506 /// metadata name and ID.
507 void MetadataContext::
508 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&N) const {
509 pImpl->getHandlerNames(N);
512 /// ValueIsDeleted - This handler is used to update metadata store
513 /// when a value is deleted.
514 void MetadataContext::ValueIsDeleted(Instruction *Inst) {
515 pImpl->ValueIsDeleted(Inst);
517 void MetadataContext::ValueIsRAUWd(Value *V1, Value *V2) {
518 pImpl->ValueIsRAUWd(V1, V2);
521 /// ValueIsCloned - This handler is used to update metadata store
522 /// when In1 is cloned to create In2.
523 void MetadataContext::ValueIsCloned(const Instruction *In1, Instruction *In2) {
524 pImpl->ValueIsCloned(In1, In2);