1 //===-- Metadata.cpp - Implement Metadata classes -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Metadata classes.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Metadata.h"
15 #include "LLVMContextImpl.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 "llvm/ADT/SmallString.h"
22 #include "SymbolTableListTraitsImpl.h"
23 #include "llvm/Support/ValueHandle.h"
26 //===----------------------------------------------------------------------===//
27 // MDString implementation.
30 MDString::MDString(LLVMContext &C, StringRef S)
31 : MetadataBase(Type::getMetadataTy(C), Value::MDStringVal), Str(S) {}
33 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
34 LLVMContextImpl *pImpl = Context.pImpl;
35 StringMapEntry<MDString *> &Entry =
36 pImpl->MDStringCache.GetOrCreateValue(Str);
37 MDString *&S = Entry.getValue();
38 if (!S) S = new MDString(Context, Entry.getKey());
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) S = new MDString(Context, Entry.getKey());
51 //===----------------------------------------------------------------------===//
52 // MDNodeOperand implementation.
55 // Use CallbackVH to hold MDNode operands.
57 class MDNodeOperand : public CallbackVH {
60 MDNodeOperand(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {}
67 virtual void deleted();
68 virtual void allUsesReplacedWith(Value *NV);
70 } // end namespace llvm.
73 void MDNodeOperand::deleted() {
74 Parent->replaceOperand(this, 0);
77 void MDNodeOperand::allUsesReplacedWith(Value *NV) {
78 Parent->replaceOperand(this, NV);
83 //===----------------------------------------------------------------------===//
84 // MDNode implementation.
87 /// getOperandPtr - Helper function to get the MDNodeOperand's coallocated on
88 /// the end of the MDNode.
89 static MDNodeOperand *getOperandPtr(MDNode *N, unsigned Op) {
90 assert(Op < N->getNumOperands() && "Invalid operand number");
91 return reinterpret_cast<MDNodeOperand*>(N+1)+Op;
94 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals,
96 : MetadataBase(Type::getMetadataTy(C), Value::MDNodeVal) {
97 NumOperands = NumVals;
100 setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit);
102 // Initialize the operand list, which is co-allocated on the end of the node.
103 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
104 Op != E; ++Op, ++Vals)
105 new (Op) MDNodeOperand(*Vals, this);
109 /// ~MDNode - Destroy MDNode.
111 assert((getSubclassDataFromValue() & DestroyFlag) != 0 &&
112 "Not being destroyed through destroy()?");
113 if (!isNotUniqued()) {
114 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
115 pImpl->MDNodeSet.RemoveNode(this);
118 // Destroy the operands.
119 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
121 Op->~MDNodeOperand();
124 // destroy - Delete this node. Only when there are no uses.
125 void MDNode::destroy() {
126 setValueSubclassData(getSubclassDataFromValue() | DestroyFlag);
127 // Placement delete, the free the memory.
132 MDNode *MDNode::getMDNode(LLVMContext &Context, Value *const *Vals,
133 unsigned NumVals, FunctionLocalness FL) {
134 LLVMContextImpl *pImpl = Context.pImpl;
136 for (unsigned i = 0; i != NumVals; ++i)
137 ID.AddPointer(Vals[i]);
140 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
142 bool isFunctionLocal = false;
145 for (unsigned i = 0; i != NumVals; ++i) {
148 if (isa<Instruction>(V) || isa<Argument>(V) || isa<BasicBlock>(V) ||
149 (isa<MDNode>(V) && cast<MDNode>(V)->isFunctionLocal())) {
150 isFunctionLocal = true;
156 isFunctionLocal = false;
159 isFunctionLocal = true;
163 // Coallocate space for the node and Operands together, then placement new.
164 void *Ptr = malloc(sizeof(MDNode)+NumVals*sizeof(MDNodeOperand));
165 N = new (Ptr) MDNode(Context, Vals, NumVals, isFunctionLocal);
167 // InsertPoint will have been set by the FindNodeOrInsertPos call.
168 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
173 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals) {
174 return getMDNode(Context, Vals, NumVals, FL_Unknown);
177 MDNode *MDNode::getWhenValsUnresolved(LLVMContext &Context, Value*const* Vals,
178 unsigned NumVals, bool isFunctionLocal) {
179 return getMDNode(Context, Vals, NumVals, isFunctionLocal ? FL_Yes : FL_No);
182 /// getOperand - Return specified operand.
183 Value *MDNode::getOperand(unsigned i) const {
184 return *getOperandPtr(const_cast<MDNode*>(this), i);
187 void MDNode::Profile(FoldingSetNodeID &ID) const {
188 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
189 ID.AddPointer(getOperand(i));
193 // Replace value from this node's operand list.
194 void MDNode::replaceOperand(MDNodeOperand *Op, Value *To) {
200 // Update the operand.
203 // If this node is already not being uniqued (because one of the operands
204 // already went to null), then there is nothing else to do here.
205 if (isNotUniqued()) return;
207 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
209 // Remove "this" from the context map. FoldingSet doesn't have to reprofile
210 // this node to remove it, so we don't care what state the operands are in.
211 pImpl->MDNodeSet.RemoveNode(this);
213 // If we are dropping an argument to null, we choose to not unique the MDNode
214 // anymore. This commonly occurs during destruction, and uniquing these
215 // brings little reuse.
221 // Now that the node is out of the folding set, get ready to reinsert it.
222 // First, check to see if another node with the same operands already exists
223 // in the set. If it doesn't exist, this returns the position to insert it.
227 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
230 N->replaceAllUsesWith(this);
232 N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
233 assert(N == 0 && "shouldn't be in the map now!"); (void)N;
236 // InsertPoint will have been set by the FindNodeOrInsertPos call.
237 pImpl->MDNodeSet.InsertNode(this, InsertPoint);
240 //===----------------------------------------------------------------------===//
241 // NamedMDNode implementation.
245 // SymbolTableListTraits specialization for MDSymbolTable.
246 void ilist_traits<NamedMDNode>
247 ::addNodeToList(NamedMDNode *N) {
248 assert(N->getParent() == 0 && "Value already in a container!!");
249 Module *Owner = getListOwner();
251 MDSymbolTable &ST = Owner->getMDSymbolTable();
252 ST.insert(N->getName(), N);
255 void ilist_traits<NamedMDNode>::removeNodeFromList(NamedMDNode *N) {
257 Module *Owner = getListOwner();
258 MDSymbolTable &ST = Owner->getMDSymbolTable();
259 ST.remove(N->getName());
263 static SmallVector<WeakVH, 4> &getNMDOps(void *Operands) {
264 return *(SmallVector<WeakVH, 4>*)Operands;
267 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
269 unsigned NumMDs, Module *ParentModule)
270 : Value(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
272 Operands = new SmallVector<WeakVH, 4>();
274 SmallVector<WeakVH, 4> &Node = getNMDOps(Operands);
275 for (unsigned i = 0; i != NumMDs; ++i)
276 Node.push_back(WeakVH(MDs[i]));
279 ParentModule->getNamedMDList().push_back(this);
282 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
283 assert(NMD && "Invalid source NamedMDNode!");
284 SmallVector<MDNode *, 4> Elems;
285 Elems.reserve(NMD->getNumOperands());
287 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
288 Elems.push_back(NMD->getOperand(i));
289 return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
290 Elems.data(), Elems.size(), M);
293 NamedMDNode::~NamedMDNode() {
295 delete &getNMDOps(Operands);
298 /// getNumOperands - Return number of NamedMDNode operands.
299 unsigned NamedMDNode::getNumOperands() const {
300 return (unsigned)getNMDOps(Operands).size();
303 /// getOperand - Return specified operand.
304 MDNode *NamedMDNode::getOperand(unsigned i) const {
305 assert(i < getNumOperands() && "Invalid Operand number!");
306 return dyn_cast_or_null<MDNode>(getNMDOps(Operands)[i]);
309 /// addOperand - Add metadata Operand.
310 void NamedMDNode::addOperand(MDNode *M) {
311 getNMDOps(Operands).push_back(WeakVH(M));
314 /// eraseFromParent - Drop all references and remove the node from parent
316 void NamedMDNode::eraseFromParent() {
317 getParent()->getNamedMDList().erase(this);
320 /// dropAllReferences - Remove all uses and clear node vector.
321 void NamedMDNode::dropAllReferences() {
322 getNMDOps(Operands).clear();
325 /// setName - Set the name of this named metadata.
326 void NamedMDNode::setName(const Twine &NewName) {
327 assert (!NewName.isTriviallyEmpty() && "Invalid named metadata name!");
329 SmallString<256> NameData;
330 NewName.toVector(NameData);
332 const char *NameStr = NameData.data();
333 unsigned NameLen = NameData.size();
335 StringRef NameRef = StringRef(NameStr, NameLen);
336 // Name isn't changing?
337 if (getName() == NameRef)
340 Name = NameRef.str();
342 Parent->getMDSymbolTable().insert(NameRef, this);
345 /// getName - Return a constant reference to this named metadata's name.
346 StringRef NamedMDNode::getName() const {
347 return StringRef(Name);
350 //===----------------------------------------------------------------------===//
351 // LLVMContext MDKind naming implementation.
355 /// isValidName - Return true if Name is a valid custom metadata handler name.
356 static bool isValidName(StringRef MDName) {
360 if (!isalpha(MDName[0]))
363 for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
365 if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
372 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
373 unsigned LLVMContext::getMDKindID(StringRef Name) const {
374 assert(isValidName(Name) && "Invalid MDNode name");
376 unsigned &Entry = pImpl->CustomMDKindNames[Name];
378 // If this is new, assign it its ID.
379 if (Entry == 0) Entry = pImpl->CustomMDKindNames.size();
383 /// getHandlerNames - Populate client supplied smallvector using custome
384 /// metadata name and ID.
385 void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
386 Names.resize(pImpl->CustomMDKindNames.size()+1);
388 for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
389 E = pImpl->CustomMDKindNames.end(); I != E; ++I)
390 // MD Handlers are numbered from 1.
391 Names[I->second] = I->first();
394 //===----------------------------------------------------------------------===//
395 // Instruction Metadata method implementations.
398 void Instruction::setMetadata(const char *Kind, MDNode *Node) {
399 if (Node == 0 && !hasMetadata()) return;
400 setMetadata(getContext().getMDKindID(Kind), Node);
403 MDNode *Instruction::getMetadataImpl(const char *Kind) const {
404 return getMetadataImpl(getContext().getMDKindID(Kind));
407 /// setMetadata - Set the metadata of of the specified kind to the specified
408 /// node. This updates/replaces metadata if already present, or removes it if
410 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
411 if (Node == 0 && !hasMetadata()) return;
413 // Handle the case when we're adding/updating metadata on an instruction.
415 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
416 assert(!Info.empty() == hasMetadata() && "HasMetadata bit is wonked");
418 setHasMetadata(true);
420 // Handle replacement of an existing value.
421 for (unsigned i = 0, e = Info.size(); i != e; ++i)
422 if (Info[i].first == KindID) {
423 Info[i].second = Node;
428 // No replacement, just add it to the list.
429 Info.push_back(std::make_pair(KindID, Node));
433 // Otherwise, we're removing metadata from an instruction.
434 assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
435 "HasMetadata bit out of date!");
436 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
438 // Common case is removing the only entry.
439 if (Info.size() == 1 && Info[0].first == KindID) {
440 getContext().pImpl->MetadataStore.erase(this);
441 setHasMetadata(false);
445 // Handle replacement of an existing value.
446 for (unsigned i = 0, e = Info.size(); i != e; ++i)
447 if (Info[i].first == KindID) {
448 Info[i] = Info.back();
450 assert(!Info.empty() && "Removing last entry should be handled above");
453 // Otherwise, removing an entry that doesn't exist on the instruction.
456 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
457 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
458 assert(hasMetadata() && !Info.empty() && "Shouldn't have called this");
460 for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end();
462 if (I->first == KindID)
467 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
468 MDNode*> > &Result)const {
469 assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
470 "Shouldn't have called this");
471 const LLVMContextImpl::MDMapTy &Info =
472 getContext().pImpl->MetadataStore.find(this)->second;
473 assert(!Info.empty() && "Shouldn't have called this");
476 Result.append(Info.begin(), Info.end());
478 // Sort the resulting array so it is stable.
479 if (Result.size() > 1)
480 array_pod_sort(Result.begin(), Result.end());
483 /// removeAllMetadata - Remove all metadata from this instruction.
484 void Instruction::removeAllMetadata() {
485 assert(hasMetadata() && "Caller should check");
486 getContext().pImpl->MetadataStore.erase(this);
487 setHasMetadata(false);