Eliminate two bits of ugliness in MDNode::replaceElement:
[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
149   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
150
151   // Remove "this" from the context map.  FoldingSet doesn't have to reprofile
152   // this node to remove it, so we don't care what state the operands are in.
153   pImpl->MDNodeSet.RemoveNode(this);
154   
155   // Find value. This is a linear search, do something if it consumes 
156   // lot of time. It is possible that to have multiple instances of
157   // From in this MDNode's element list.
158   for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
159     if (Operands[i] == From)
160       Operands[i].set(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 = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
176     assert(N == 0 && "shouldn't be in the map now!"); (void)N;
177   }
178
179   // InsertPoint will have been set by the FindNodeOrInsertPos call.
180   pImpl->MDNodeSet.InsertNode(this, InsertPoint);
181 }
182
183 //===----------------------------------------------------------------------===//
184 // NamedMDNode implementation.
185 //
186 static SmallVector<TrackingVH<MetadataBase>, 4> &getNMDOps(void *Operands) {
187   return *(SmallVector<TrackingVH<MetadataBase>, 4>*)Operands;
188 }
189
190 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
191                          MetadataBase *const *MDs, 
192                          unsigned NumMDs, Module *ParentModule)
193   : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
194   setName(N);
195     
196   Operands = new SmallVector<TrackingVH<MetadataBase>, 4>();
197     
198   SmallVector<TrackingVH<MetadataBase>, 4> &Node = getNMDOps(Operands);
199   for (unsigned i = 0; i != NumMDs; ++i)
200     Node.push_back(TrackingVH<MetadataBase>(MDs[i]));
201
202   if (ParentModule)
203     ParentModule->getNamedMDList().push_back(this);
204 }
205
206 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
207   assert(NMD && "Invalid source NamedMDNode!");
208   SmallVector<MetadataBase *, 4> Elems;
209   Elems.reserve(NMD->getNumElements());
210   
211   for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
212     Elems.push_back(NMD->getElement(i));
213   return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
214                          Elems.data(), Elems.size(), M);
215 }
216
217 NamedMDNode::~NamedMDNode() {
218   dropAllReferences();
219   delete &getNMDOps(Operands);
220 }
221
222 /// getNumElements - Return number of NamedMDNode elements.
223 unsigned NamedMDNode::getNumElements() const {
224   return (unsigned)getNMDOps(Operands).size();
225 }
226
227 /// getElement - Return specified element.
228 MetadataBase *NamedMDNode::getElement(unsigned i) const {
229   assert(i < getNumElements() && "Invalid element number!");
230   return getNMDOps(Operands)[i];
231 }
232
233 /// addElement - Add metadata element.
234 void NamedMDNode::addElement(MetadataBase *M) {
235   getNMDOps(Operands).push_back(TrackingVH<MetadataBase>(M));
236 }
237
238 /// eraseFromParent - Drop all references and remove the node from parent
239 /// module.
240 void NamedMDNode::eraseFromParent() {
241   getParent()->getNamedMDList().erase(this);
242 }
243
244 /// dropAllReferences - Remove all uses and clear node vector.
245 void NamedMDNode::dropAllReferences() {
246   getNMDOps(Operands).clear();
247 }
248
249
250 //===----------------------------------------------------------------------===//
251 // MetadataContextImpl implementation.
252 //
253 namespace llvm {
254 class MetadataContextImpl {
255 public:
256   typedef std::pair<unsigned, TrackingVH<MDNode> > MDPairTy;
257   typedef SmallVector<MDPairTy, 2> MDMapTy;
258   typedef DenseMap<const Instruction *, MDMapTy> MDStoreTy;
259   friend class BitcodeReader;
260 private:
261
262   /// MetadataStore - Collection of metadata used in this context.
263   MDStoreTy MetadataStore;
264
265   /// MDHandlerNames - Map to hold metadata handler names.
266   StringMap<unsigned> MDHandlerNames;
267
268 public:
269   /// registerMDKind - Register a new metadata kind and return its ID.
270   /// A metadata kind can be registered only once. 
271   unsigned registerMDKind(StringRef Name);
272
273   /// getMDKind - Return metadata kind. If the requested metadata kind
274   /// is not registered then return 0.
275   unsigned getMDKind(StringRef Name) const;
276
277   /// getMD - Get the metadata of given kind attached to an Instruction.
278   /// If the metadata is not found then return 0.
279   MDNode *getMD(unsigned Kind, const Instruction *Inst);
280
281   /// getMDs - Get the metadata attached to an Instruction.
282   void getMDs(const Instruction *Inst,
283               SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs) const;
284
285   /// addMD - Attach the metadata of given kind to an Instruction.
286   void addMD(unsigned Kind, MDNode *Node, Instruction *Inst);
287   
288   /// removeMD - Remove metadata of given kind attached with an instruction.
289   void removeMD(unsigned Kind, Instruction *Inst);
290   
291   /// removeAllMetadata - Remove all metadata attached with an instruction.
292   void removeAllMetadata(Instruction *Inst);
293
294   /// copyMD - If metadata is attached with Instruction In1 then attach
295   /// the same metadata to In2.
296   void copyMD(Instruction *In1, Instruction *In2);
297
298   /// getHandlerNames - Populate client-supplied smallvector using custom
299   /// metadata name and ID.
300   void getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&) const;
301
302   /// ValueIsDeleted - This handler is used to update metadata store
303   /// when a value is deleted.
304   void ValueIsDeleted(const Value *) {}
305   void ValueIsDeleted(Instruction *Inst) {
306     removeAllMetadata(Inst);
307   }
308   void ValueIsRAUWd(Value *V1, Value *V2);
309
310   /// ValueIsCloned - This handler is used to update metadata store
311   /// when In1 is cloned to create In2.
312   void ValueIsCloned(const Instruction *In1, Instruction *In2);
313 };
314 }
315
316 /// registerMDKind - Register a new metadata kind and return its ID.
317 /// A metadata kind can be registered only once. 
318 unsigned MetadataContextImpl::registerMDKind(StringRef Name) {
319   unsigned Count = MDHandlerNames.size();
320   assert(MDHandlerNames.count(Name) == 0 && "Already registered MDKind!");
321   return MDHandlerNames[Name] = Count + 1;
322 }
323
324 /// getMDKind - Return metadata kind. If the requested metadata kind
325 /// is not registered then return 0.
326 unsigned MetadataContextImpl::getMDKind(StringRef Name) const {
327   StringMap<unsigned>::const_iterator I = MDHandlerNames.find(Name);
328   if (I == MDHandlerNames.end())
329     return 0;
330
331   return I->getValue();
332 }
333
334 /// addMD - Attach the metadata of given kind to an Instruction.
335 void MetadataContextImpl::addMD(unsigned MDKind, MDNode *Node, 
336                                 Instruction *Inst) {
337   assert(Node && "Invalid null MDNode");
338   Inst->HasMetadata = true;
339   MDMapTy &Info = MetadataStore[Inst];
340   if (Info.empty()) {
341     Info.push_back(std::make_pair(MDKind, Node));
342     MetadataStore.insert(std::make_pair(Inst, Info));
343     return;
344   }
345
346   // If there is an entry for this MDKind then replace it.
347   for (unsigned i = 0, e = Info.size(); i != e; ++i) {
348     MDPairTy &P = Info[i];
349     if (P.first == MDKind) {
350       Info[i] = std::make_pair(MDKind, Node);
351       return;
352     }
353   }
354
355   // Otherwise add a new entry.
356   Info.push_back(std::make_pair(MDKind, Node));
357 }
358
359 /// removeMD - Remove metadata of given kind attached with an instruction.
360 void MetadataContextImpl::removeMD(unsigned Kind, Instruction *Inst) {
361   MDStoreTy::iterator I = MetadataStore.find(Inst);
362   if (I == MetadataStore.end())
363     return;
364
365   MDMapTy &Info = I->second;
366   for (MDMapTy::iterator MI = Info.begin(), ME = Info.end(); MI != ME; ++MI) {
367     MDPairTy &P = *MI;
368     if (P.first == Kind) {
369       Info.erase(MI);
370       return;
371     }
372   }
373 }
374
375 /// removeAllMetadata - Remove all metadata attached with an instruction.
376 void MetadataContextImpl::removeAllMetadata(Instruction *Inst) {
377   MetadataStore.erase(Inst);
378   Inst->HasMetadata = false;
379 }
380
381 /// copyMD - If metadata is attached with Instruction In1 then attach
382 /// the same metadata to In2.
383 void MetadataContextImpl::copyMD(Instruction *In1, Instruction *In2) {
384   assert(In1 && In2 && "Invalid instruction!");
385   MDMapTy &In1Info = MetadataStore[In1];
386   if (In1Info.empty())
387     return;
388
389   for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
390     addMD(I->first, I->second, In2);
391 }
392
393 /// getMD - Get the metadata of given kind attached to an Instruction.
394 /// If the metadata is not found then return 0.
395 MDNode *MetadataContextImpl::getMD(unsigned MDKind, const Instruction *Inst) {
396   MDMapTy &Info = MetadataStore[Inst];
397   if (Info.empty())
398     return NULL;
399
400   for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I)
401     if (I->first == MDKind)
402       return I->second;
403   return NULL;
404 }
405
406 /// getMDs - Get the metadata attached to an Instruction.
407 void MetadataContextImpl::
408 getMDs(const Instruction *Inst,
409        SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs) const {
410   MDStoreTy::const_iterator I = MetadataStore.find(Inst);
411   if (I == MetadataStore.end())
412     return;
413   MDs.resize(I->second.size());
414   for (MDMapTy::const_iterator MI = I->second.begin(), ME = I->second.end();
415        MI != ME; ++MI)
416     // MD kinds are numbered from 1.
417     MDs[MI->first - 1] = std::make_pair(MI->first, MI->second);
418 }
419
420 /// getHandlerNames - Populate client supplied smallvector using custome
421 /// metadata name and ID.
422 void MetadataContextImpl::
423 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&Names) const {
424   Names.resize(MDHandlerNames.size());
425   for (StringMap<unsigned>::const_iterator I = MDHandlerNames.begin(),
426          E = MDHandlerNames.end(); I != E; ++I) 
427     // MD Handlers are numbered from 1.
428     Names[I->second - 1] = std::make_pair(I->second, I->first());
429 }
430
431 /// ValueIsCloned - This handler is used to update metadata store
432 /// when In1 is cloned to create In2.
433 void MetadataContextImpl::ValueIsCloned(const Instruction *In1, 
434                                         Instruction *In2) {
435   // Find Metadata handles for In1.
436   MDStoreTy::iterator I = MetadataStore.find(In1);
437   assert(I != MetadataStore.end() && "Invalid custom metadata info!");
438
439   // FIXME : Give all metadata handlers a chance to adjust.
440
441   MDMapTy &In1Info = I->second;
442   MDMapTy In2Info;
443   for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
444     addMD(I->first, I->second, In2);
445 }
446
447 /// ValueIsRAUWd - This handler is used when V1's all uses are replaced by
448 /// V2.
449 void MetadataContextImpl::ValueIsRAUWd(Value *V1, Value *V2) {
450   Instruction *I1 = dyn_cast<Instruction>(V1);
451   Instruction *I2 = dyn_cast<Instruction>(V2);
452   if (!I1 || !I2)
453     return;
454
455   // FIXME : Give custom handlers a chance to override this.
456   ValueIsCloned(I1, I2);
457 }
458
459 //===----------------------------------------------------------------------===//
460 // MetadataContext implementation.
461 //
462 MetadataContext::MetadataContext() 
463   : pImpl(new MetadataContextImpl()) { }
464 MetadataContext::~MetadataContext() { delete pImpl; }
465
466 /// isValidName - Return true if Name is a valid custom metadata handler name.
467 bool MetadataContext::isValidName(StringRef MDName) {
468   if (MDName.empty())
469     return false;
470
471   if (!isalpha(MDName[0]))
472     return false;
473
474   for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
475        ++I) {
476     if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
477         return false;
478   }
479   return true;
480 }
481
482 /// registerMDKind - Register a new metadata kind and return its ID.
483 /// A metadata kind can be registered only once. 
484 unsigned MetadataContext::registerMDKind(StringRef Name) {
485   assert(isValidName(Name) && "Invalid custome metadata name!");
486   return pImpl->registerMDKind(Name);
487 }
488
489 /// getMDKind - Return metadata kind. If the requested metadata kind
490 /// is not registered then return 0.
491 unsigned MetadataContext::getMDKind(StringRef Name) const {
492   return pImpl->getMDKind(Name);
493 }
494
495 /// getMD - Get the metadata of given kind attached to an Instruction.
496 /// If the metadata is not found then return 0.
497 MDNode *MetadataContext::getMD(unsigned Kind, const Instruction *Inst) {
498   return pImpl->getMD(Kind, Inst);
499 }
500
501 /// getMDs - Get the metadata attached to an Instruction.
502 void MetadataContext::
503 getMDs(const Instruction *Inst, 
504        SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs) const {
505   return pImpl->getMDs(Inst, MDs);
506 }
507
508 /// addMD - Attach the metadata of given kind to an Instruction.
509 void MetadataContext::addMD(unsigned Kind, MDNode *Node, Instruction *Inst) {
510   pImpl->addMD(Kind, Node, Inst);
511 }
512
513 /// removeMD - Remove metadata of given kind attached with an instruction.
514 void MetadataContext::removeMD(unsigned Kind, Instruction *Inst) {
515   pImpl->removeMD(Kind, Inst);
516 }
517
518 /// removeAllMetadata - Remove all metadata attached with an instruction.
519 void MetadataContext::removeAllMetadata(Instruction *Inst) {
520   pImpl->removeAllMetadata(Inst);
521 }
522
523 /// copyMD - If metadata is attached with Instruction In1 then attach
524 /// the same metadata to In2.
525 void MetadataContext::copyMD(Instruction *In1, Instruction *In2) {
526   pImpl->copyMD(In1, In2);
527 }
528
529 /// getHandlerNames - Populate client supplied smallvector using custome
530 /// metadata name and ID.
531 void MetadataContext::
532 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&N) const {
533   pImpl->getHandlerNames(N);
534 }
535
536 /// ValueIsDeleted - This handler is used to update metadata store
537 /// when a value is deleted.
538 void MetadataContext::ValueIsDeleted(Instruction *Inst) {
539   pImpl->ValueIsDeleted(Inst);
540 }
541 void MetadataContext::ValueIsRAUWd(Value *V1, Value *V2) {
542   pImpl->ValueIsRAUWd(V1, V2);
543 }
544
545 /// ValueIsCloned - This handler is used to update metadata store
546 /// when In1 is cloned to create In2.
547 void MetadataContext::ValueIsCloned(const Instruction *In1, Instruction *In2) {
548   pImpl->ValueIsCloned(In1, In2);
549 }