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