Derive metadata hierarchy from Value instead of User.
[oota-llvm.git] / lib / VMCore / Metadata.cpp
1 //===-- Metadata.cpp - Implement Metadata classes -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Metadata classes.
11 //
12 //===----------------------------------------------------------------------===//
13
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"
20 using namespace llvm;
21
22 //===----------------------------------------------------------------------===//
23 // MetadataBase implementation.
24 //
25
26 //===----------------------------------------------------------------------===//
27 // MDString implementation.
28 //
29 MDString *MDString::get(LLVMContext &Context, const StringRef &Str) {
30   LLVMContextImpl *pImpl = Context.pImpl;
31   StringMapEntry<MDString *> &Entry = 
32     pImpl->MDStringCache.GetOrCreateValue(Str);
33   MDString *&S = Entry.getValue();
34   if (S) return S;
35   
36   return S = new MDString(Context, Entry.getKeyData(), Entry.getKeyLength());
37 }
38
39 //===----------------------------------------------------------------------===//
40 // MDNode implementation.
41 //
42 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals)
43   : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
44   NodeSize = NumVals;
45   Node = new ElementVH[NodeSize];
46   ElementVH *Ptr = Node;
47   for (unsigned i = 0; i != NumVals; ++i) 
48     *Ptr++ = ElementVH(Vals[i], this);
49 }
50
51 void MDNode::Profile(FoldingSetNodeID &ID) const {
52   for (unsigned i = 0, e = getNumElements(); i != e; ++i)
53     ID.AddPointer(getElement(i));
54 }
55
56 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals) {
57   LLVMContextImpl *pImpl = Context.pImpl;
58   FoldingSetNodeID ID;
59   for (unsigned i = 0; i != NumVals; ++i)
60     ID.AddPointer(Vals[i]);
61
62   void *InsertPoint;
63   MDNode *N;
64   {
65     N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
66   }  
67   if (N) return N;
68   
69   N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
70   if (!N) {
71     // InsertPoint will have been set by the FindNodeOrInsertPos call.
72     N = new MDNode(Context, Vals, NumVals);
73     pImpl->MDNodeSet.InsertNode(N, InsertPoint);
74   }
75
76   return N;
77 }
78
79 /// ~MDNode - Destroy MDNode.
80 MDNode::~MDNode() {
81   {
82     LLVMContextImpl *pImpl = getType()->getContext().pImpl;
83     pImpl->MDNodeSet.RemoveNode(this);
84   }
85   delete [] Node;
86   Node = NULL;
87 }
88
89 // Replace value from this node's element list.
90 void MDNode::replaceElement(Value *From, Value *To) {
91   if (From == To || !getType())
92     return;
93   LLVMContext &Context = getType()->getContext();
94   LLVMContextImpl *pImpl = Context.pImpl;
95
96   // Find value. This is a linear search, do something if it consumes 
97   // lot of time. It is possible that to have multiple instances of
98   // From in this MDNode's element list.
99   SmallVector<unsigned, 4> Indexes;
100   unsigned Index = 0;
101   for (unsigned i = 0, e = getNumElements(); i != e; ++i, ++Index) {
102     Value *V = getElement(i);
103     if (V && V == From) 
104       Indexes.push_back(Index);
105   }
106
107   if (Indexes.empty())
108     return;
109
110   // Remove "this" from the context map. 
111   pImpl->MDNodeSet.RemoveNode(this);
112
113   // Replace From element(s) in place.
114   for (SmallVector<unsigned, 4>::iterator I = Indexes.begin(), E = Indexes.end(); 
115        I != E; ++I) {
116     unsigned Index = *I;
117     Node[Index] = ElementVH(To, this);
118   }
119
120   // Insert updated "this" into the context's folding node set.
121   // If a node with same element list already exist then before inserting 
122   // updated "this" into the folding node set, replace all uses of existing 
123   // node with updated "this" node.
124   FoldingSetNodeID ID;
125   Profile(ID);
126   void *InsertPoint;
127   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
128
129   if (N) {
130     N->replaceAllUsesWith(this);
131     delete N;
132     N = 0;
133   }
134
135   N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
136   if (!N) {
137     // InsertPoint will have been set by the FindNodeOrInsertPos call.
138     N = this;
139     pImpl->MDNodeSet.InsertNode(N, InsertPoint);
140   }
141 }
142
143 //===----------------------------------------------------------------------===//
144 // NamedMDNode implementation.
145 //
146 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
147                          MetadataBase *const *MDs, 
148                          unsigned NumMDs, Module *ParentModule)
149   : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
150   setName(N);
151
152   for (unsigned i = 0; i != NumMDs; ++i)
153     Node.push_back(WeakMetadataVH(MDs[i]));
154
155   if (ParentModule)
156     ParentModule->getNamedMDList().push_back(this);
157 }
158
159 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
160   assert(NMD && "Invalid source NamedMDNode!");
161   SmallVector<MetadataBase *, 4> Elems;
162   for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
163     Elems.push_back(NMD->getElement(i));
164   return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
165                          Elems.data(), Elems.size(), M);
166 }
167
168 /// eraseFromParent - Drop all references and remove the node from parent
169 /// module.
170 void NamedMDNode::eraseFromParent() {
171   getParent()->getNamedMDList().erase(this);
172 }
173
174 /// dropAllReferences - Remove all uses and clear node vector.
175 void NamedMDNode::dropAllReferences() {
176   Node.clear();
177 }
178
179 NamedMDNode::~NamedMDNode() {
180   dropAllReferences();
181 }
182
183 //===----------------------------------------------------------------------===//
184 // MetadataContext implementation.
185 //
186
187 /// registerMDKind - Register a new metadata kind and return its ID.
188 /// A metadata kind can be registered only once. 
189 unsigned MetadataContext::registerMDKind(const StringRef Name) {
190   assert(isValidName(Name) && "Invalid custome metadata name!");
191   unsigned Count = MDHandlerNames.size();
192   assert(MDHandlerNames.count(Name) == 0 && "Already registered MDKind!");
193   return MDHandlerNames[Name] = Count + 1;
194 }
195
196 /// isValidName - Return true if Name is a valid custom metadata handler name.
197 bool MetadataContext::isValidName(const StringRef MDName) {
198   if (MDName.empty())
199     return false;
200
201   if (!isalpha(MDName[0]))
202     return false;
203
204   for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
205        ++I) {
206     if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
207         return false;
208   }
209   return true;
210 }
211
212 /// getMDKind - Return metadata kind. If the requested metadata kind
213 /// is not registered then return 0.
214 unsigned MetadataContext::getMDKind(const StringRef Name) const {
215   StringMap<unsigned>::const_iterator I = MDHandlerNames.find(Name);
216   if (I == MDHandlerNames.end()) {
217     assert(isValidName(Name) && "Invalid custome metadata name!");
218     return 0;
219   }
220
221   return I->getValue();
222 }
223
224 /// addMD - Attach the metadata of given kind to an Instruction.
225 void MetadataContext::addMD(unsigned MDKind, MDNode *Node, Instruction *Inst) {
226   assert(Node && "Invalid null MDNode");
227   Inst->HasMetadata = true;
228   MDMapTy &Info = MetadataStore[Inst];
229   if (Info.empty()) {
230     Info.push_back(std::make_pair(MDKind, Node));
231     MetadataStore.insert(std::make_pair(Inst, Info));
232     return;
233   }
234
235   // If there is an entry for this MDKind then replace it.
236   for (unsigned i = 0, e = Info.size(); i != e; ++i) {
237     MDPairTy &P = Info[i];
238     if (P.first == MDKind) {
239       Info[i] = std::make_pair(MDKind, Node);
240       return;
241     }
242   }
243
244   // Otherwise add a new entry.
245   Info.push_back(std::make_pair(MDKind, Node));
246 }
247
248 /// removeMD - Remove metadata of given kind attached with an instuction.
249 void MetadataContext::removeMD(unsigned Kind, Instruction *Inst) {
250   MDStoreTy::iterator I = MetadataStore.find(Inst);
251   if (I == MetadataStore.end())
252     return;
253
254   MDMapTy &Info = I->second;
255   for (MDMapTy::iterator MI = Info.begin(), ME = Info.end(); MI != ME; ++MI) {
256     MDPairTy &P = *MI;
257     if (P.first == Kind) {
258       Info.erase(MI);
259       return;
260     }
261   }
262 }
263   
264 /// removeAllMetadata - Remove all metadata attached with an instruction.
265 void MetadataContext::removeAllMetadata(Instruction *Inst) {
266   MetadataStore.erase(Inst);
267   Inst->HasMetadata = false;
268 }
269
270 /// copyMD - If metadata is attached with Instruction In1 then attach
271 /// the same metadata to In2.
272 void MetadataContext::copyMD(Instruction *In1, Instruction *In2) {
273   assert(In1 && In2 && "Invalid instruction!");
274   MDMapTy &In1Info = MetadataStore[In1];
275   if (In1Info.empty())
276     return;
277
278   for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
279     if (MDNode *MD = dyn_cast_or_null<MDNode>(I->second))
280       addMD(I->first, MD, In2);
281 }
282
283 /// getMD - Get the metadata of given kind attached to an Instruction.
284 /// If the metadata is not found then return 0.
285 MDNode *MetadataContext::getMD(unsigned MDKind, const Instruction *Inst) {
286   MDMapTy &Info = MetadataStore[Inst];
287   if (Info.empty())
288     return NULL;
289
290   for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I)
291     if (I->first == MDKind)
292       return dyn_cast_or_null<MDNode>(I->second);
293   return NULL;
294 }
295
296 /// getMDs - Get the metadata attached to an Instruction.
297 const MetadataContext::MDMapTy *
298 MetadataContext::getMDs(const Instruction *Inst) {
299   MDStoreTy::iterator I = MetadataStore.find(Inst);
300   if (I == MetadataStore.end())
301     return NULL;
302   
303   return &I->second;
304 }
305
306 /// getHandlerNames - Get handler names. This is used by bitcode
307 /// writer.
308 const StringMap<unsigned> *MetadataContext::getHandlerNames() {
309   return &MDHandlerNames;
310 }
311
312 /// ValueIsCloned - This handler is used to update metadata store
313 /// when In1 is cloned to create In2.
314 void MetadataContext::ValueIsCloned(const Instruction *In1, Instruction *In2) {
315   // Find Metadata handles for In1.
316   MDStoreTy::iterator I = MetadataStore.find(In1);
317   assert(I != MetadataStore.end() && "Invalid custom metadata info!");
318
319   // FIXME : Give all metadata handlers a chance to adjust.
320
321   MDMapTy &In1Info = I->second;
322   MDMapTy In2Info;
323   for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
324     if (MDNode *MD = dyn_cast_or_null<MDNode>(I->second))
325       addMD(I->first, MD, In2);
326 }
327
328 /// ValueIsRAUWd - This handler is used when V1's all uses are replaced by
329 /// V2.
330 void MetadataContext::ValueIsRAUWd(Value *V1, Value *V2) {
331   Instruction *I1 = dyn_cast<Instruction>(V1);
332   Instruction *I2 = dyn_cast<Instruction>(V2);
333   if (!I1 || !I2)
334     return;
335
336   // FIXME : Give custom handlers a chance to override this.
337   ValueIsCloned(I1, I2);
338 }
339