Do not use StringRef in DebugInfo interface.
[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 "LLVMContextImpl.h"
15 #include "llvm/Metadata.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 "SymbolTableListTraitsImpl.h"
22 using namespace llvm;
23
24 //===----------------------------------------------------------------------===//
25 // MetadataBase implementation.
26 //
27
28 //===----------------------------------------------------------------------===//
29 // MDString implementation.
30 //
31 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
32   LLVMContextImpl *pImpl = Context.pImpl;
33   StringMapEntry<MDString *> &Entry = 
34     pImpl->MDStringCache.GetOrCreateValue(Str);
35   MDString *&S = Entry.getValue();
36   if (S) return S;
37   
38   return S = 
39     new MDString(Context, Entry.getKey());
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) return S;
48   
49   return S = 
50     new MDString(Context, Entry.getKey());
51 }
52
53 //===----------------------------------------------------------------------===//
54 // MDNode implementation.
55 //
56 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals)
57   : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
58   NodeSize = NumVals;
59   Node = new ElementVH[NodeSize];
60   ElementVH *Ptr = Node;
61   for (unsigned i = 0; i != NumVals; ++i) 
62     *Ptr++ = ElementVH(Vals[i], this);
63 }
64
65 void MDNode::Profile(FoldingSetNodeID &ID) const {
66   for (unsigned i = 0, e = getNumElements(); i != e; ++i)
67     ID.AddPointer(getElement(i));
68 }
69
70 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals) {
71   LLVMContextImpl *pImpl = Context.pImpl;
72   FoldingSetNodeID ID;
73   for (unsigned i = 0; i != NumVals; ++i)
74     ID.AddPointer(Vals[i]);
75
76   void *InsertPoint;
77   MDNode *N;
78   {
79     N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
80   }  
81   if (N) return N;
82   
83   N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
84   if (!N) {
85     // InsertPoint will have been set by the FindNodeOrInsertPos call.
86     N = new MDNode(Context, Vals, NumVals);
87     pImpl->MDNodeSet.InsertNode(N, InsertPoint);
88   }
89
90   return N;
91 }
92
93 /// ~MDNode - Destroy MDNode.
94 MDNode::~MDNode() {
95   {
96     LLVMContextImpl *pImpl = getType()->getContext().pImpl;
97     pImpl->MDNodeSet.RemoveNode(this);
98   }
99   delete [] Node;
100   Node = NULL;
101 }
102
103 // Replace value from this node's element list.
104 void MDNode::replaceElement(Value *From, Value *To) {
105   if (From == To || !getType())
106     return;
107   LLVMContext &Context = getType()->getContext();
108   LLVMContextImpl *pImpl = Context.pImpl;
109
110   // Find value. This is a linear search, do something if it consumes 
111   // lot of time. It is possible that to have multiple instances of
112   // From in this MDNode's element list.
113   SmallVector<unsigned, 4> Indexes;
114   unsigned Index = 0;
115   for (unsigned i = 0, e = getNumElements(); i != e; ++i, ++Index) {
116     Value *V = getElement(i);
117     if (V && V == From) 
118       Indexes.push_back(Index);
119   }
120
121   if (Indexes.empty())
122     return;
123
124   // Remove "this" from the context map. 
125   pImpl->MDNodeSet.RemoveNode(this);
126
127   // Replace From element(s) in place.
128   for (SmallVector<unsigned, 4>::iterator I = Indexes.begin(), E = Indexes.end(); 
129        I != E; ++I) {
130     unsigned Index = *I;
131     Node[Index] = ElementVH(To, this);
132   }
133
134   // Insert updated "this" into the context's folding node set.
135   // If a node with same element list already exist then before inserting 
136   // updated "this" into the folding node set, replace all uses of existing 
137   // node with updated "this" node.
138   FoldingSetNodeID ID;
139   Profile(ID);
140   void *InsertPoint;
141   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
142
143   if (N) {
144     N->replaceAllUsesWith(this);
145     delete N;
146     N = 0;
147   }
148
149   N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
150   if (!N) {
151     // InsertPoint will have been set by the FindNodeOrInsertPos call.
152     N = this;
153     pImpl->MDNodeSet.InsertNode(N, InsertPoint);
154   }
155 }
156
157 //===----------------------------------------------------------------------===//
158 // NamedMDNode implementation.
159 //
160 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
161                          MetadataBase *const *MDs, 
162                          unsigned NumMDs, Module *ParentModule)
163   : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
164   setName(N);
165
166   for (unsigned i = 0; i != NumMDs; ++i)
167     Node.push_back(TrackingVH<MetadataBase>(MDs[i]));
168
169   if (ParentModule)
170     ParentModule->getNamedMDList().push_back(this);
171 }
172
173 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
174   assert(NMD && "Invalid source NamedMDNode!");
175   SmallVector<MetadataBase *, 4> Elems;
176   for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
177     Elems.push_back(NMD->getElement(i));
178   return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
179                          Elems.data(), Elems.size(), M);
180 }
181
182 /// eraseFromParent - Drop all references and remove the node from parent
183 /// module.
184 void NamedMDNode::eraseFromParent() {
185   getParent()->getNamedMDList().erase(this);
186 }
187
188 /// dropAllReferences - Remove all uses and clear node vector.
189 void NamedMDNode::dropAllReferences() {
190   Node.clear();
191 }
192
193 NamedMDNode::~NamedMDNode() {
194   dropAllReferences();
195 }
196
197 //===----------------------------------------------------------------------===//
198 // MetadataContextImpl implementation.
199 //
200 namespace llvm {
201 class MetadataContextImpl {
202 public:
203   typedef std::pair<unsigned, TrackingVH<MDNode> > MDPairTy;
204   typedef SmallVector<MDPairTy, 2> MDMapTy;
205   typedef DenseMap<const Instruction *, MDMapTy> MDStoreTy;
206   friend class BitcodeReader;
207 private:
208
209   /// MetadataStore - Collection of metadata used in this context.
210   MDStoreTy MetadataStore;
211
212   /// MDHandlerNames - Map to hold metadata handler names.
213   StringMap<unsigned> MDHandlerNames;
214
215 public:
216   /// registerMDKind - Register a new metadata kind and return its ID.
217   /// A metadata kind can be registered only once. 
218   unsigned registerMDKind(StringRef Name);
219
220   /// getMDKind - Return metadata kind. If the requested metadata kind
221   /// is not registered then return 0.
222   unsigned getMDKind(StringRef Name) const;
223
224   /// getMD - Get the metadata of given kind attached to an Instruction.
225   /// If the metadata is not found then return 0.
226   MDNode *getMD(unsigned Kind, const Instruction *Inst);
227
228   /// getMDs - Get the metadata attached to an Instruction.
229   void getMDs(const Instruction *Inst, SmallVectorImpl<MDPairTy> &MDs) const;
230
231   /// addMD - Attach the metadata of given kind to an Instruction.
232   void addMD(unsigned Kind, MDNode *Node, Instruction *Inst);
233   
234   /// removeMD - Remove metadata of given kind attached with an instuction.
235   void removeMD(unsigned Kind, Instruction *Inst);
236   
237   /// removeAllMetadata - Remove all metadata attached with an instruction.
238   void removeAllMetadata(Instruction *Inst);
239
240   /// copyMD - If metadata is attached with Instruction In1 then attach
241   /// the same metadata to In2.
242   void copyMD(Instruction *In1, Instruction *In2);
243
244   /// getHandlerNames - Populate client supplied smallvector using custome
245   /// metadata name and ID.
246   void getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&) const;
247
248   /// ValueIsDeleted - This handler is used to update metadata store
249   /// when a value is deleted.
250   void ValueIsDeleted(const Value *) {}
251   void ValueIsDeleted(Instruction *Inst) {
252     removeAllMetadata(Inst);
253   }
254   void ValueIsRAUWd(Value *V1, Value *V2);
255
256   /// ValueIsCloned - This handler is used to update metadata store
257   /// when In1 is cloned to create In2.
258   void ValueIsCloned(const Instruction *In1, Instruction *In2);
259 };
260 }
261
262 /// registerMDKind - Register a new metadata kind and return its ID.
263 /// A metadata kind can be registered only once. 
264 unsigned MetadataContextImpl::registerMDKind(StringRef Name) {
265   unsigned Count = MDHandlerNames.size();
266   assert(MDHandlerNames.count(Name) == 0 && "Already registered MDKind!");
267   return MDHandlerNames[Name] = Count + 1;
268 }
269
270 /// getMDKind - Return metadata kind. If the requested metadata kind
271 /// is not registered then return 0.
272 unsigned MetadataContextImpl::getMDKind(StringRef Name) const {
273   StringMap<unsigned>::const_iterator I = MDHandlerNames.find(Name);
274   if (I == MDHandlerNames.end())
275     return 0;
276
277   return I->getValue();
278 }
279
280 /// addMD - Attach the metadata of given kind to an Instruction.
281 void MetadataContextImpl::addMD(unsigned MDKind, MDNode *Node, 
282                                 Instruction *Inst) {
283   assert(Node && "Invalid null MDNode");
284   Inst->HasMetadata = true;
285   MDMapTy &Info = MetadataStore[Inst];
286   if (Info.empty()) {
287     Info.push_back(std::make_pair(MDKind, Node));
288     MetadataStore.insert(std::make_pair(Inst, Info));
289     return;
290   }
291
292   // If there is an entry for this MDKind then replace it.
293   for (unsigned i = 0, e = Info.size(); i != e; ++i) {
294     MDPairTy &P = Info[i];
295     if (P.first == MDKind) {
296       Info[i] = std::make_pair(MDKind, Node);
297       return;
298     }
299   }
300
301   // Otherwise add a new entry.
302   Info.push_back(std::make_pair(MDKind, Node));
303 }
304
305 /// removeMD - Remove metadata of given kind attached with an instuction.
306 void MetadataContextImpl::removeMD(unsigned Kind, Instruction *Inst) {
307   MDStoreTy::iterator I = MetadataStore.find(Inst);
308   if (I == MetadataStore.end())
309     return;
310
311   MDMapTy &Info = I->second;
312   for (MDMapTy::iterator MI = Info.begin(), ME = Info.end(); MI != ME; ++MI) {
313     MDPairTy &P = *MI;
314     if (P.first == Kind) {
315       Info.erase(MI);
316       return;
317     }
318   }
319 }
320   
321 /// removeAllMetadata - Remove all metadata attached with an instruction.
322 void MetadataContextImpl::removeAllMetadata(Instruction *Inst) {
323   MetadataStore.erase(Inst);
324   Inst->HasMetadata = false;
325 }
326
327 /// copyMD - If metadata is attached with Instruction In1 then attach
328 /// the same metadata to In2.
329 void MetadataContextImpl::copyMD(Instruction *In1, Instruction *In2) {
330   assert(In1 && In2 && "Invalid instruction!");
331   MDMapTy &In1Info = MetadataStore[In1];
332   if (In1Info.empty())
333     return;
334
335   for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
336     addMD(I->first, I->second, In2);
337 }
338
339 /// getMD - Get the metadata of given kind attached to an Instruction.
340 /// If the metadata is not found then return 0.
341 MDNode *MetadataContextImpl::getMD(unsigned MDKind, const Instruction *Inst) {
342   MDMapTy &Info = MetadataStore[Inst];
343   if (Info.empty())
344     return NULL;
345
346   for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I)
347     if (I->first == MDKind)
348       return I->second;
349   return NULL;
350 }
351
352 /// getMDs - Get the metadata attached to an Instruction.
353 void MetadataContextImpl::
354 getMDs(const Instruction *Inst, SmallVectorImpl<MDPairTy> &MDs) const {
355   MDStoreTy::const_iterator I = MetadataStore.find(Inst);
356   if (I == MetadataStore.end())
357     return;
358   MDs.resize(I->second.size());
359   for (MDMapTy::const_iterator MI = I->second.begin(), ME = I->second.end();
360        MI != ME; ++MI)
361     // MD kinds are numbered from 1.
362     MDs[MI->first - 1] = std::make_pair(MI->first, MI->second);
363 }
364
365 /// getHandlerNames - Populate client supplied smallvector using custome
366 /// metadata name and ID.
367 void MetadataContextImpl::
368 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&Names) const {
369   Names.resize(MDHandlerNames.size());
370   for (StringMap<unsigned>::const_iterator I = MDHandlerNames.begin(),
371          E = MDHandlerNames.end(); I != E; ++I) 
372     // MD Handlers are numbered from 1.
373     Names[I->second - 1] = std::make_pair(I->second, I->first());
374 }
375
376 /// ValueIsCloned - This handler is used to update metadata store
377 /// when In1 is cloned to create In2.
378 void MetadataContextImpl::ValueIsCloned(const Instruction *In1, 
379                                         Instruction *In2) {
380   // Find Metadata handles for In1.
381   MDStoreTy::iterator I = MetadataStore.find(In1);
382   assert(I != MetadataStore.end() && "Invalid custom metadata info!");
383
384   // FIXME : Give all metadata handlers a chance to adjust.
385
386   MDMapTy &In1Info = I->second;
387   MDMapTy In2Info;
388   for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
389     addMD(I->first, I->second, In2);
390 }
391
392 /// ValueIsRAUWd - This handler is used when V1's all uses are replaced by
393 /// V2.
394 void MetadataContextImpl::ValueIsRAUWd(Value *V1, Value *V2) {
395   Instruction *I1 = dyn_cast<Instruction>(V1);
396   Instruction *I2 = dyn_cast<Instruction>(V2);
397   if (!I1 || !I2)
398     return;
399
400   // FIXME : Give custom handlers a chance to override this.
401   ValueIsCloned(I1, I2);
402 }
403
404 //===----------------------------------------------------------------------===//
405 // MetadataContext implementation.
406 //
407 MetadataContext::MetadataContext() 
408   : pImpl(new MetadataContextImpl()) { }
409 MetadataContext::~MetadataContext() { delete pImpl; }
410
411 /// isValidName - Return true if Name is a valid custom metadata handler name.
412 bool MetadataContext::isValidName(StringRef MDName) {
413   if (MDName.empty())
414     return false;
415
416   if (!isalpha(MDName[0]))
417     return false;
418
419   for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
420        ++I) {
421     if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
422         return false;
423   }
424   return true;
425 }
426
427 /// registerMDKind - Register a new metadata kind and return its ID.
428 /// A metadata kind can be registered only once. 
429 unsigned MetadataContext::registerMDKind(StringRef Name) {
430   assert(isValidName(Name) && "Invalid custome metadata name!");
431   return pImpl->registerMDKind(Name);
432 }
433
434 /// getMDKind - Return metadata kind. If the requested metadata kind
435 /// is not registered then return 0.
436 unsigned MetadataContext::getMDKind(StringRef Name) const {
437   return pImpl->getMDKind(Name);
438 }
439
440 /// getMD - Get the metadata of given kind attached to an Instruction.
441 /// If the metadata is not found then return 0.
442 MDNode *MetadataContext::getMD(unsigned Kind, const Instruction *Inst) {
443   return pImpl->getMD(Kind, Inst);
444 }
445
446 /// getMDs - Get the metadata attached to an Instruction.
447 void MetadataContext::
448 getMDs(const Instruction *Inst, 
449        SmallVectorImpl<std::pair<unsigned, TrackingVH<MDNode> > > &MDs) const {
450   return pImpl->getMDs(Inst, MDs);
451 }
452
453 /// addMD - Attach the metadata of given kind to an Instruction.
454 void MetadataContext::addMD(unsigned Kind, MDNode *Node, Instruction *Inst) {
455   pImpl->addMD(Kind, Node, Inst);
456 }
457   
458 /// removeMD - Remove metadata of given kind attached with an instuction.
459 void MetadataContext::removeMD(unsigned Kind, Instruction *Inst) {
460   pImpl->removeMD(Kind, Inst);
461 }
462   
463 /// removeAllMetadata - Remove all metadata attached with an instruction.
464 void MetadataContext::removeAllMetadata(Instruction *Inst) {
465   pImpl->removeAllMetadata(Inst);
466 }
467
468 /// copyMD - If metadata is attached with Instruction In1 then attach
469 /// the same metadata to In2.
470 void MetadataContext::copyMD(Instruction *In1, Instruction *In2) {
471   pImpl->copyMD(In1, In2);
472 }
473
474 /// getHandlerNames - Populate client supplied smallvector using custome
475 /// metadata name and ID.
476 void MetadataContext::
477 getHandlerNames(SmallVectorImpl<std::pair<unsigned, StringRef> >&N) const {
478   pImpl->getHandlerNames(N);
479 }
480
481 /// ValueIsDeleted - This handler is used to update metadata store
482 /// when a value is deleted.
483 void MetadataContext::ValueIsDeleted(Instruction *Inst) {
484   pImpl->ValueIsDeleted(Inst);
485 }
486 void MetadataContext::ValueIsRAUWd(Value *V1, Value *V2) {
487   pImpl->ValueIsRAUWd(V1, V2);
488 }
489
490 /// ValueIsCloned - This handler is used to update metadata store
491 /// when In1 is cloned to create In2.
492 void MetadataContext::ValueIsCloned(const Instruction *In1, Instruction *In2) {
493   pImpl->ValueIsCloned(In1, In2);
494 }