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