Derive NamedMDNode from Value.
[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 // MDNodeOperand implementation.
52 //
53
54 // Use CallbackVH to hold MDNode operands.
55 namespace llvm {
56 class MDNodeOperand : public CallbackVH {
57   MDNode *Parent;
58 public:
59   MDNodeOperand(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {}
60   ~MDNodeOperand() {}
61   
62   void set(Value *V) {
63     setValPtr(V);
64   }
65   
66   virtual void deleted();
67   virtual void allUsesReplacedWith(Value *NV);
68 };
69 } // end namespace llvm.
70
71
72 void MDNodeOperand::deleted() {
73   Parent->replaceOperand(this, 0);
74 }
75
76 void MDNodeOperand::allUsesReplacedWith(Value *NV) {
77   Parent->replaceOperand(this, NV);
78 }
79
80
81
82 //===----------------------------------------------------------------------===//
83 // MDNode implementation.
84 //
85
86 /// getOperandPtr - Helper function to get the MDNodeOperand's coallocated on
87 /// the end of the MDNode.
88 static MDNodeOperand *getOperandPtr(MDNode *N, unsigned Op) {
89   assert(Op < N->getNumOperands() && "Invalid operand number");
90   return reinterpret_cast<MDNodeOperand*>(N+1)+Op;
91 }
92
93 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals,
94                bool isFunctionLocal)
95 : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
96   NumOperands = NumVals;
97  
98   if (isFunctionLocal)
99     setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit);
100
101   // Initialize the operand list, which is co-allocated on the end of the node.
102   for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
103        Op != E; ++Op, ++Vals)
104     new (Op) MDNodeOperand(*Vals, this);
105 }
106
107
108 /// ~MDNode - Destroy MDNode.
109 MDNode::~MDNode() {
110   assert((getSubclassDataFromValue() & DestroyFlag) != 0 && 
111          "Not being destroyed through destroy()?");
112   if (!isNotUniqued()) {
113     LLVMContextImpl *pImpl = getType()->getContext().pImpl;
114     pImpl->MDNodeSet.RemoveNode(this);
115   }
116   
117   // Destroy the operands.
118   for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
119        Op != E; ++Op)
120     Op->~MDNodeOperand();
121 }
122
123 // destroy - Delete this node.  Only when there are no uses.
124 void MDNode::destroy() {
125   setValueSubclassData(getSubclassDataFromValue() | DestroyFlag);
126   // Placement delete, the free the memory.
127   this->~MDNode();
128   free(this);
129 }
130
131
132 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals,
133                     bool isFunctionLocal) {
134   LLVMContextImpl *pImpl = Context.pImpl;
135   FoldingSetNodeID ID;
136   for (unsigned i = 0; i != NumVals; ++i)
137     ID.AddPointer(Vals[i]);
138
139   void *InsertPoint;
140   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
141   if (!N) {
142     // Coallocate space for the node and Operands together, then placement new.
143     void *Ptr = malloc(sizeof(MDNode)+NumVals*sizeof(MDNodeOperand));
144     N = new (Ptr) MDNode(Context, Vals, NumVals, isFunctionLocal);
145     
146     // InsertPoint will have been set by the FindNodeOrInsertPos call.
147     pImpl->MDNodeSet.InsertNode(N, InsertPoint);
148   }
149   return N;
150 }
151
152 /// getOperand - Return specified operand.
153 Value *MDNode::getOperand(unsigned i) const {
154   return *getOperandPtr(const_cast<MDNode*>(this), i);
155 }
156
157 void MDNode::Profile(FoldingSetNodeID &ID) const {
158   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
159     ID.AddPointer(getOperand(i));
160 }
161
162
163 // Replace value from this node's operand list.
164 void MDNode::replaceOperand(MDNodeOperand *Op, Value *To) {
165   Value *From = *Op;
166   
167   if (From == To)
168     return;
169
170   // Update the operand.
171   Op->set(To);
172
173   // If this node is already not being uniqued (because one of the operands
174   // already went to null), then there is nothing else to do here.
175   if (isNotUniqued()) return;
176   
177   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
178
179   // Remove "this" from the context map.  FoldingSet doesn't have to reprofile
180   // this node to remove it, so we don't care what state the operands are in.
181   pImpl->MDNodeSet.RemoveNode(this);
182
183   // If we are dropping an argument to null, we choose to not unique the MDNode
184   // anymore.  This commonly occurs during destruction, and uniquing these
185   // brings little reuse.
186   if (To == 0) {
187     setIsNotUniqued();
188     return;
189   }
190   
191   // Now that the node is out of the folding set, get ready to reinsert it.
192   // First, check to see if another node with the same operands already exists
193   // in the set.  If it doesn't exist, this returns the position to insert it.
194   FoldingSetNodeID ID;
195   Profile(ID);
196   void *InsertPoint;
197   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
198
199   if (N) {
200     N->replaceAllUsesWith(this);
201     N->destroy();
202     N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
203     assert(N == 0 && "shouldn't be in the map now!"); (void)N;
204   }
205
206   // InsertPoint will have been set by the FindNodeOrInsertPos call.
207   pImpl->MDNodeSet.InsertNode(this, InsertPoint);
208 }
209
210 //===----------------------------------------------------------------------===//
211 // NamedMDNode implementation.
212 //
213 static SmallVector<WeakVH, 4> &getNMDOps(void *Operands) {
214   return *(SmallVector<WeakVH, 4>*)Operands;
215 }
216
217 NamedMDNode::NamedMDNode(LLVMContext &C, StringRef N,
218                          MDNode *const *MDs, 
219                          unsigned NumMDs, Module *ParentModule)
220   : Value(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
221   setName(N);
222   Operands = new SmallVector<WeakVH, 4>();
223     
224   SmallVector<WeakVH, 4> &Node = getNMDOps(Operands);
225   for (unsigned i = 0; i != NumMDs; ++i)
226     Node.push_back(WeakVH(MDs[i]));
227
228   if (ParentModule) {
229     ParentModule->getNamedMDList().push_back(this);
230     ParentModule->addMDNodeName(N, this);
231   }
232 }
233
234 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
235   assert(NMD && "Invalid source NamedMDNode!");
236   SmallVector<MDNode *, 4> Elems;
237   Elems.reserve(NMD->getNumOperands());
238   
239   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
240     Elems.push_back(NMD->getOperand(i));
241   return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
242                          Elems.data(), Elems.size(), M);
243 }
244
245 NamedMDNode::~NamedMDNode() {
246   dropAllReferences();
247   delete &getNMDOps(Operands);
248 }
249
250 /// getNumOperands - Return number of NamedMDNode operands.
251 unsigned NamedMDNode::getNumOperands() const {
252   return (unsigned)getNMDOps(Operands).size();
253 }
254
255 /// getOperand - Return specified operand.
256 MDNode *NamedMDNode::getOperand(unsigned i) const {
257   assert(i < getNumOperands() && "Invalid Operand number!");
258   return dyn_cast_or_null<MDNode>(getNMDOps(Operands)[i]);
259 }
260
261 /// addOperand - Add metadata Operand.
262 void NamedMDNode::addOperand(MDNode *M) {
263   getNMDOps(Operands).push_back(WeakVH(M));
264 }
265
266 /// eraseFromParent - Drop all references and remove the node from parent
267 /// module.
268 void NamedMDNode::eraseFromParent() {
269   getParent()->getMDSymbolTable().remove(getName());
270   getParent()->getNamedMDList().erase(this);
271 }
272
273 /// dropAllReferences - Remove all uses and clear node vector.
274 void NamedMDNode::dropAllReferences() {
275   getNMDOps(Operands).clear();
276 }
277
278 /// setName - Set the name of this named metadata.
279 void NamedMDNode::setName(StringRef N) {
280   if (!N.empty())
281     Name = N.str();
282 }
283
284 /// getName - Return a constant reference to this named metadata's name.
285 StringRef NamedMDNode::getName() const {
286   return StringRef(Name);
287 }
288
289 //===----------------------------------------------------------------------===//
290 // LLVMContext MDKind naming implementation.
291 //
292
293 #ifndef NDEBUG
294 /// isValidName - Return true if Name is a valid custom metadata handler name.
295 static bool isValidName(StringRef MDName) {
296   if (MDName.empty())
297     return false;
298
299   if (!isalpha(MDName[0]))
300     return false;
301
302   for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
303        ++I) {
304     if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
305         return false;
306   }
307   return true;
308 }
309 #endif
310
311 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
312 unsigned LLVMContext::getMDKindID(StringRef Name) const {
313   assert(isValidName(Name) && "Invalid MDNode name");
314   
315   unsigned &Entry = pImpl->CustomMDKindNames[Name];
316   
317   // If this is new, assign it its ID.
318   if (Entry == 0) Entry = pImpl->CustomMDKindNames.size();
319   return Entry;
320 }
321
322 /// getHandlerNames - Populate client supplied smallvector using custome
323 /// metadata name and ID.
324 void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
325   Names.resize(pImpl->CustomMDKindNames.size()+1);
326   Names[0] = "";
327   for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
328        E = pImpl->CustomMDKindNames.end(); I != E; ++I) 
329     // MD Handlers are numbered from 1.
330     Names[I->second] = I->first();
331 }
332
333 //===----------------------------------------------------------------------===//
334 // Instruction Metadata method implementations.
335 //
336
337 void Instruction::setMetadata(const char *Kind, MDNode *Node) {
338   if (Node == 0 && !hasMetadata()) return;
339   setMetadata(getContext().getMDKindID(Kind), Node);
340 }
341
342 MDNode *Instruction::getMetadataImpl(const char *Kind) const {
343   return getMetadataImpl(getContext().getMDKindID(Kind));
344 }
345
346 /// setMetadata - Set the metadata of of the specified kind to the specified
347 /// node.  This updates/replaces metadata if already present, or removes it if
348 /// Node is null.
349 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
350   if (Node == 0 && !hasMetadata()) return;
351   
352   // Handle the case when we're adding/updating metadata on an instruction.
353   if (Node) {
354     LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
355     assert(!Info.empty() == hasMetadata() && "HasMetadata bit is wonked");
356     if (Info.empty()) {
357       setHasMetadata(true);
358     } else {
359       // Handle replacement of an existing value.
360       for (unsigned i = 0, e = Info.size(); i != e; ++i)
361         if (Info[i].first == KindID) {
362           Info[i].second = Node;
363           return;
364         }
365     }
366     
367     // No replacement, just add it to the list.
368     Info.push_back(std::make_pair(KindID, Node));
369     return;
370   }
371   
372   // Otherwise, we're removing metadata from an instruction.
373   assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
374          "HasMetadata bit out of date!");
375   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
376   
377   // Common case is removing the only entry.
378   if (Info.size() == 1 && Info[0].first == KindID) {
379     getContext().pImpl->MetadataStore.erase(this);
380     setHasMetadata(false);
381     return;
382   }
383   
384   // Handle replacement of an existing value.
385   for (unsigned i = 0, e = Info.size(); i != e; ++i)
386     if (Info[i].first == KindID) {
387       Info[i] = Info.back();
388       Info.pop_back();
389       assert(!Info.empty() && "Removing last entry should be handled above");
390       return;
391     }
392   // Otherwise, removing an entry that doesn't exist on the instruction.
393 }
394
395 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
396   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
397   assert(hasMetadata() && !Info.empty() && "Shouldn't have called this");
398   
399   for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end();
400        I != E; ++I)
401     if (I->first == KindID)
402       return I->second;
403   return 0;
404 }
405
406 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
407                                        MDNode*> > &Result)const {
408   assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
409          "Shouldn't have called this");
410   const LLVMContextImpl::MDMapTy &Info =
411     getContext().pImpl->MetadataStore.find(this)->second;
412   assert(!Info.empty() && "Shouldn't have called this");
413   
414   Result.clear();
415   Result.append(Info.begin(), Info.end());
416   
417   // Sort the resulting array so it is stable.
418   if (Result.size() > 1)
419     array_pod_sort(Result.begin(), Result.end());
420 }
421
422 /// removeAllMetadata - Remove all metadata from this instruction.
423 void Instruction::removeAllMetadata() {
424   assert(hasMetadata() && "Caller should check");
425   getContext().pImpl->MetadataStore.erase(this);
426   setHasMetadata(false);
427 }
428