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