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