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