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