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 "SymbolTableListTraitsImpl.h"
22 //===----------------------------------------------------------------------===//
23 // MetadataBase implementation.
26 /// resizeOperands - Metadata keeps track of other metadata uses using
27 /// OperandList. Resize this list to hold anticipated number of metadata
29 void MetadataBase::resizeOperands(unsigned NumOps) {
30 unsigned e = getNumOperands();
33 if (NumOps < 2) NumOps = 2;
34 } else if (NumOps > NumOperands) {
36 if (ReservedSpace >= NumOps) return;
37 } else if (NumOps == NumOperands) {
38 if (ReservedSpace == NumOps) return;
43 ReservedSpace = NumOps;
44 Use *OldOps = OperandList;
45 Use *NewOps = allocHungoffUses(NumOps);
46 std::copy(OldOps, OldOps + e, NewOps);
48 if (OldOps) Use::zap(OldOps, OldOps + e, true);
50 //===----------------------------------------------------------------------===//
51 // MDString implementation.
53 MDString *MDString::get(LLVMContext &Context, const StringRef &Str) {
54 LLVMContextImpl *pImpl = Context.pImpl;
55 StringMapEntry<MDString *> &Entry =
56 pImpl->MDStringCache.GetOrCreateValue(Str);
57 MDString *&S = Entry.getValue();
60 return S = new MDString(Context, Entry.getKeyData(), Entry.getKeyLength());
63 //===----------------------------------------------------------------------===//
64 // MDNode implementation.
66 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals)
67 : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
69 resizeOperands(NumVals);
71 Node = new ElementVH[NodeSize];
72 ElementVH *Ptr = Node;
73 for (unsigned i = 0; i != NumVals; ++i) {
74 // Only record metadata uses.
75 if (MetadataBase *MB = dyn_cast_or_null<MetadataBase>(Vals[i]))
76 OperandList[NumOperands++] = MB;
78 Vals[i]->getType()->getTypeID() == Type::MetadataTyID)
79 OperandList[NumOperands++] = Vals[i];
80 *Ptr++ = ElementVH(Vals[i], this);
84 void MDNode::Profile(FoldingSetNodeID &ID) const {
85 for (unsigned i = 0, e = getNumElements(); i != e; ++i)
86 ID.AddPointer(getElement(i));
89 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals) {
90 LLVMContextImpl *pImpl = Context.pImpl;
92 for (unsigned i = 0; i != NumVals; ++i)
93 ID.AddPointer(Vals[i]);
98 N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
102 N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
104 // InsertPoint will have been set by the FindNodeOrInsertPos call.
105 N = new MDNode(Context, Vals, NumVals);
106 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
112 /// dropAllReferences - Remove all uses and clear node vector.
113 void MDNode::dropAllReferences() {
114 User::dropAllReferences();
121 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
122 pImpl->MDNodeSet.RemoveNode(this);
127 // Replace value from this node's element list.
128 void MDNode::replaceElement(Value *From, Value *To) {
129 if (From == To || !getType())
131 LLVMContext &Context = getType()->getContext();
132 LLVMContextImpl *pImpl = Context.pImpl;
134 // Find value. This is a linear search, do something if it consumes
135 // lot of time. It is possible that to have multiple instances of
136 // From in this MDNode's element list.
137 SmallVector<unsigned, 4> Indexes;
139 for (unsigned i = 0, e = getNumElements(); i != e; ++i, ++Index) {
140 Value *V = getElement(i);
142 Indexes.push_back(Index);
148 // Remove "this" from the context map.
149 pImpl->MDNodeSet.RemoveNode(this);
151 // MDNode only lists metadata elements in operand list, because MDNode
152 // used by MDNode is considered a valid use. However on the side, MDNode
153 // using a non-metadata value is not considered a "use" of non-metadata
155 SmallVector<unsigned, 4> OpIndexes;
156 unsigned OpIndex = 0;
157 for (User::op_iterator OI = op_begin(), OE = op_end();
158 OI != OE; ++OI, OpIndex++) {
160 OpIndexes.push_back(OpIndex);
162 if (MetadataBase *MDTo = dyn_cast_or_null<MetadataBase>(To)) {
163 for (SmallVector<unsigned, 4>::iterator OI = OpIndexes.begin(),
164 OE = OpIndexes.end(); OI != OE; ++OI)
165 setOperand(*OI, MDTo);
167 for (SmallVector<unsigned, 4>::iterator OI = OpIndexes.begin(),
168 OE = OpIndexes.end(); OI != OE; ++OI)
172 // Replace From element(s) in place.
173 for (SmallVector<unsigned, 4>::iterator I = Indexes.begin(), E = Indexes.end();
176 Node[Index] = ElementVH(To, this);
179 // Insert updated "this" into the context's folding node set.
180 // If a node with same element list already exist then before inserting
181 // updated "this" into the folding node set, replace all uses of existing
182 // node with updated "this" node.
186 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
189 N->replaceAllUsesWith(this);
194 N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
196 // InsertPoint will have been set by the FindNodeOrInsertPos call.
198 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
202 //===----------------------------------------------------------------------===//
203 // NamedMDNode implementation.
205 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
206 MetadataBase *const *MDs,
207 unsigned NumMDs, Module *ParentModule)
208 : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
211 resizeOperands(NumMDs);
213 for (unsigned i = 0; i != NumMDs; ++i) {
215 OperandList[NumOperands++] = MDs[i];
216 Node.push_back(WeakMetadataVH(MDs[i]));
219 ParentModule->getNamedMDList().push_back(this);
222 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
223 assert(NMD && "Invalid source NamedMDNode!");
224 SmallVector<MetadataBase *, 4> Elems;
225 for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
226 Elems.push_back(NMD->getElement(i));
227 return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
228 Elems.data(), Elems.size(), M);
231 /// eraseFromParent - Drop all references and remove the node from parent
233 void NamedMDNode::eraseFromParent() {
234 getParent()->getNamedMDList().erase(this);
237 /// dropAllReferences - Remove all uses and clear node vector.
238 void NamedMDNode::dropAllReferences() {
239 User::dropAllReferences();
243 NamedMDNode::~NamedMDNode() {
247 //===----------------------------------------------------------------------===//
248 // MetadataContext implementation.
251 /// registerMDKind - Register a new metadata kind and return its ID.
252 /// A metadata kind can be registered only once.
253 unsigned MetadataContext::registerMDKind(const StringRef Name) {
254 assert(isValidName(Name) && "Invalid custome metadata name!");
255 unsigned Count = MDHandlerNames.size();
256 assert(MDHandlerNames.count(Name) == 0 && "Already registered MDKind!");
257 return MDHandlerNames[Name] = Count + 1;
260 /// isValidName - Return true if Name is a valid custom metadata handler name.
261 bool MetadataContext::isValidName(const StringRef MDName) {
265 if (!isalpha(MDName[0]))
268 for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
270 if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
276 /// getMDKind - Return metadata kind. If the requested metadata kind
277 /// is not registered then return 0.
278 unsigned MetadataContext::getMDKind(const StringRef Name) const {
279 StringMap<unsigned>::const_iterator I = MDHandlerNames.find(Name);
280 if (I == MDHandlerNames.end()) {
281 assert(isValidName(Name) && "Invalid custome metadata name!");
285 return I->getValue();
288 /// addMD - Attach the metadata of given kind to an Instruction.
289 void MetadataContext::addMD(unsigned MDKind, MDNode *Node, Instruction *Inst) {
290 assert(Node && "Invalid null MDNode");
291 Inst->HasMetadata = true;
292 MDMapTy &Info = MetadataStore[Inst];
294 Info.push_back(std::make_pair(MDKind, Node));
295 MetadataStore.insert(std::make_pair(Inst, Info));
299 // If there is an entry for this MDKind then replace it.
300 for (unsigned i = 0, e = Info.size(); i != e; ++i) {
301 MDPairTy &P = Info[i];
302 if (P.first == MDKind) {
303 Info[i] = std::make_pair(MDKind, Node);
308 // Otherwise add a new entry.
309 Info.push_back(std::make_pair(MDKind, Node));
312 /// removeMD - Remove metadata of given kind attached with an instuction.
313 void MetadataContext::removeMD(unsigned Kind, Instruction *Inst) {
314 MDStoreTy::iterator I = MetadataStore.find(Inst);
315 if (I == MetadataStore.end())
318 MDMapTy &Info = I->second;
319 for (MDMapTy::iterator MI = Info.begin(), ME = Info.end(); MI != ME; ++MI) {
321 if (P.first == Kind) {
328 /// removeAllMetadata - Remove all metadata attached with an instruction.
329 void MetadataContext::removeAllMetadata(Instruction *Inst) {
330 MetadataStore.erase(Inst);
331 Inst->HasMetadata = false;
334 /// copyMD - If metadata is attached with Instruction In1 then attach
335 /// the same metadata to In2.
336 void MetadataContext::copyMD(Instruction *In1, Instruction *In2) {
337 assert(In1 && In2 && "Invalid instruction!");
338 MDMapTy &In1Info = MetadataStore[In1];
342 for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
343 if (MDNode *MD = dyn_cast_or_null<MDNode>(I->second))
344 addMD(I->first, MD, In2);
347 /// getMD - Get the metadata of given kind attached to an Instruction.
348 /// If the metadata is not found then return 0.
349 MDNode *MetadataContext::getMD(unsigned MDKind, const Instruction *Inst) {
350 MDMapTy &Info = MetadataStore[Inst];
354 for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I)
355 if (I->first == MDKind)
356 return dyn_cast_or_null<MDNode>(I->second);
360 /// getMDs - Get the metadata attached to an Instruction.
361 const MetadataContext::MDMapTy *
362 MetadataContext::getMDs(const Instruction *Inst) {
363 MDStoreTy::iterator I = MetadataStore.find(Inst);
364 if (I == MetadataStore.end())
370 /// getHandlerNames - Get handler names. This is used by bitcode
372 const StringMap<unsigned> *MetadataContext::getHandlerNames() {
373 return &MDHandlerNames;
376 /// ValueIsCloned - This handler is used to update metadata store
377 /// when In1 is cloned to create In2.
378 void MetadataContext::ValueIsCloned(const Instruction *In1, Instruction *In2) {
379 // Find Metadata handles for In1.
380 MDStoreTy::iterator I = MetadataStore.find(In1);
381 assert(I != MetadataStore.end() && "Invalid custom metadata info!");
383 // FIXME : Give all metadata handlers a chance to adjust.
385 MDMapTy &In1Info = I->second;
387 for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
388 if (MDNode *MD = dyn_cast_or_null<MDNode>(I->second))
389 addMD(I->first, MD, In2);
392 /// ValueIsRAUWd - This handler is used when V1's all uses are replaced by
394 void MetadataContext::ValueIsRAUWd(Value *V1, Value *V2) {
395 Instruction *I1 = dyn_cast<Instruction>(V1);
396 Instruction *I2 = dyn_cast<Instruction>(V2);
400 // FIXME : Give custom handlers a chance to override this.
401 ValueIsCloned(I1, I2);