the only call to this function (from clang) has been removed, zap it.
[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 // MDString implementation.
27 //
28
29 MDString::MDString(LLVMContext &C, StringRef S)
30   : MetadataBase(Type::getMetadataTy(C), Value::MDStringVal), Str(S) {}
31
32 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
33   LLVMContextImpl *pImpl = Context.pImpl;
34   StringMapEntry<MDString *> &Entry = 
35     pImpl->MDStringCache.GetOrCreateValue(Str);
36   MDString *&S = Entry.getValue();
37   if (!S) S = new MDString(Context, Entry.getKey());
38   return S;
39 }
40
41 MDString *MDString::get(LLVMContext &Context, const char *Str) {
42   LLVMContextImpl *pImpl = Context.pImpl;
43   StringMapEntry<MDString *> &Entry = 
44     pImpl->MDStringCache.GetOrCreateValue(Str ? StringRef(Str) : StringRef());
45   MDString *&S = Entry.getValue();
46   if (!S) S = new MDString(Context, Entry.getKey());
47   return S;
48 }
49
50 //===----------------------------------------------------------------------===//
51 // MDNodeElement implementation.
52 //
53
54 // Use CallbackVH to hold MDNode elements.
55 namespace llvm {
56 class MDNodeElement : public CallbackVH {
57   MDNode *Parent;
58 public:
59   MDNodeElement() {}
60   MDNodeElement(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {}
61   ~MDNodeElement() {}
62   
63   void set(Value *V, MDNode *P) {
64     setValPtr(V);
65     Parent = P;
66   }
67   
68   virtual void deleted();
69   virtual void allUsesReplacedWith(Value *NV);
70 };
71 } // end namespace llvm.
72
73
74 void MDNodeElement::deleted() {
75   Parent->replaceElement(this, 0);
76 }
77
78 void MDNodeElement::allUsesReplacedWith(Value *NV) {
79   Parent->replaceElement(this, NV);
80 }
81
82
83
84 //===----------------------------------------------------------------------===//
85 // MDNode implementation.
86 //
87
88 /// ~MDNode - Destroy MDNode.
89 MDNode::~MDNode() {
90   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
91   pImpl->MDNodeSet.RemoveNode(this);
92   delete [] Operands;
93   Operands = NULL;
94 }
95
96 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals,
97                bool isFunctionLocal)
98   : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
99   NumOperands = NumVals;
100   Operands = new MDNodeElement[NumOperands];
101     
102   for (unsigned i = 0; i != NumVals; ++i) 
103     Operands[i].set(Vals[i], this);
104     
105   if (isFunctionLocal)
106     setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit);
107 }
108
109 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals,
110                     bool isFunctionLocal) {
111   LLVMContextImpl *pImpl = Context.pImpl;
112   FoldingSetNodeID ID;
113   for (unsigned i = 0; i != NumVals; ++i)
114     ID.AddPointer(Vals[i]);
115
116   void *InsertPoint;
117   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
118   if (!N) {
119     // InsertPoint will have been set by the FindNodeOrInsertPos call.
120     N = new MDNode(Context, Vals, NumVals, isFunctionLocal);
121     pImpl->MDNodeSet.InsertNode(N, InsertPoint);
122   }
123   return N;
124 }
125
126 void MDNode::Profile(FoldingSetNodeID &ID) const {
127   for (unsigned i = 0, e = getNumElements(); i != e; ++i)
128     ID.AddPointer(getElement(i));
129   // HASH TABLE COLLISIONS?
130   // DO NOT REINSERT AFTER AN OPERAND DROPS TO NULL!
131 }
132
133
134 /// getElement - Return specified element.
135 Value *MDNode::getElement(unsigned i) const {
136   assert(i < getNumElements() && "Invalid element number!");
137   return Operands[i];
138 }
139
140
141
142 // Replace value from this node's element list.
143 void MDNode::replaceElement(MDNodeElement *Op, Value *To) {
144   Value *From = *Op;
145   
146   if (From == To)
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   // Update the operand.
156   Op->set(To, this);
157
158   // Insert updated "this" into the context's folding node set.
159   // If a node with same element list already exist then before inserting 
160   // updated "this" into the folding node set, replace all uses of existing 
161   // node with updated "this" node.
162   FoldingSetNodeID ID;
163   Profile(ID);
164   void *InsertPoint;
165   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
166
167   if (N) {
168     N->replaceAllUsesWith(this);
169     delete N;
170     N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
171     assert(N == 0 && "shouldn't be in the map now!"); (void)N;
172   }
173
174   // InsertPoint will have been set by the FindNodeOrInsertPos call.
175   pImpl->MDNodeSet.InsertNode(this, InsertPoint);
176 }
177
178 //===----------------------------------------------------------------------===//
179 // NamedMDNode implementation.
180 //
181 static SmallVector<TrackingVH<MetadataBase>, 4> &getNMDOps(void *Operands) {
182   return *(SmallVector<TrackingVH<MetadataBase>, 4>*)Operands;
183 }
184
185 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
186                          MetadataBase *const *MDs, 
187                          unsigned NumMDs, Module *ParentModule)
188   : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
189   setName(N);
190     
191   Operands = new SmallVector<TrackingVH<MetadataBase>, 4>();
192     
193   SmallVector<TrackingVH<MetadataBase>, 4> &Node = getNMDOps(Operands);
194   for (unsigned i = 0; i != NumMDs; ++i)
195     Node.push_back(TrackingVH<MetadataBase>(MDs[i]));
196
197   if (ParentModule)
198     ParentModule->getNamedMDList().push_back(this);
199 }
200
201 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
202   assert(NMD && "Invalid source NamedMDNode!");
203   SmallVector<MetadataBase *, 4> Elems;
204   Elems.reserve(NMD->getNumElements());
205   
206   for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
207     Elems.push_back(NMD->getElement(i));
208   return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
209                          Elems.data(), Elems.size(), M);
210 }
211
212 NamedMDNode::~NamedMDNode() {
213   dropAllReferences();
214   delete &getNMDOps(Operands);
215 }
216
217 /// getNumElements - Return number of NamedMDNode elements.
218 unsigned NamedMDNode::getNumElements() const {
219   return (unsigned)getNMDOps(Operands).size();
220 }
221
222 /// getElement - Return specified element.
223 MetadataBase *NamedMDNode::getElement(unsigned i) const {
224   assert(i < getNumElements() && "Invalid element number!");
225   return getNMDOps(Operands)[i];
226 }
227
228 /// addElement - Add metadata element.
229 void NamedMDNode::addElement(MetadataBase *M) {
230   getNMDOps(Operands).push_back(TrackingVH<MetadataBase>(M));
231 }
232
233 /// eraseFromParent - Drop all references and remove the node from parent
234 /// module.
235 void NamedMDNode::eraseFromParent() {
236   getParent()->getNamedMDList().erase(this);
237 }
238
239 /// dropAllReferences - Remove all uses and clear node vector.
240 void NamedMDNode::dropAllReferences() {
241   getNMDOps(Operands).clear();
242 }
243
244
245 //===----------------------------------------------------------------------===//
246 // MetadataContextImpl implementation.
247 //
248 namespace llvm {
249 class MetadataContextImpl {
250 public:
251   typedef std::pair<unsigned, TrackingVH<MDNode> > MDPairTy;
252   typedef SmallVector<MDPairTy, 2> MDMapTy;
253   typedef DenseMap<const Instruction *, MDMapTy> MDStoreTy;
254   friend class BitcodeReader;
255 private:
256
257   /// MetadataStore - Collection of metadata used in this context.
258   MDStoreTy MetadataStore;
259
260   /// MDHandlerNames - Map to hold metadata handler names.
261   StringMap<unsigned> MDHandlerNames;
262
263 public:
264   // Name <-> ID mapping methods.
265   unsigned getMDKindID(StringRef Name);
266   void getMDKindNames(SmallVectorImpl<StringRef> &) const;
267   
268   
269   // Instruction metadata methods.
270   MDNode *getMetadata(const Instruction *Inst, unsigned Kind);
271   void getAllMetadata(const Instruction *Inst,
272                       SmallVectorImpl<std::pair<unsigned, MDNode*> > &MDs)const;
273
274   void setMetadata(Instruction *Inst, unsigned Kind, MDNode *Node);
275
276   /// removeAllMetadata - Remove all metadata attached to an instruction.
277   void removeAllMetadata(Instruction *Inst);
278 };
279 }
280
281 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
282 unsigned MetadataContextImpl::getMDKindID(StringRef Name) {
283   unsigned &Entry = MDHandlerNames[Name];
284
285   // If this is new, assign it its ID.
286   if (Entry == 0) Entry = MDHandlerNames.size();
287   return Entry;
288 }
289
290 /// getHandlerNames - Populate client supplied smallvector using custome
291 /// metadata name and ID.
292 void MetadataContextImpl::
293 getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
294   Names.resize(MDHandlerNames.size()+1);
295   Names[0] = "";
296   for (StringMap<unsigned>::const_iterator I = MDHandlerNames.begin(),
297        E = MDHandlerNames.end(); I != E; ++I) 
298     // MD Handlers are numbered from 1.
299     Names[I->second] = I->first();
300 }
301
302
303 /// getMetadata - Get the metadata of given kind attached to an Instruction.
304 /// If the metadata is not found then return 0.
305 MDNode *MetadataContextImpl::
306 getMetadata(const Instruction *Inst, unsigned MDKind) {
307   MDMapTy &Info = MetadataStore[Inst];
308   assert(Inst->hasMetadata() && !Info.empty() && "Shouldn't have called this");
309   
310   for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I)
311     if (I->first == MDKind)
312       return I->second;
313   return 0;
314 }
315
316 /// getAllMetadata - Get all of the metadata attached to an Instruction.
317 void MetadataContextImpl::
318 getAllMetadata(const Instruction *Inst,
319                SmallVectorImpl<std::pair<unsigned, MDNode*> > &Result) const {
320   assert(Inst->hasMetadata() && MetadataStore.find(Inst) != MetadataStore.end()
321          && "Shouldn't have called this");
322   const MDMapTy &Info = MetadataStore.find(Inst)->second;
323   assert(!Info.empty() && "Shouldn't have called this");
324
325   Result.clear();
326   Result.append(Info.begin(), Info.end());
327   
328   // Sort the resulting array so it is stable.
329   if (Result.size() > 1)
330     array_pod_sort(Result.begin(), Result.end());
331 }
332
333
334 void MetadataContextImpl::setMetadata(Instruction *Inst, unsigned Kind,
335                                       MDNode *Node) {
336   // Handle the case when we're adding/updating metadata on an instruction.
337   if (Node) {
338     MDMapTy &Info = MetadataStore[Inst];
339     assert(!Info.empty() == Inst->hasMetadata() && "HasMetadata bit is wonked");
340     if (Info.empty()) {
341       Inst->setHasMetadata(true);
342     } else {
343       // Handle replacement of an existing value.
344       for (unsigned i = 0, e = Info.size(); i != e; ++i)
345         if (Info[i].first == Kind) {
346           Info[i].second = Node;
347           return;
348         }
349     }
350     
351     // No replacement, just add it to the list.
352     Info.push_back(std::make_pair(Kind, Node));
353     return;
354   }
355   
356   // Otherwise, we're removing metadata from an instruction.
357   assert(Inst->hasMetadata() && MetadataStore.count(Inst) &&
358          "HasMetadata bit out of date!");
359   MDMapTy &Info = MetadataStore[Inst];
360
361   // Common case is removing the only entry.
362   if (Info.size() == 1 && Info[0].first == Kind) {
363     MetadataStore.erase(Inst);
364     Inst->setHasMetadata(false);
365     return;
366   }
367   
368   // Handle replacement of an existing value.
369   for (unsigned i = 0, e = Info.size(); i != e; ++i)
370     if (Info[i].first == Kind) {
371       Info[i] = Info.back();
372       Info.pop_back();
373       assert(!Info.empty() && "Removing last entry should be handled above");
374       return;
375     }
376   // Otherwise, removing an entry that doesn't exist on the instruction.
377 }
378
379 /// removeAllMetadata - Remove all metadata attached with an instruction.
380 void MetadataContextImpl::removeAllMetadata(Instruction *Inst) {
381   MetadataStore.erase(Inst);
382   Inst->setHasMetadata(false);
383 }
384
385
386 //===----------------------------------------------------------------------===//
387 // MetadataContext implementation.
388 //
389 MetadataContext::MetadataContext() : pImpl(new MetadataContextImpl()) { }
390 MetadataContext::~MetadataContext() { delete pImpl; }
391
392 /// isValidName - Return true if Name is a valid custom metadata handler name.
393 bool MetadataContext::isValidName(StringRef MDName) {
394   if (MDName.empty())
395     return false;
396
397   if (!isalpha(MDName[0]))
398     return false;
399
400   for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
401        ++I) {
402     if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
403         return false;
404   }
405   return true;
406 }
407
408 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
409 unsigned MetadataContext::getMDKindID(StringRef Name) const {
410   return pImpl->getMDKindID(Name);
411 }
412
413 /// getHandlerNames - Populate client supplied smallvector using custome
414 /// metadata name and ID.
415 void MetadataContext::getMDKindNames(SmallVectorImpl<StringRef> &N) const {
416   pImpl->getMDKindNames(N);
417 }
418
419 //===----------------------------------------------------------------------===//
420 // Instruction Metadata method implementations.
421 //
422
423 void Instruction::setMetadata(const char *Kind, MDNode *Node) {
424   if (Node == 0 && !hasMetadata()) return;
425   setMetadata(getContext().getMetadata().getMDKindID(Kind), Node);
426 }
427
428 MDNode *Instruction::getMetadataImpl(const char *Kind) const {
429   return getMetadataImpl(getContext().getMetadata().getMDKindID(Kind));
430 }
431
432 /// setMetadata - Set the metadata of of the specified kind to the specified
433 /// node.  This updates/replaces metadata if already present, or removes it if
434 /// Node is null.
435 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
436   if (Node == 0 && !hasMetadata()) return;
437   
438   getContext().getMetadata().pImpl->setMetadata(this, KindID, Node);
439 }
440
441 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
442   return getContext().getMetadata().pImpl->getMetadata(this, KindID);
443 }
444
445 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
446                                        MDNode*> > &Result)const {
447   getContext().getMetadata().pImpl->getAllMetadata(this, Result);
448 }
449
450 /// removeAllMetadata - Remove all metadata from this instruction.
451 void Instruction::removeAllMetadata() {
452   assert(hasMetadata() && "Caller should check");
453   getContext().getMetadata().pImpl->removeAllMetadata(this);
454 }
455