Copy metadata when value is RAUW'd. It is debatable whether this is the right approac...
[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 "SymbolTableListTraitsImpl.h"
20 using namespace llvm;
21
22 //===----------------------------------------------------------------------===//
23 //MetadataBase implementation
24 //
25
26 /// resizeOperands - Metadata keeps track of other metadata uses using 
27 /// OperandList. Resize this list to hold anticipated number of metadata
28 /// operands.
29 void MetadataBase::resizeOperands(unsigned NumOps) {
30   unsigned e = getNumOperands();
31   if (NumOps == 0) {
32     NumOps = e*2;
33     if (NumOps < 2) NumOps = 2;  
34   } else if (NumOps > NumOperands) {
35     // No resize needed.
36     if (ReservedSpace >= NumOps) return;
37   } else if (NumOps == NumOperands) {
38     if (ReservedSpace == NumOps) return;
39   } else {
40     return;
41   }
42
43   ReservedSpace = NumOps;
44   Use *OldOps = OperandList;
45   Use *NewOps = allocHungoffUses(NumOps);
46   std::copy(OldOps, OldOps + e, NewOps);
47   OperandList = NewOps;
48   if (OldOps) Use::zap(OldOps, OldOps + e, true);
49 }
50 //===----------------------------------------------------------------------===//
51 //MDString implementation
52 //
53 MDString *MDString::get(LLVMContext &Context, const StringRef &Str) {
54   LLVMContextImpl *pImpl = Context.pImpl;
55   sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
56   StringMapEntry<MDString *> &Entry = 
57     pImpl->MDStringCache.GetOrCreateValue(Str);
58   MDString *&S = Entry.getValue();
59   if (!S) S = new MDString(Context, Entry.getKeyData(),
60                            Entry.getKeyLength());
61
62   return S;
63 }
64
65 //===----------------------------------------------------------------------===//
66 //MDNode implementation
67 //
68 MDNode::MDNode(LLVMContext &C, Value*const* Vals, unsigned NumVals)
69   : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
70   NumOperands = 0;
71   resizeOperands(NumVals);
72   for (unsigned i = 0; i != NumVals; ++i) {
73     // Only record metadata uses.
74     if (MetadataBase *MB = dyn_cast_or_null<MetadataBase>(Vals[i]))
75       OperandList[NumOperands++] = MB;
76     else if(Vals[i] && 
77             Vals[i]->getType()->getTypeID() == Type::MetadataTyID)
78       OperandList[NumOperands++] = Vals[i];
79     Node.push_back(ElementVH(Vals[i], this));
80   }
81 }
82
83 void MDNode::Profile(FoldingSetNodeID &ID) const {
84   for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
85     ID.AddPointer(*I);
86 }
87
88 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals) {
89   LLVMContextImpl *pImpl = Context.pImpl;
90   FoldingSetNodeID ID;
91   for (unsigned i = 0; i != NumVals; ++i)
92     ID.AddPointer(Vals[i]);
93
94   pImpl->ConstantsLock.reader_acquire();
95   void *InsertPoint;
96   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
97   pImpl->ConstantsLock.reader_release();
98   
99   if (!N) {
100     sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
101     N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
102     if (!N) {
103       // InsertPoint will have been set by the FindNodeOrInsertPos call.
104       N = new MDNode(Context, Vals, NumVals);
105       pImpl->MDNodeSet.InsertNode(N, InsertPoint);
106     }
107   }
108
109   return N;
110 }
111
112 /// dropAllReferences - Remove all uses and clear node vector.
113 void MDNode::dropAllReferences() {
114   User::dropAllReferences();
115   Node.clear();
116 }
117
118 MDNode::~MDNode() {
119   {
120     LLVMContextImpl *pImpl = getType()->getContext().pImpl;
121     sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
122     pImpl->MDNodeSet.RemoveNode(this);
123   }
124   dropAllReferences();
125 }
126
127 // Replace value from this node's element list.
128 void MDNode::replaceElement(Value *From, Value *To) {
129   if (From == To || !getType())
130     return;
131   LLVMContext &Context = getType()->getContext();
132   LLVMContextImpl *pImpl = Context.pImpl;
133
134   // Find value. This is a linear search, do something if it consumes 
135   // lot of time. It is possible that to have multiple instances of
136   // From in this MDNode's element list.
137   SmallVector<unsigned, 4> Indexes;
138   unsigned Index = 0;
139   for (SmallVector<ElementVH, 4>::iterator I = Node.begin(),
140          E = Node.end(); I != E; ++I, ++Index) {
141     Value *V = *I;
142     if (V && V == From) 
143       Indexes.push_back(Index);
144   }
145
146   if (Indexes.empty())
147     return;
148
149   // Remove "this" from the context map. 
150   {
151     sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
152     pImpl->MDNodeSet.RemoveNode(this);
153   }
154
155   // MDNode only lists metadata elements in operand list, because MDNode
156   // used by MDNode is considered a valid use. However on the side, MDNode
157   // using a non-metadata value is not considered a "use" of non-metadata
158   // value.
159   SmallVector<unsigned, 4> OpIndexes;
160   unsigned OpIndex = 0;
161   for (User::op_iterator OI = op_begin(), OE = op_end();
162        OI != OE; ++OI, OpIndex++) {
163     if (*OI == From)
164       OpIndexes.push_back(OpIndex);
165   }
166   if (MetadataBase *MDTo = dyn_cast_or_null<MetadataBase>(To)) {
167     for (SmallVector<unsigned, 4>::iterator OI = OpIndexes.begin(),
168            OE = OpIndexes.end(); OI != OE; ++OI)
169       setOperand(*OI, MDTo);
170   } else {
171     for (SmallVector<unsigned, 4>::iterator OI = OpIndexes.begin(),
172            OE = OpIndexes.end(); OI != OE; ++OI)
173       setOperand(*OI, 0);
174   }
175
176   // Replace From element(s) in place.
177   for (SmallVector<unsigned, 4>::iterator I = Indexes.begin(), E = Indexes.end(); 
178        I != E; ++I) {
179     unsigned Index = *I;
180     Node[Index] = ElementVH(To, this);
181   }
182
183   // Insert updated "this" into the context's folding node set.
184   // If a node with same element list already exist then before inserting 
185   // updated "this" into the folding node set, replace all uses of existing 
186   // node with updated "this" node.
187   FoldingSetNodeID ID;
188   Profile(ID);
189   pImpl->ConstantsLock.reader_acquire();
190   void *InsertPoint;
191   MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
192   pImpl->ConstantsLock.reader_release();
193
194   if (N) {
195     N->replaceAllUsesWith(this);
196     delete N;
197     N = 0;
198   }
199
200   {
201     sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
202     N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
203     if (!N) {
204       // InsertPoint will have been set by the FindNodeOrInsertPos call.
205       N = this;
206       pImpl->MDNodeSet.InsertNode(N, InsertPoint);
207     }
208   }
209 }
210
211 //===----------------------------------------------------------------------===//
212 //NamedMDNode implementation
213 //
214 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
215                          MetadataBase*const* MDs, 
216                          unsigned NumMDs, Module *ParentModule)
217   : MetadataBase(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
218   setName(N);
219   NumOperands = 0;
220   resizeOperands(NumMDs);
221
222   for (unsigned i = 0; i != NumMDs; ++i) {
223     if (MDs[i])
224       OperandList[NumOperands++] = MDs[i];
225     Node.push_back(WeakMetadataVH(MDs[i]));
226   }
227   if (ParentModule)
228     ParentModule->getNamedMDList().push_back(this);
229 }
230
231 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
232   assert (NMD && "Invalid source NamedMDNode!");
233   SmallVector<MetadataBase *, 4> Elems;
234   for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i)
235     Elems.push_back(NMD->getElement(i));
236   return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
237                          Elems.data(), Elems.size(), M);
238 }
239
240 /// eraseFromParent - Drop all references and remove the node from parent
241 /// module.
242 void NamedMDNode::eraseFromParent() {
243   getParent()->getNamedMDList().erase(this);
244 }
245
246 /// dropAllReferences - Remove all uses and clear node vector.
247 void NamedMDNode::dropAllReferences() {
248   User::dropAllReferences();
249   Node.clear();
250 }
251
252 NamedMDNode::~NamedMDNode() {
253   dropAllReferences();
254 }
255
256 //===----------------------------------------------------------------------===//
257 //Metadata implementation
258 //
259
260 /// RegisterMDKind - Register a new metadata kind and return its ID.
261 /// A metadata kind can be registered only once. 
262 unsigned MetadataContext::RegisterMDKind(const char *Name) {
263   assert (validName(Name) && "Invalid custome metadata name!");
264   unsigned Count = MDHandlerNames.size();
265   assert(MDHandlerNames.find(Name) == MDHandlerNames.end() 
266          && "Already registered MDKind!");
267   MDHandlerNames[Name] = Count + 1;
268   return Count + 1;
269 }
270
271 /// validName - Return true if Name is a valid custom metadata handler name.
272 bool MetadataContext::validName(const char *Name) {
273   if (!Name)
274     return false;
275
276   if (!isalpha(*Name))
277     return false;
278
279   unsigned Length = strlen(Name);  
280   unsigned Count = 1;
281   ++Name;
282   while (Name &&
283          (isalnum(*Name) || *Name == '_' || *Name == '-' || *Name == '.')) {
284     ++Name;
285     ++Count;
286   }
287   if (Length != Count)
288     return false;
289   return true;
290 }
291
292 /// getMDKind - Return metadata kind. If the requested metadata kind
293 /// is not registered then return 0.
294 unsigned MetadataContext::getMDKind(const char *Name) {
295   assert (validName(Name) && "Invalid custome metadata name!");
296   StringMap<unsigned>::iterator I = MDHandlerNames.find(Name);
297   if (I == MDHandlerNames.end())
298     return 0;
299
300   return I->getValue();
301 }
302
303 /// addMD - Attach the metadata of given kind with an Instruction.
304 void MetadataContext::addMD(unsigned MDKind, MDNode *Node, Instruction *Inst) {
305   assert (Node && "Unable to add custome metadata");
306   Inst->HasMetadata = true;
307   MDStoreTy::iterator I = MetadataStore.find(Inst);
308   if (I == MetadataStore.end()) {
309     MDMapTy Info;
310     Info.push_back(std::make_pair(MDKind, Node));
311     MetadataStore.insert(std::make_pair(Inst, Info));
312     return;
313   }
314
315   MDMapTy &Info = I->second;
316   // If there is an entry for this MDKind then replace it.
317   for (unsigned i = 0, e = Info.size(); i != e; ++i) {
318     MDPairTy &P = Info[i];
319     if (P.first == MDKind) {
320       Info[i] = std::make_pair(MDKind, Node);
321       return;
322     }
323   }
324
325   // Otherwise add a new entry.
326   Info.push_back(std::make_pair(MDKind, Node));
327   return;
328 }
329
330 /// removeMD - Remove metadata of given kind attached with an instuction.
331 void MetadataContext::removeMD(unsigned Kind, Instruction *Inst) {
332   MDStoreTy::iterator I = MetadataStore.find(Inst);
333   if (I == MetadataStore.end())
334     return;
335
336   MDMapTy &Info = I->second;
337   for (MDMapTy::iterator MI = Info.begin(), ME = Info.end(); MI != ME; ++MI) {
338     MDPairTy &P = *MI;
339     if (P.first == Kind) {
340       Info.erase(MI);
341       return;
342     }
343   }
344
345   return;
346 }
347   
348 /// removeMDs - Remove all metadata attached with an instruction.
349 void MetadataContext::removeMDs(const Instruction *Inst) {
350   // Find Metadata handles for this instruction.
351   MDStoreTy::iterator I = MetadataStore.find(Inst);
352   assert (I != MetadataStore.end() && "Invalid custom metadata info!");
353   MDMapTy &Info = I->second;
354   
355   // FIXME : Give all metadata handlers a chance to adjust.
356   
357   // Remove the entries for this instruction.
358   Info.clear();
359   MetadataStore.erase(I);
360 }
361
362
363 /// getMD - Get the metadata of given kind attached with an Instruction.
364 /// If the metadata is not found then return 0.
365 MDNode *MetadataContext::getMD(unsigned MDKind, const Instruction *Inst) {
366   MDStoreTy::iterator I = MetadataStore.find(Inst);
367   if (I == MetadataStore.end())
368     return NULL;
369   
370   MDMapTy &Info = I->second;
371   for (MDMapTy::iterator I = Info.begin(), E = Info.end(); I != E; ++I)
372     if (I->first == MDKind)
373       return dyn_cast_or_null<MDNode>(I->second);
374   return NULL;
375 }
376
377 /// getMDs - Get the metadata attached with an Instruction.
378 const MetadataContext::MDMapTy *MetadataContext::getMDs(const Instruction *Inst) {
379   MDStoreTy::iterator I = MetadataStore.find(Inst);
380   if (I == MetadataStore.end())
381     return NULL;
382   
383   return &(I->second);
384 }
385
386 /// getHandlerNames - Get handler names. This is used by bitcode
387 /// writer.
388 const StringMap<unsigned> *MetadataContext::getHandlerNames() {
389   return &MDHandlerNames;
390 }
391
392 /// ValueIsCloned - This handler is used to update metadata store
393 /// when In1 is cloned to create In2.
394 void MetadataContext::ValueIsCloned(const Instruction *In1, Instruction *In2) {
395   // Find Metadata handles for In1.
396   MDStoreTy::iterator I = MetadataStore.find(In1);
397   assert (I != MetadataStore.end() && "Invalid custom metadata info!");
398
399   // FIXME : Give all metadata handlers a chance to adjust.
400
401   MDMapTy &In1Info = I->second;
402   MDMapTy In2Info;
403   for (MDMapTy::iterator I = In1Info.begin(), E = In1Info.end(); I != E; ++I)
404     if (MDNode *MD = dyn_cast_or_null<MDNode>(I->second))
405       addMD(I->first, MD, In2);
406 }
407
408 /// ValueIsRAUWd - This handler is used when V1's all uses are replaced by
409 /// V2.
410 void MetadataContext::ValueIsRAUWd(Value *V1, Value *V2) {
411   Instruction *I1 = dyn_cast<Instruction>(V1);
412   Instruction *I2 = dyn_cast<Instruction>(V2);
413   if (!I1 || !I2)
414     return;
415
416   // FIXME : Give custom handlers a chance to override this.
417   ValueIsCloned(I1, I2);
418 }