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