do not bother reuniquing mdnodes whose operands drop to null. Doing
[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   if (!isNotUniqued()) {
91     LLVMContextImpl *pImpl = getType()->getContext().pImpl;
92     pImpl->MDNodeSet.RemoveNode(this);
93   }
94   delete [] Operands;
95   Operands = NULL;
96 }
97
98 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals,
99                bool isFunctionLocal)
100   : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
101   NumOperands = NumVals;
102   // FIXME: Coallocate the operand list.  These have fixed arity.
103   Operands = new MDNodeElement[NumOperands];
104     
105   for (unsigned i = 0; i != NumVals; ++i) 
106     Operands[i].set(Vals[i], this);
107     
108   if (isFunctionLocal)
109     setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit);
110 }
111
112 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals,
113                     bool isFunctionLocal) {
114   LLVMContextImpl *pImpl = Context.pImpl;
115   FoldingSetNodeID ID;
116   for (unsigned i = 0; i != NumVals; ++i)
117     ID.AddPointer(Vals[i]);
118
119   void *InsertPoint;
120   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
121   if (!N) {
122     // InsertPoint will have been set by the FindNodeOrInsertPos call.
123     N = new MDNode(Context, Vals, NumVals, isFunctionLocal);
124     pImpl->MDNodeSet.InsertNode(N, InsertPoint);
125   }
126   return N;
127 }
128
129 void MDNode::Profile(FoldingSetNodeID &ID) const {
130   for (unsigned i = 0, e = getNumElements(); i != e; ++i)
131     ID.AddPointer(getElement(i));
132   // HASH TABLE COLLISIONS?
133   // DO NOT REINSERT AFTER AN OPERAND DROPS TO NULL!
134 }
135
136
137 /// getElement - Return specified element.
138 Value *MDNode::getElement(unsigned i) const {
139   assert(i < getNumElements() && "Invalid element number!");
140   return Operands[i];
141 }
142
143
144
145 // Replace value from this node's element list.
146 void MDNode::replaceElement(MDNodeElement *Op, Value *To) {
147   Value *From = *Op;
148   
149   if (From == To)
150     return;
151
152   // Update the operand.
153   Op->set(To, this);
154
155   // If this node is already not being uniqued (because one of the operands
156   // already went to null), then there is nothing else to do here.
157   if (isNotUniqued()) return;
158   
159   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
160
161   // Remove "this" from the context map.  FoldingSet doesn't have to reprofile
162   // this node to remove it, so we don't care what state the operands are in.
163   pImpl->MDNodeSet.RemoveNode(this);
164
165   // If we are dropping an argument to null, we choose to not unique the MDNode
166   // anymore.  This commonly occurs during destruction, and uniquing these
167   // brings little reuse.
168   if (To == 0) {
169     setIsNotUniqued();
170     return;
171   }
172   
173   // Now that the node is out of the folding set, get ready to reinsert it.
174   // First, check to see if another node with the same operands already exists
175   // in the set.  If it doesn't exist, this returns the position to insert it.
176   FoldingSetNodeID ID;
177   Profile(ID);
178   void *InsertPoint;
179   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
180
181   if (N) {
182     // FIXME:
183     // If it already exists in the set, we don't reinsert it, we just claim it
184     // isn't uniqued.
185     
186     N->replaceAllUsesWith(this);
187     delete N;
188     N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
189     assert(N == 0 && "shouldn't be in the map now!"); (void)N;
190   }
191
192   // InsertPoint will have been set by the FindNodeOrInsertPos call.
193   pImpl->MDNodeSet.InsertNode(this, InsertPoint);
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 // MetadataContext implementation.
265 //
266
267 #ifndef NDEBUG
268 /// isValidName - Return true if Name is a valid custom metadata handler name.
269 static bool isValidName(StringRef MDName) {
270   if (MDName.empty())
271     return false;
272
273   if (!isalpha(MDName[0]))
274     return false;
275
276   for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
277        ++I) {
278     if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
279         return false;
280   }
281   return true;
282 }
283 #endif
284
285 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
286 unsigned LLVMContext::getMDKindID(StringRef Name) const {
287   assert(isValidName(Name) && "Invalid MDNode name");
288   
289   unsigned &Entry = pImpl->CustomMDKindNames[Name];
290   
291   // If this is new, assign it its ID.
292   if (Entry == 0) Entry = pImpl->CustomMDKindNames.size();
293   return Entry;
294 }
295
296 /// getHandlerNames - Populate client supplied smallvector using custome
297 /// metadata name and ID.
298 void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
299   Names.resize(pImpl->CustomMDKindNames.size()+1);
300   Names[0] = "";
301   for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
302        E = pImpl->CustomMDKindNames.end(); I != E; ++I) 
303     // MD Handlers are numbered from 1.
304     Names[I->second] = I->first();
305 }
306
307 //===----------------------------------------------------------------------===//
308 // Instruction Metadata method implementations.
309 //
310
311 void Instruction::setMetadata(const char *Kind, MDNode *Node) {
312   if (Node == 0 && !hasMetadata()) return;
313   setMetadata(getContext().getMDKindID(Kind), Node);
314 }
315
316 MDNode *Instruction::getMetadataImpl(const char *Kind) const {
317   return getMetadataImpl(getContext().getMDKindID(Kind));
318 }
319
320 /// setMetadata - Set the metadata of of the specified kind to the specified
321 /// node.  This updates/replaces metadata if already present, or removes it if
322 /// Node is null.
323 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
324   if (Node == 0 && !hasMetadata()) return;
325   
326   // Handle the case when we're adding/updating metadata on an instruction.
327   if (Node) {
328     LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
329     assert(!Info.empty() == hasMetadata() && "HasMetadata bit is wonked");
330     if (Info.empty()) {
331       setHasMetadata(true);
332     } else {
333       // Handle replacement of an existing value.
334       for (unsigned i = 0, e = Info.size(); i != e; ++i)
335         if (Info[i].first == KindID) {
336           Info[i].second = Node;
337           return;
338         }
339     }
340     
341     // No replacement, just add it to the list.
342     Info.push_back(std::make_pair(KindID, Node));
343     return;
344   }
345   
346   // Otherwise, we're removing metadata from an instruction.
347   assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
348          "HasMetadata bit out of date!");
349   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
350   
351   // Common case is removing the only entry.
352   if (Info.size() == 1 && Info[0].first == KindID) {
353     getContext().pImpl->MetadataStore.erase(this);
354     setHasMetadata(false);
355     return;
356   }
357   
358   // Handle replacement of an existing value.
359   for (unsigned i = 0, e = Info.size(); i != e; ++i)
360     if (Info[i].first == KindID) {
361       Info[i] = Info.back();
362       Info.pop_back();
363       assert(!Info.empty() && "Removing last entry should be handled above");
364       return;
365     }
366   // Otherwise, removing an entry that doesn't exist on the instruction.
367 }
368
369 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
370   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
371   assert(hasMetadata() && !Info.empty() && "Shouldn't have called this");
372   
373   for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end();
374        I != E; ++I)
375     if (I->first == KindID)
376       return I->second;
377   return 0;
378 }
379
380 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
381                                        MDNode*> > &Result)const {
382   assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
383          "Shouldn't have called this");
384   const LLVMContextImpl::MDMapTy &Info =
385     getContext().pImpl->MetadataStore.find(this)->second;
386   assert(!Info.empty() && "Shouldn't have called this");
387   
388   Result.clear();
389   Result.append(Info.begin(), Info.end());
390   
391   // Sort the resulting array so it is stable.
392   if (Result.size() > 1)
393     array_pod_sort(Result.begin(), Result.end());
394 }
395
396 /// removeAllMetadata - Remove all metadata from this instruction.
397 void Instruction::removeAllMetadata() {
398   assert(hasMetadata() && "Caller should check");
399   getContext().pImpl->MetadataStore.erase(this);
400   setHasMetadata(false);
401 }
402