Make NamedMDNode not be a subclass of Value, and simplify the interface
[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 "llvm/ADT/SmallString.h"
22 #include "SymbolTableListTraitsImpl.h"
23 #include "llvm/Support/ValueHandle.h"
24 using namespace llvm;
25
26 //===----------------------------------------------------------------------===//
27 // MDString implementation.
28 //
29
30 MDString::MDString(LLVMContext &C, StringRef S)
31   : Value(Type::getMetadataTy(C), Value::MDStringVal), Str(S) {}
32
33 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
34   LLVMContextImpl *pImpl = Context.pImpl;
35   StringMapEntry<MDString *> &Entry =
36     pImpl->MDStringCache.GetOrCreateValue(Str);
37   MDString *&S = Entry.getValue();
38   if (!S) S = new MDString(Context, Entry.getKey());
39   return S;
40 }
41
42 //===----------------------------------------------------------------------===//
43 // MDNodeOperand implementation.
44 //
45
46 // Use CallbackVH to hold MDNode operands.
47 namespace llvm {
48 class MDNodeOperand : public CallbackVH {
49   MDNode *Parent;
50 public:
51   MDNodeOperand(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {}
52   ~MDNodeOperand() {}
53
54   void set(Value *V) {
55     setValPtr(V);
56   }
57
58   virtual void deleted();
59   virtual void allUsesReplacedWith(Value *NV);
60 };
61 } // end namespace llvm.
62
63
64 void MDNodeOperand::deleted() {
65   Parent->replaceOperand(this, 0);
66 }
67
68 void MDNodeOperand::allUsesReplacedWith(Value *NV) {
69   Parent->replaceOperand(this, NV);
70 }
71
72
73
74 //===----------------------------------------------------------------------===//
75 // MDNode implementation.
76 //
77
78 /// getOperandPtr - Helper function to get the MDNodeOperand's coallocated on
79 /// the end of the MDNode.
80 static MDNodeOperand *getOperandPtr(MDNode *N, unsigned Op) {
81   // Use <= instead of < to permit a one-past-the-end address.
82   assert(Op <= N->getNumOperands() && "Invalid operand number");
83   return reinterpret_cast<MDNodeOperand*>(N+1)+Op;
84 }
85
86 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals,
87                bool isFunctionLocal)
88 : Value(Type::getMetadataTy(C), Value::MDNodeVal) {
89   NumOperands = NumVals;
90
91   if (isFunctionLocal)
92     setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit);
93
94   // Initialize the operand list, which is co-allocated on the end of the node.
95   for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
96        Op != E; ++Op, ++Vals)
97     new (Op) MDNodeOperand(*Vals, this);
98 }
99
100
101 /// ~MDNode - Destroy MDNode.
102 MDNode::~MDNode() {
103   assert((getSubclassDataFromValue() & DestroyFlag) != 0 &&
104          "Not being destroyed through destroy()?");
105   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
106   if (isNotUniqued()) {
107     pImpl->NonUniquedMDNodes.erase(this);
108   } else {
109     pImpl->MDNodeSet.RemoveNode(this);
110   }
111
112   // Destroy the operands.
113   for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
114        Op != E; ++Op)
115     Op->~MDNodeOperand();
116 }
117
118 static const Function *getFunctionForValue(Value *V) {
119   if (!V) return NULL;
120   if (Instruction *I = dyn_cast<Instruction>(V)) {
121     BasicBlock *BB = I->getParent();
122     return BB ? BB->getParent() : 0;
123   }
124   if (Argument *A = dyn_cast<Argument>(V))
125     return A->getParent();
126   if (BasicBlock *BB = dyn_cast<BasicBlock>(V))
127     return BB->getParent();
128   if (MDNode *MD = dyn_cast<MDNode>(V))
129     return MD->getFunction();
130   return NULL;
131 }
132
133 #ifndef NDEBUG
134 static const Function *assertLocalFunction(const MDNode *N) {
135   if (!N->isFunctionLocal()) return 0;
136
137   // FIXME: This does not handle cyclic function local metadata.
138   const Function *F = 0, *NewF = 0;
139   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
140     if (Value *V = N->getOperand(i)) {
141       if (MDNode *MD = dyn_cast<MDNode>(V))
142         NewF = assertLocalFunction(MD);
143       else
144         NewF = getFunctionForValue(V);
145     }
146     if (F == 0)
147       F = NewF;
148     else 
149       assert((NewF == 0 || F == NewF) &&"inconsistent function-local metadata");
150   }
151   return F;
152 }
153 #endif
154
155 // getFunction - If this metadata is function-local and recursively has a
156 // function-local operand, return the first such operand's parent function.
157 // Otherwise, return null. getFunction() should not be used for performance-
158 // critical code because it recursively visits all the MDNode's operands.  
159 const Function *MDNode::getFunction() const {
160 #ifndef NDEBUG
161   return assertLocalFunction(this);
162 #endif
163   if (!isFunctionLocal()) return NULL;
164   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
165     if (const Function *F = getFunctionForValue(getOperand(i)))
166       return F;
167   return NULL;
168 }
169
170 // destroy - Delete this node.  Only when there are no uses.
171 void MDNode::destroy() {
172   setValueSubclassData(getSubclassDataFromValue() | DestroyFlag);
173   // Placement delete, the free the memory.
174   this->~MDNode();
175   free(this);
176 }
177
178 /// isFunctionLocalValue - Return true if this is a value that would require a
179 /// function-local MDNode.
180 static bool isFunctionLocalValue(Value *V) {
181   return isa<Instruction>(V) || isa<Argument>(V) || isa<BasicBlock>(V) ||
182          (isa<MDNode>(V) && cast<MDNode>(V)->isFunctionLocal());
183 }
184
185 MDNode *MDNode::getMDNode(LLVMContext &Context, Value *const *Vals,
186                           unsigned NumVals, FunctionLocalness FL,
187                           bool Insert) {
188   LLVMContextImpl *pImpl = Context.pImpl;
189   bool isFunctionLocal = false;
190   switch (FL) {
191   case FL_Unknown:
192     for (unsigned i = 0; i != NumVals; ++i) {
193       Value *V = Vals[i];
194       if (!V) continue;
195       if (isFunctionLocalValue(V)) {
196         isFunctionLocal = true;
197         break;
198       }
199     }
200     break;
201   case FL_No:
202     isFunctionLocal = false;
203     break;
204   case FL_Yes:
205     isFunctionLocal = true;
206     break;
207   }
208
209   FoldingSetNodeID ID;
210   for (unsigned i = 0; i != NumVals; ++i)
211     ID.AddPointer(Vals[i]);
212   ID.AddBoolean(isFunctionLocal);
213
214   void *InsertPoint;
215   MDNode *N = NULL;
216   
217   if ((N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint)))
218     return N;
219     
220   if (!Insert)
221     return NULL;
222     
223   // Coallocate space for the node and Operands together, then placement new.
224   void *Ptr = malloc(sizeof(MDNode)+NumVals*sizeof(MDNodeOperand));
225   N = new (Ptr) MDNode(Context, Vals, NumVals, isFunctionLocal);
226
227   // InsertPoint will have been set by the FindNodeOrInsertPos call.
228   pImpl->MDNodeSet.InsertNode(N, InsertPoint);
229
230   return N;
231 }
232
233 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals) {
234   return getMDNode(Context, Vals, NumVals, FL_Unknown);
235 }
236
237 MDNode *MDNode::getWhenValsUnresolved(LLVMContext &Context, Value *const *Vals,
238                                       unsigned NumVals, bool isFunctionLocal) {
239   return getMDNode(Context, Vals, NumVals, isFunctionLocal ? FL_Yes : FL_No);
240 }
241
242 MDNode *MDNode::getIfExists(LLVMContext &Context, Value *const *Vals,
243                             unsigned NumVals) {
244   return getMDNode(Context, Vals, NumVals, FL_Unknown, false);
245 }
246
247 /// getOperand - Return specified operand.
248 Value *MDNode::getOperand(unsigned i) const {
249   return *getOperandPtr(const_cast<MDNode*>(this), i);
250 }
251
252 void MDNode::Profile(FoldingSetNodeID &ID) const {
253   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
254     ID.AddPointer(getOperand(i));
255   ID.AddBoolean(isFunctionLocal());
256 }
257
258 void MDNode::setIsNotUniqued() {
259   setValueSubclassData(getSubclassDataFromValue() | NotUniquedBit);
260   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
261   pImpl->NonUniquedMDNodes.insert(this);
262 }
263
264 // Replace value from this node's operand list.
265 void MDNode::replaceOperand(MDNodeOperand *Op, Value *To) {
266   Value *From = *Op;
267
268   // If is possible that someone did GV->RAUW(inst), replacing a global variable
269   // with an instruction or some other function-local object.  If this is a
270   // non-function-local MDNode, it can't point to a function-local object.
271   // Handle this case by implicitly dropping the MDNode reference to null.
272   // Likewise if the MDNode is function-local but for a different function.
273   if (To && isFunctionLocalValue(To)) {
274     if (!isFunctionLocal())
275       To = 0;
276     else {
277       const Function *F = getFunction();
278       const Function *FV = getFunctionForValue(To);
279       // Metadata can be function-local without having an associated function.
280       // So only consider functions to have changed if non-null.
281       if (F && FV && F != FV)
282         To = 0;
283     }
284   }
285   
286   if (From == To)
287     return;
288
289   // Update the operand.
290   Op->set(To);
291
292   // If this node is already not being uniqued (because one of the operands
293   // already went to null), then there is nothing else to do here.
294   if (isNotUniqued()) return;
295
296   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
297
298   // Remove "this" from the context map.  FoldingSet doesn't have to reprofile
299   // this node to remove it, so we don't care what state the operands are in.
300   pImpl->MDNodeSet.RemoveNode(this);
301
302   // If we are dropping an argument to null, we choose to not unique the MDNode
303   // anymore.  This commonly occurs during destruction, and uniquing these
304   // brings little reuse.
305   if (To == 0) {
306     setIsNotUniqued();
307     return;
308   }
309
310   // Now that the node is out of the folding set, get ready to reinsert it.
311   // First, check to see if another node with the same operands already exists
312   // in the set.  If it doesn't exist, this returns the position to insert it.
313   FoldingSetNodeID ID;
314   Profile(ID);
315   void *InsertPoint;
316   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
317
318   if (N) {
319     N->replaceAllUsesWith(this);
320     N->destroy();
321     N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
322     assert(N == 0 && "shouldn't be in the map now!"); (void)N;
323   }
324
325   // InsertPoint will have been set by the FindNodeOrInsertPos call.
326   pImpl->MDNodeSet.InsertNode(this, InsertPoint);
327 }
328
329 //===----------------------------------------------------------------------===//
330 // NamedMDNode implementation.
331 //
332
333 static SmallVector<TrackingVH<MDNode>, 4> &getNMDOps(void *Operands) {
334   return *(SmallVector<TrackingVH<MDNode>, 4>*)Operands;
335 }
336
337 NamedMDNode::NamedMDNode(const Twine &N)
338   : Name(N.str()), Parent(0),
339     Operands(new SmallVector<TrackingVH<MDNode>, 4>()) {
340 }
341
342 NamedMDNode::~NamedMDNode() {
343   dropAllReferences();
344   delete &getNMDOps(Operands);
345 }
346
347 /// getNumOperands - Return number of NamedMDNode operands.
348 unsigned NamedMDNode::getNumOperands() const {
349   return (unsigned)getNMDOps(Operands).size();
350 }
351
352 /// getOperand - Return specified operand.
353 MDNode *NamedMDNode::getOperand(unsigned i) const {
354   assert(i < getNumOperands() && "Invalid Operand number!");
355   return dyn_cast<MDNode>(&*getNMDOps(Operands)[i]);
356 }
357
358 /// addOperand - Add metadata Operand.
359 void NamedMDNode::addOperand(MDNode *M) {
360   getNMDOps(Operands).push_back(TrackingVH<MDNode>(M));
361 }
362
363 /// eraseFromParent - Drop all references and remove the node from parent
364 /// module.
365 void NamedMDNode::eraseFromParent() {
366   getParent()->eraseNamedMetadata(this);
367 }
368
369 /// dropAllReferences - Remove all uses and clear node vector.
370 void NamedMDNode::dropAllReferences() {
371   getNMDOps(Operands).clear();
372 }
373
374 /// getName - Return a constant reference to this named metadata's name.
375 StringRef NamedMDNode::getName() const {
376   return StringRef(Name);
377 }
378
379 //===----------------------------------------------------------------------===//
380 // Instruction Metadata method implementations.
381 //
382
383 void Instruction::setMetadata(const char *Kind, MDNode *Node) {
384   if (Node == 0 && !hasMetadata()) return;
385   setMetadata(getContext().getMDKindID(Kind), Node);
386 }
387
388 MDNode *Instruction::getMetadataImpl(const char *Kind) const {
389   return getMetadataImpl(getContext().getMDKindID(Kind));
390 }
391
392 /// setMetadata - Set the metadata of of the specified kind to the specified
393 /// node.  This updates/replaces metadata if already present, or removes it if
394 /// Node is null.
395 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
396   if (Node == 0 && !hasMetadata()) return;
397
398   // Handle 'dbg' as a special case since it is not stored in the hash table.
399   if (KindID == LLVMContext::MD_dbg) {
400     DbgLoc = DebugLoc::getFromDILocation(Node);
401     return;
402   }
403   
404   // Handle the case when we're adding/updating metadata on an instruction.
405   if (Node) {
406     LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
407     assert(!Info.empty() == hasMetadataHashEntry() &&
408            "HasMetadata bit is wonked");
409     if (Info.empty()) {
410       setHasMetadataHashEntry(true);
411     } else {
412       // Handle replacement of an existing value.
413       for (unsigned i = 0, e = Info.size(); i != e; ++i)
414         if (Info[i].first == KindID) {
415           Info[i].second = Node;
416           return;
417         }
418     }
419
420     // No replacement, just add it to the list.
421     Info.push_back(std::make_pair(KindID, Node));
422     return;
423   }
424
425   // Otherwise, we're removing metadata from an instruction.
426   assert(hasMetadataHashEntry() &&
427          getContext().pImpl->MetadataStore.count(this) &&
428          "HasMetadata bit out of date!");
429   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
430
431   // Common case is removing the only entry.
432   if (Info.size() == 1 && Info[0].first == KindID) {
433     getContext().pImpl->MetadataStore.erase(this);
434     setHasMetadataHashEntry(false);
435     return;
436   }
437
438   // Handle removal of an existing value.
439   for (unsigned i = 0, e = Info.size(); i != e; ++i)
440     if (Info[i].first == KindID) {
441       Info[i] = Info.back();
442       Info.pop_back();
443       assert(!Info.empty() && "Removing last entry should be handled above");
444       return;
445     }
446   // Otherwise, removing an entry that doesn't exist on the instruction.
447 }
448
449 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
450   // Handle 'dbg' as a special case since it is not stored in the hash table.
451   if (KindID == LLVMContext::MD_dbg)
452     return DbgLoc.getAsMDNode(getContext());
453   
454   if (!hasMetadataHashEntry()) return 0;
455   
456   LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
457   assert(!Info.empty() && "bit out of sync with hash table");
458
459   for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end();
460        I != E; ++I)
461     if (I->first == KindID)
462       return I->second;
463   return 0;
464 }
465
466 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
467                                        MDNode*> > &Result) const {
468   Result.clear();
469   
470   // Handle 'dbg' as a special case since it is not stored in the hash table.
471   if (!DbgLoc.isUnknown()) {
472     Result.push_back(std::make_pair((unsigned)LLVMContext::MD_dbg,
473                                     DbgLoc.getAsMDNode(getContext())));
474     if (!hasMetadataHashEntry()) return;
475   }
476   
477   assert(hasMetadataHashEntry() &&
478          getContext().pImpl->MetadataStore.count(this) &&
479          "Shouldn't have called this");
480   const LLVMContextImpl::MDMapTy &Info =
481     getContext().pImpl->MetadataStore.find(this)->second;
482   assert(!Info.empty() && "Shouldn't have called this");
483
484   Result.append(Info.begin(), Info.end());
485
486   // Sort the resulting array so it is stable.
487   if (Result.size() > 1)
488     array_pod_sort(Result.begin(), Result.end());
489 }
490
491 void Instruction::
492 getAllMetadataOtherThanDebugLocImpl(SmallVectorImpl<std::pair<unsigned,
493                                     MDNode*> > &Result) const {
494   Result.clear();
495   assert(hasMetadataHashEntry() &&
496          getContext().pImpl->MetadataStore.count(this) &&
497          "Shouldn't have called this");
498   const LLVMContextImpl::MDMapTy &Info =
499   getContext().pImpl->MetadataStore.find(this)->second;
500   assert(!Info.empty() && "Shouldn't have called this");
501   
502   Result.append(Info.begin(), Info.end());
503   
504   // Sort the resulting array so it is stable.
505   if (Result.size() > 1)
506     array_pod_sort(Result.begin(), Result.end());
507 }
508
509
510 /// clearMetadataHashEntries - Clear all hashtable-based metadata from
511 /// this instruction.
512 void Instruction::clearMetadataHashEntries() {
513   assert(hasMetadataHashEntry() && "Caller should check");
514   getContext().pImpl->MetadataStore.erase(this);
515   setHasMetadataHashEntry(false);
516 }
517