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