Use different name for argument and field
[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 "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "SymbolTableListTraitsImpl.h"
22 using namespace llvm;
23
24 //===----------------------------------------------------------------------===//
25 // MetadataBase implementation.
26 //
27
28 //===----------------------------------------------------------------------===//
29 // MDString implementation.
30 //
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());
37   return S;
38 }
39
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());
46   return S;
47 }
48
49 //===----------------------------------------------------------------------===//
50 // MDNode implementation.
51 //
52 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals,
53                Function *LocalFunc)
54   : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
55   NodeSize = NumVals;
56   Node = new ElementVH[NodeSize];
57   ElementVH *Ptr = Node;
58   for (unsigned i = 0; i != NumVals; ++i) 
59     *Ptr++ = ElementVH(Vals[i], this);
60   LocalFunction = LocalFunc;
61 }
62
63 void MDNode::Profile(FoldingSetNodeID &ID) const {
64   for (unsigned i = 0, e = getNumElements(); i != e; ++i)
65     ID.AddPointer(getElement(i));
66 }
67
68 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals,
69                     Function *LocalFunction) {
70   LLVMContextImpl *pImpl = Context.pImpl;
71   FoldingSetNodeID ID;
72   for (unsigned i = 0; i != NumVals; ++i)
73     ID.AddPointer(Vals[i]);
74   if (LocalFunction)
75     ID.AddPointer(LocalFunction);
76
77   void *InsertPoint;
78   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
79   if (!N) {
80     // InsertPoint will have been set by the FindNodeOrInsertPos call.
81     N = new MDNode(Context, Vals, NumVals, LocalFunction);
82     pImpl->MDNodeSet.InsertNode(N, InsertPoint);
83   }
84   return N;
85 }
86
87 /// ~MDNode - Destroy MDNode.
88 MDNode::~MDNode() {
89   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
90   pImpl->MDNodeSet.RemoveNode(this);
91   delete [] Node;
92   Node = NULL;
93 }
94
95 // Replace value from this node's element list.
96 void MDNode::replaceElement(Value *From, Value *To) {
97   if (From == To || !getType())
98     return;
99   LLVMContext &Context = getType()->getContext();
100   LLVMContextImpl *pImpl = Context.pImpl;
101
102   // Find value. This is a linear search, do something if it consumes 
103   // lot of time. It is possible that to have multiple instances of
104   // From in this MDNode's element list.
105   SmallVector<unsigned, 4> Indexes;
106   unsigned Index = 0;
107   for (unsigned i = 0, e = getNumElements(); i != e; ++i, ++Index) {
108     Value *V = getElement(i);
109     if (V && V == From) 
110       Indexes.push_back(Index);
111   }
112
113   if (Indexes.empty())
114     return;
115
116   // Remove "this" from the context map. 
117   pImpl->MDNodeSet.RemoveNode(this);
118
119   // Replace From element(s) in place.
120   for (SmallVector<unsigned, 4>::iterator I = Indexes.begin(), E = Indexes.end(); 
121        I != E; ++I) {
122     unsigned Index = *I;
123     Node[Index] = ElementVH(To, this);
124   }
125
126   // Insert updated "this" into the context's folding node set.
127   // If a node with same element list already exist then before inserting 
128   // updated "this" into the folding node set, replace all uses of existing 
129   // node with updated "this" node.
130   FoldingSetNodeID ID;
131   Profile(ID);
132   void *InsertPoint;
133   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
134
135   if (N) {
136     N->replaceAllUsesWith(this);
137     delete N;
138     N = 0;
139   }
140
141   N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
142   if (!N) {
143     // InsertPoint will have been set by the FindNodeOrInsertPos call.
144     N = this;
145     pImpl->MDNodeSet.InsertNode(N, InsertPoint);
146   }
147 }
148
149 //===----------------------------------------------------------------------===//
150 // NamedMDNode implementation.
151 //
152 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
153                          MetadataBase *const *MDs, 
154                          unsigned NumMDs, Module *ParentModule)
155   : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
156   setName(N);
157
158   for (unsigned i = 0; i != NumMDs; ++i)
159     Node.push_back(TrackingVH<MetadataBase>(MDs[i]));
160
161   if (ParentModule)
162     ParentModule->getNamedMDList().push_back(this);
163 }
164
165 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
166   assert(NMD && "Invalid source NamedMDNode!");
167   SmallVector<MetadataBase *, 4> Elems;
168   for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
169     Elems.push_back(NMD->getElement(i));
170   return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
171                          Elems.data(), Elems.size(), M);
172 }
173
174 /// eraseFromParent - Drop all references and remove the node from parent
175 /// module.
176 void NamedMDNode::eraseFromParent() {
177   getParent()->getNamedMDList().erase(this);
178 }
179
180 /// dropAllReferences - Remove all uses and clear node vector.
181 void NamedMDNode::dropAllReferences() {
182   Node.clear();
183 }
184
185 NamedMDNode::~NamedMDNode() {
186   dropAllReferences();
187 }
188
189 //===----------------------------------------------------------------------===//
190 // MetadataContextImpl implementation.
191 //
192 namespace llvm {
193 class MetadataContextImpl {
194 public:
195   typedef std::pair<unsigned, TrackingVH<MDNode> > MDPairTy;
196   typedef SmallVector<MDPairTy, 2> MDMapTy;
197   typedef DenseMap<const Instruction *, MDMapTy> MDStoreTy;
198   friend class BitcodeReader;
199 private:
200
201   /// MetadataStore - Collection of metadata used in this context.
202   MDStoreTy MetadataStore;
203
204   /// MDHandlerNames - Map to hold metadata handler names.
205   StringMap<unsigned> MDHandlerNames;
206
207 public:
208   /// registerMDKind - Register a new metadata kind and return its ID.
209   /// A metadata kind can be registered only once. 
210   unsigned registerMDKind(StringRef Name);
211
212   /// getMDKind - Return metadata kind. If the requested metadata kind
213   /// is not registered then return 0.
214   unsigned getMDKind(StringRef Name) const;
215
216   /// getMD - Get the metadata of given kind attached to an Instruction.
217   /// If the metadata is not found then return 0.
218   MDNode *getMD(unsigned Kind, const Instruction *Inst);
219
220   /// getMDs - Get the metadata attached to an Instruction.
221   void getMDs(const Instruction *Inst, SmallVectorImpl<MDPairTy> &MDs) const;
222
223   /// addMD - Attach the metadata of given kind to an Instruction.
224   void addMD(unsigned Kind, MDNode *Node, Instruction *Inst);
225   
226   /// removeMD - Remove metadata of given kind attached with an instruction.
227   void removeMD(unsigned Kind, Instruction *Inst);
228   
229   /// removeAllMetadata - Remove all metadata attached with an instruction.
230   void removeAllMetadata(Instruction *Inst);
231
232   /// copyMD - If metadata is attached with Instruction In1 then attach
233   /// the same metadata to In2.
234   void copyMD(Instruction *In1, Instruction *In2);
235
236   /// getHandlerNames - Populate client-supplied smallvector using custom
237   /// metadata name and ID.
238   void getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&) const;
239
240   /// ValueIsDeleted - This handler is used to update metadata store
241   /// when a value is deleted.
242   void ValueIsDeleted(const Value *) {}
243   void ValueIsDeleted(Instruction *Inst) {
244     removeAllMetadata(Inst);
245   }
246   void ValueIsRAUWd(Value *V1, Value *V2);
247
248   /// ValueIsCloned - This handler is used to update metadata store
249   /// when In1 is cloned to create In2.
250   void ValueIsCloned(const Instruction *In1, Instruction *In2);
251 };
252 }
253
254 /// registerMDKind - Register a new metadata kind and return its ID.
255 /// A metadata kind can be registered only once. 
256 unsigned MetadataContextImpl::registerMDKind(StringRef Name) {
257   unsigned Count = MDHandlerNames.size();
258   assert(MDHandlerNames.count(Name) == 0 && "Already registered MDKind!");
259   return MDHandlerNames[Name] = Count + 1;
260 }
261
262 /// getMDKind - Return metadata kind. If the requested metadata kind
263 /// is not registered then return 0.
264 unsigned MetadataContextImpl::getMDKind(StringRef Name) const {
265   StringMap<unsigned>::const_iterator I = MDHandlerNames.find(Name);
266   if (I == MDHandlerNames.end())
267     return 0;
268
269   return I->getValue();
270 }
271
272 /// addMD - Attach the metadata of given kind to an Instruction.
273 void MetadataContextImpl::addMD(unsigned MDKind, MDNode *Node, 
274                                 Instruction *Inst) {
275   assert(Node && "Invalid null MDNode");
276   Inst->HasMetadata = true;
277   MDMapTy &Info = MetadataStore[Inst];
278   if (Info.empty()) {
279     Info.push_back(std::make_pair(MDKind, Node));
280     MetadataStore.insert(std::make_pair(Inst, Info));
281     return;
282   }
283
284   // If there is an entry for this MDKind then replace it.
285   for (unsigned i = 0, e = Info.size(); i != e; ++i) {
286     MDPairTy &P = Info[i];
287     if (P.first == MDKind) {
288       Info[i] = std::make_pair(MDKind, Node);
289       return;
290     }
291   }
292
293   // Otherwise add a new entry.
294   Info.push_back(std::make_pair(MDKind, Node));
295 }
296
297 /// removeMD - Remove metadata of given kind attached with an instruction.
298 void MetadataContextImpl::removeMD(unsigned Kind, Instruction *Inst) {
299   MDStoreTy::iterator I = MetadataStore.find(Inst);
300   if (I == MetadataStore.end())
301     return;
302
303   MDMapTy &Info = I->second;
304   for (MDMapTy::iterator MI = Info.begin(), ME = Info.end(); MI != ME; ++MI) {
305     MDPairTy &P = *MI;
306     if (P.first == Kind) {
307       Info.erase(MI);
308       return;
309     }
310   }
311 }
312
313 /// removeAllMetadata - Remove all metadata attached with an instruction.
314 void MetadataContextImpl::removeAllMetadata(Instruction *Inst) {
315   MetadataStore.erase(Inst);
316   Inst->HasMetadata = false;
317 }
318
319 /// copyMD - If metadata is attached with Instruction In1 then attach
320 /// the same metadata to In2.
321 void MetadataContextImpl::copyMD(Instruction *In1, Instruction *In2) {
322   assert(In1 && In2 && "Invalid instruction!");
323   MDMapTy &In1Info = MetadataStore[In1];
324   if (In1Info.empty())
325     return;
326
327   for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
328     addMD(I->first, I->second, In2);
329 }
330
331 /// getMD - Get the metadata of given kind attached to an Instruction.
332 /// If the metadata is not found then return 0.
333 MDNode *MetadataContextImpl::getMD(unsigned MDKind, const Instruction *Inst) {
334   MDMapTy &Info = MetadataStore[Inst];
335   if (Info.empty())
336     return NULL;
337
338   for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I)
339     if (I->first == MDKind)
340       return I->second;
341   return NULL;
342 }
343
344 /// getMDs - Get the metadata attached to an Instruction.
345 void MetadataContextImpl::
346 getMDs(const Instruction *Inst, SmallVectorImpl<MDPairTy> &MDs) const {
347   MDStoreTy::const_iterator I = MetadataStore.find(Inst);
348   if (I == MetadataStore.end())
349     return;
350   MDs.resize(I->second.size());
351   for (MDMapTy::const_iterator MI = I->second.begin(), ME = I->second.end();
352        MI != ME; ++MI)
353     // MD kinds are numbered from 1.
354     MDs[MI->first - 1] = std::make_pair(MI->first, MI->second);
355 }
356
357 /// getHandlerNames - Populate client supplied smallvector using custome
358 /// metadata name and ID.
359 void MetadataContextImpl::
360 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&Names) const {
361   Names.resize(MDHandlerNames.size());
362   for (StringMap<unsigned>::const_iterator I = MDHandlerNames.begin(),
363          E = MDHandlerNames.end(); I != E; ++I) 
364     // MD Handlers are numbered from 1.
365     Names[I->second - 1] = std::make_pair(I->second, I->first());
366 }
367
368 /// ValueIsCloned - This handler is used to update metadata store
369 /// when In1 is cloned to create In2.
370 void MetadataContextImpl::ValueIsCloned(const Instruction *In1, 
371                                         Instruction *In2) {
372   // Find Metadata handles for In1.
373   MDStoreTy::iterator I = MetadataStore.find(In1);
374   assert(I != MetadataStore.end() && "Invalid custom metadata info!");
375
376   // FIXME : Give all metadata handlers a chance to adjust.
377
378   MDMapTy &In1Info = I->second;
379   MDMapTy In2Info;
380   for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
381     addMD(I->first, I->second, In2);
382 }
383
384 /// ValueIsRAUWd - This handler is used when V1's all uses are replaced by
385 /// V2.
386 void MetadataContextImpl::ValueIsRAUWd(Value *V1, Value *V2) {
387   Instruction *I1 = dyn_cast<Instruction>(V1);
388   Instruction *I2 = dyn_cast<Instruction>(V2);
389   if (!I1 || !I2)
390     return;
391
392   // FIXME : Give custom handlers a chance to override this.
393   ValueIsCloned(I1, I2);
394 }
395
396 //===----------------------------------------------------------------------===//
397 // MetadataContext implementation.
398 //
399 MetadataContext::MetadataContext() 
400   : pImpl(new MetadataContextImpl()) { }
401 MetadataContext::~MetadataContext() { delete pImpl; }
402
403 /// isValidName - Return true if Name is a valid custom metadata handler name.
404 bool MetadataContext::isValidName(StringRef MDName) {
405   if (MDName.empty())
406     return false;
407
408   if (!isalpha(MDName[0]))
409     return false;
410
411   for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
412        ++I) {
413     if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
414         return false;
415   }
416   return true;
417 }
418
419 /// registerMDKind - Register a new metadata kind and return its ID.
420 /// A metadata kind can be registered only once. 
421 unsigned MetadataContext::registerMDKind(StringRef Name) {
422   assert(isValidName(Name) && "Invalid custome metadata name!");
423   return pImpl->registerMDKind(Name);
424 }
425
426 /// getMDKind - Return metadata kind. If the requested metadata kind
427 /// is not registered then return 0.
428 unsigned MetadataContext::getMDKind(StringRef Name) const {
429   return pImpl->getMDKind(Name);
430 }
431
432 /// getMD - Get the metadata of given kind attached to an Instruction.
433 /// If the metadata is not found then return 0.
434 MDNode *MetadataContext::getMD(unsigned Kind, const Instruction *Inst) {
435   return pImpl->getMD(Kind, Inst);
436 }
437
438 /// getMDs - Get the metadata attached to an Instruction.
439 void MetadataContext::
440 getMDs(const Instruction *Inst, 
441        SmallVectorImpl<std::pair<unsigned, TrackingVH<MDNode> > > &MDs) const {
442   return pImpl->getMDs(Inst, MDs);
443 }
444
445 /// addMD - Attach the metadata of given kind to an Instruction.
446 void MetadataContext::addMD(unsigned Kind, MDNode *Node, Instruction *Inst) {
447   pImpl->addMD(Kind, Node, Inst);
448 }
449
450 /// removeMD - Remove metadata of given kind attached with an instruction.
451 void MetadataContext::removeMD(unsigned Kind, Instruction *Inst) {
452   pImpl->removeMD(Kind, Inst);
453 }
454
455 /// removeAllMetadata - Remove all metadata attached with an instruction.
456 void MetadataContext::removeAllMetadata(Instruction *Inst) {
457   pImpl->removeAllMetadata(Inst);
458 }
459
460 /// copyMD - If metadata is attached with Instruction In1 then attach
461 /// the same metadata to In2.
462 void MetadataContext::copyMD(Instruction *In1, Instruction *In2) {
463   pImpl->copyMD(In1, In2);
464 }
465
466 /// getHandlerNames - Populate client supplied smallvector using custome
467 /// metadata name and ID.
468 void MetadataContext::
469 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&N) const {
470   pImpl->getHandlerNames(N);
471 }
472
473 /// ValueIsDeleted - This handler is used to update metadata store
474 /// when a value is deleted.
475 void MetadataContext::ValueIsDeleted(Instruction *Inst) {
476   pImpl->ValueIsDeleted(Inst);
477 }
478 void MetadataContext::ValueIsRAUWd(Value *V1, Value *V2) {
479   pImpl->ValueIsRAUWd(V1, V2);
480 }
481
482 /// ValueIsCloned - This handler is used to update metadata store
483 /// when In1 is cloned to create In2.
484 void MetadataContext::ValueIsCloned(const Instruction *In1, Instruction *In2) {
485   pImpl->ValueIsCloned(In1, In2);
486 }