Parse custom metadata attached with an instruction.
[oota-llvm.git] / include / llvm / Metadata.h
1 //===-- llvm/Metadata.h - Metadata definitions ------------------*- C++ -*-===//
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 /// @file
11 /// This file contains the declarations for metadata subclasses.
12 /// They represent the different flavors of metadata that live in LLVM.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_MDNODE_H
17 #define LLVM_MDNODE_H
18
19 #include "llvm/User.h"
20 #include "llvm/Type.h"
21 #include "llvm/OperandTraits.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/ilist_node.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/ValueHandle.h"
30
31 namespace llvm {
32 class Constant;
33 class Instruction;
34 class LLVMContext;
35
36 //===----------------------------------------------------------------------===//
37 // MetadataBase  - A base class for MDNode, MDString and NamedMDNode.
38 class MetadataBase : public User {
39 private:
40   /// ReservedSpace - The number of operands actually allocated.  NumOperands is
41   /// the number actually in use.
42   unsigned ReservedSpace;
43
44 protected:
45   MetadataBase(const Type *Ty, unsigned scid)
46     : User(Ty, scid, NULL, 0), ReservedSpace(0) {}
47
48   void resizeOperands(unsigned NumOps);
49 public:
50   /// isNullValue - Return true if this is the value that would be returned by
51   /// getNullValue.  This always returns false because getNullValue will never
52   /// produce metadata.
53   virtual bool isNullValue() const {
54     return false;
55   }
56
57   /// Methods for support type inquiry through isa, cast, and dyn_cast:
58   static inline bool classof(const MetadataBase *) { return true; }
59   static bool classof(const Value *V) {
60     return V->getValueID() == MDStringVal || V->getValueID() == MDNodeVal
61       || V->getValueID() == NamedMDNodeVal;
62   }
63 };
64
65 //===----------------------------------------------------------------------===//
66 /// MDString - a single uniqued string.
67 /// These are used to efficiently contain a byte sequence for metadata.
68 /// MDString is always unnamd.
69 class MDString : public MetadataBase {
70   MDString(const MDString &);            // DO NOT IMPLEMENT
71   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
72   unsigned getNumOperands();             // DO NOT IMPLEMENT
73
74   StringRef Str;
75 protected:
76   explicit MDString(LLVMContext &C, const char *begin, unsigned l)
77     : MetadataBase(Type::getMetadataTy(C), Value::MDStringVal), Str(begin, l) {}
78
79 public:
80   // Do not allocate any space for operands.
81   void *operator new(size_t s) {
82     return User::operator new(s, 0);
83   }
84   static MDString *get(LLVMContext &Context, const StringRef &Str);
85   
86   StringRef getString() const { return Str; }
87
88   unsigned length() const { return Str.size(); }
89
90   /// begin() - Pointer to the first byte of the string.
91   ///
92   const char *begin() const { return Str.begin(); }
93
94   /// end() - Pointer to one byte past the end of the string.
95   ///
96   const char *end() const { return Str.end(); }
97
98   /// Methods for support type inquiry through isa, cast, and dyn_cast:
99   static inline bool classof(const MDString *) { return true; }
100   static bool classof(const Value *V) {
101     return V->getValueID() == MDStringVal;
102   }
103 };
104
105 //===----------------------------------------------------------------------===//
106 /// MDNode - a tuple of other values.
107 /// These contain a list of the values that represent the metadata. 
108 /// MDNode is always unnamed.
109 class MDNode : public MetadataBase, public FoldingSetNode {
110   MDNode(const MDNode &);                // DO NOT IMPLEMENT
111   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
112   // getNumOperands - Make this only available for private uses.
113   unsigned getNumOperands() { return User::getNumOperands();  }
114
115   friend class ElementVH;
116   // Use CallbackVH to hold MDNOde elements.
117   struct ElementVH : public CallbackVH {
118     MDNode *Parent;
119     ElementVH(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {}
120     ~ElementVH() {}
121
122     virtual void deleted() {
123       Parent->replaceElement(this->operator Value*(), 0);
124     }
125
126     virtual void allUsesReplacedWith(Value *NV) {
127       Parent->replaceElement(this->operator Value*(), NV);
128     }
129   };
130   // Replace each instance of F from the element list of this node with T.
131   void replaceElement(Value *F, Value *T);
132
133   SmallVector<ElementVH, 4> Node;
134
135 protected:
136   explicit MDNode(LLVMContext &C, Value*const* Vals, unsigned NumVals);
137 public:
138   // Do not allocate any space for operands.
139   void *operator new(size_t s) {
140     return User::operator new(s, 0);
141   }
142   // Constructors and destructors.
143   static MDNode *get(LLVMContext &Context, 
144                      Value* const* Vals, unsigned NumVals);
145
146   /// dropAllReferences - Remove all uses and clear node vector.
147   void dropAllReferences();
148
149   /// ~MDNode - Destroy MDNode.
150   ~MDNode();
151   
152   /// getElement - Return specified element.
153   Value *getElement(unsigned i) const {
154     assert (getNumElements() > i && "Invalid element number!");
155     return Node[i];
156   }
157
158   /// getNumElements - Return number of MDNode elements.
159   unsigned getNumElements() const {
160     return Node.size();
161   }
162
163   // Element access
164   typedef SmallVectorImpl<ElementVH>::const_iterator const_elem_iterator;
165   typedef SmallVectorImpl<ElementVH>::iterator elem_iterator;
166   /// elem_empty - Return true if MDNode is empty.
167   bool elem_empty() const                { return Node.empty(); }
168   const_elem_iterator elem_begin() const { return Node.begin(); }
169   const_elem_iterator elem_end() const   { return Node.end();   }
170   elem_iterator elem_begin()             { return Node.begin(); }
171   elem_iterator elem_end()               { return Node.end();   }
172
173   /// isNullValue - Return true if this is the value that would be returned by
174   /// getNullValue.  This always returns false because getNullValue will never
175   /// produce metadata.
176   virtual bool isNullValue() const {
177     return false;
178   }
179
180   /// Profile - calculate a unique identifier for this MDNode to collapse
181   /// duplicates
182   void Profile(FoldingSetNodeID &ID) const;
183
184   virtual void replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
185     llvm_unreachable("This should never be called because MDNodes have no ops");
186   }
187
188   /// Methods for support type inquiry through isa, cast, and dyn_cast:
189   static inline bool classof(const MDNode *) { return true; }
190   static bool classof(const Value *V) {
191     return V->getValueID() == MDNodeVal;
192   }
193 };
194
195 //===----------------------------------------------------------------------===//
196 /// WeakMetadataVH - a weak value handle for metadata.
197 class WeakMetadataVH : public WeakVH {
198 public:
199   WeakMetadataVH() : WeakVH() {}
200   WeakMetadataVH(MetadataBase *M) : WeakVH(M) {}
201   WeakMetadataVH(const WeakMetadataVH &RHS) : WeakVH(RHS) {}
202   
203   operator Value*() const {
204     llvm_unreachable("WeakMetadataVH only handles Metadata");
205   }
206
207   operator MetadataBase*() const {
208    return dyn_cast_or_null<MetadataBase>(getValPtr());
209   }
210 };
211
212 //===----------------------------------------------------------------------===//
213 /// NamedMDNode - a tuple of other metadata. 
214 /// NamedMDNode is always named. All NamedMDNode element has a type of metadata.
215 template<typename ValueSubClass, typename ItemParentClass>
216   class SymbolTableListTraits;
217
218 class NamedMDNode : public MetadataBase, public ilist_node<NamedMDNode> {
219   friend class SymbolTableListTraits<NamedMDNode, Module>;
220   friend class LLVMContextImpl;
221
222   NamedMDNode(const NamedMDNode &);      // DO NOT IMPLEMENT
223   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
224   // getNumOperands - Make this only available for private uses.
225   unsigned getNumOperands() { return User::getNumOperands();  }
226
227   Module *Parent;
228   SmallVector<WeakMetadataVH, 4> Node;
229   typedef SmallVectorImpl<WeakMetadataVH>::iterator elem_iterator;
230
231 protected:
232   explicit NamedMDNode(LLVMContext &C, const Twine &N, MetadataBase*const* Vals, 
233                        unsigned NumVals, Module *M = 0);
234 public:
235   // Do not allocate any space for operands.
236   void *operator new(size_t s) {
237     return User::operator new(s, 0);
238   }
239   static NamedMDNode *Create(LLVMContext &C, const Twine &N, 
240                              MetadataBase*const*MDs, 
241                              unsigned NumMDs, Module *M = 0) {
242     return new NamedMDNode(C, N, MDs, NumMDs, M);
243   }
244
245   static NamedMDNode *Create(const NamedMDNode *NMD, Module *M = 0);
246
247   /// eraseFromParent - Drop all references and remove the node from parent
248   /// module.
249   void eraseFromParent();
250
251   /// dropAllReferences - Remove all uses and clear node vector.
252   void dropAllReferences();
253
254   /// ~NamedMDNode - Destroy NamedMDNode.
255   ~NamedMDNode();
256
257   /// getParent - Get the module that holds this named metadata collection.
258   inline Module *getParent() { return Parent; }
259   inline const Module *getParent() const { return Parent; }
260   void setParent(Module *M) { Parent = M; }
261
262   /// getElement - Return specified element.
263   MetadataBase *getElement(unsigned i) const {
264     assert (getNumElements() > i && "Invalid element number!");
265     return Node[i];
266   }
267
268   /// getNumElements - Return number of NamedMDNode elements.
269   unsigned getNumElements() const {
270     return Node.size();
271   }
272
273   /// addElement - Add metadata element.
274   void addElement(MetadataBase *M) {
275     resizeOperands(0);
276     OperandList[NumOperands++] = M;
277     Node.push_back(WeakMetadataVH(M));
278   }
279
280   typedef SmallVectorImpl<WeakMetadataVH>::const_iterator const_elem_iterator;
281   bool elem_empty() const                { return Node.empty(); }
282   const_elem_iterator elem_begin() const { return Node.begin(); }
283   const_elem_iterator elem_end() const   { return Node.end();   }
284   elem_iterator elem_begin()             { return Node.begin(); }
285   elem_iterator elem_end()               { return Node.end();   }
286
287   /// isNullValue - Return true if this is the value that would be returned by
288   /// getNullValue.  This always returns false because getNullValue will never
289   /// produce metadata.
290   virtual bool isNullValue() const {
291     return false;
292   }
293
294   virtual void replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
295     llvm_unreachable(
296                 "This should never be called because NamedMDNodes have no ops");
297   }
298
299   /// Methods for support type inquiry through isa, cast, and dyn_cast:
300   static inline bool classof(const NamedMDNode *) { return true; }
301   static bool classof(const Value *V) {
302     return V->getValueID() == NamedMDNodeVal;
303   }
304 };
305
306 //===----------------------------------------------------------------------===//
307 /// MetadataContext -
308 /// MetadataContext handles uniquing and assignment of IDs for custom metadata
309 /// types. Custom metadata handler names do not contain spaces. And the name
310 /// must start with an alphabet. The regular expression used to check name
311 /// is [a-zA-Z$._][a-zA-Z$._0-9]*
312 class MetadataContext {
313 public:
314   typedef std::pair<unsigned, WeakVH> MDPairTy;
315   typedef SmallVector<MDPairTy, 2> MDMapTy;
316   typedef DenseMap<const Instruction *, MDMapTy> MDStoreTy;
317   friend class BitcodeReader;
318 private:
319
320   /// MetadataStore - Collection of metadata used in this context.
321   MDStoreTy MetadataStore;
322
323   /// MDHandlerNames - Map to hold metadata handler names.
324   StringMap<unsigned> MDHandlerNames;
325
326 public:
327   /// RegisterMDKind - Register a new metadata kind and return its ID.
328   /// A metadata kind can be registered only once. 
329   unsigned RegisterMDKind(const char *Name);
330
331   /// getMDKind - Return metadata kind. If the requested metadata kind
332   /// is not registered then return 0.
333   unsigned getMDKind(const char *Name);
334
335   /// validName - Return true if Name is a valid custom metadata handler name.
336   bool validName(const char *Name);
337
338   /// getMD - Get the metadata of given kind attached with an Instruction.
339   /// If the metadata is not found then return 0.
340   MDNode *getMD(unsigned Kind, const Instruction *Inst);
341
342   /// getMDs - Get the metadata attached with an Instruction.
343   const MDMapTy *getMDs(const Instruction *Inst);
344
345   /// setMD - Attach the metadata of given kind with an Instruction.
346   void setMD(unsigned Kind, MDNode *Node, Instruction *Inst);
347   
348   /// getHandlerNames - Get handler names. This is used by bitcode
349   /// writer.
350   const StringMap<unsigned> *getHandlerNames();
351
352   /// ValueIsDeleted - This handler is used to update metadata store
353   /// when a value is deleted.
354   void ValueIsDeleted(const Value *V) {}
355   void ValueIsDeleted(const Instruction *Inst);
356
357   /// ValueIsCloned - This handler is used to update metadata store
358   /// when In1 is cloned to create In2.
359   void ValueIsCloned(const Instruction *In1, Instruction *In2);
360 };
361
362 } // end llvm namespace
363
364 #endif