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