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