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