rename "elements" of metadata to "operands". "Elements" are
[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<TrackingVH<MetadataBase>, 4> &getNMDOps(void *Operands) {
214   return *(SmallVector<TrackingVH<MetadataBase>, 4>*)Operands;
215 }
216
217 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
218                          MetadataBase *const *MDs, 
219                          unsigned NumMDs, Module *ParentModule)
220   : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
221   setName(N);
222     
223   Operands = new SmallVector<TrackingVH<MetadataBase>, 4>();
224     
225   SmallVector<TrackingVH<MetadataBase>, 4> &Node = getNMDOps(Operands);
226   for (unsigned i = 0; i != NumMDs; ++i)
227     Node.push_back(TrackingVH<MetadataBase>(MDs[i]));
228
229   if (ParentModule)
230     ParentModule->getNamedMDList().push_back(this);
231 }
232
233 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
234   assert(NMD && "Invalid source NamedMDNode!");
235   SmallVector<MetadataBase *, 4> Elems;
236   Elems.reserve(NMD->getNumOperands());
237   
238   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
239     Elems.push_back(NMD->getOperand(i));
240   return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
241                          Elems.data(), Elems.size(), M);
242 }
243
244 NamedMDNode::~NamedMDNode() {
245   dropAllReferences();
246   delete &getNMDOps(Operands);
247 }
248
249 /// getNumOperands - Return number of NamedMDNode operands.
250 unsigned NamedMDNode::getNumOperands() const {
251   return (unsigned)getNMDOps(Operands).size();
252 }
253
254 /// getOperand - Return specified operand.
255 MetadataBase *NamedMDNode::getOperand(unsigned i) const {
256   assert(i < getNumOperands() && "Invalid Operand number!");
257   return getNMDOps(Operands)[i];
258 }
259
260 /// addOperand - Add metadata Operand.
261 void NamedMDNode::addOperand(MetadataBase *M) {
262   getNMDOps(Operands).push_back(TrackingVH<MetadataBase>(M));
263 }
264
265 /// eraseFromParent - Drop all references and remove the node from parent
266 /// module.
267 void NamedMDNode::eraseFromParent() {
268   getParent()->getNamedMDList().erase(this);
269 }
270
271 /// dropAllReferences - Remove all uses and clear node vector.
272 void NamedMDNode::dropAllReferences() {
273   getNMDOps(Operands).clear();
274 }
275
276
277 //===----------------------------------------------------------------------===//
278 // LLVMContext MDKind naming implementation.
279 //
280
281 #ifndef NDEBUG
282 /// isValidName - Return true if Name is a valid custom metadata handler name.
283 static bool isValidName(StringRef MDName) {
284   if (MDName.empty())
285     return false;
286
287   if (!isalpha(MDName[0]))
288     return false;
289
290   for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
291        ++I) {
292     if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
293         return false;
294   }
295   return true;
296 }
297 #endif
298
299 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
300 unsigned LLVMContext::getMDKindID(StringRef Name) const {
301   assert(isValidName(Name) && "Invalid MDNode name");
302   
303   unsigned &Entry = pImpl->CustomMDKindNames[Name];
304   
305   // If this is new, assign it its ID.
306   if (Entry == 0) Entry = pImpl->CustomMDKindNames.size();
307   return Entry;
308 }
309
310 /// getHandlerNames - Populate client supplied smallvector using custome
311 /// metadata name and ID.
312 void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
313   Names.resize(pImpl->CustomMDKindNames.size()+1);
314   Names[0] = "";
315   for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
316        E = pImpl->CustomMDKindNames.end(); I != E; ++I) 
317     // MD Handlers are numbered from 1.
318     Names[I->second] = I->first();
319 }
320
321 //===----------------------------------------------------------------------===//
322 // Instruction Metadata method implementations.
323 //
324
325 void Instruction::setMetadata(const char *Kind, MDNode *Node) {
326   if (Node == 0 && !hasMetadata()) return;
327   setMetadata(getContext().getMDKindID(Kind), Node);
328 }
329
330 MDNode *Instruction::getMetadataImpl(const char *Kind) const {
331   return getMetadataImpl(getContext().getMDKindID(Kind));
332 }
333
334 /// setMetadata - Set the metadata of of the specified kind to the specified
335 /// node.  This updates/replaces metadata if already present, or removes it if
336 /// Node is null.
337 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
338   if (Node == 0 && !hasMetadata()) return;
339   
340   // Handle the case when we're adding/updating metadata on an instruction.
341   if (Node) {
342     LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
343     assert(!Info.empty() == hasMetadata() && "HasMetadata bit is wonked");
344     if (Info.empty()) {
345       setHasMetadata(true);
346     } else {
347       // Handle replacement of an existing value.
348       for (unsigned i = 0, e = Info.size(); i != e; ++i)
349         if (Info[i].first == KindID) {
350           Info[i].second = Node;
351           return;
352         }
353     }
354     
355     // No replacement, just add it to the list.
356     Info.push_back(std::make_pair(KindID, Node));
357     return;
358   }
359   
360   // Otherwise, we're removing metadata from an instruction.
361   assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
362          "HasMetadata bit out of date!");
363   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
364   
365   // Common case is removing the only entry.
366   if (Info.size() == 1 && Info[0].first == KindID) {
367     getContext().pImpl->MetadataStore.erase(this);
368     setHasMetadata(false);
369     return;
370   }
371   
372   // Handle replacement of an existing value.
373   for (unsigned i = 0, e = Info.size(); i != e; ++i)
374     if (Info[i].first == KindID) {
375       Info[i] = Info.back();
376       Info.pop_back();
377       assert(!Info.empty() && "Removing last entry should be handled above");
378       return;
379     }
380   // Otherwise, removing an entry that doesn't exist on the instruction.
381 }
382
383 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
384   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
385   assert(hasMetadata() && !Info.empty() && "Shouldn't have called this");
386   
387   for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end();
388        I != E; ++I)
389     if (I->first == KindID)
390       return I->second;
391   return 0;
392 }
393
394 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
395                                        MDNode*> > &Result)const {
396   assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
397          "Shouldn't have called this");
398   const LLVMContextImpl::MDMapTy &Info =
399     getContext().pImpl->MetadataStore.find(this)->second;
400   assert(!Info.empty() && "Shouldn't have called this");
401   
402   Result.clear();
403   Result.append(Info.begin(), Info.end());
404   
405   // Sort the resulting array so it is stable.
406   if (Result.size() > 1)
407     array_pod_sort(Result.begin(), Result.end());
408 }
409
410 /// removeAllMetadata - Remove all metadata from this instruction.
411 void Instruction::removeAllMetadata() {
412   assert(hasMetadata() && "Caller should check");
413   getContext().pImpl->MetadataStore.erase(this);
414   setHasMetadata(false);
415 }
416