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