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