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