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 : Value(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 //===----------------------------------------------------------------------===//
43 // MDNodeOperand implementation.
46 // Use CallbackVH to hold MDNode operands.
48 class MDNodeOperand : public CallbackVH {
51 MDNodeOperand(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {}
58 virtual void deleted();
59 virtual void allUsesReplacedWith(Value *NV);
61 } // end namespace llvm.
64 void MDNodeOperand::deleted() {
65 Parent->replaceOperand(this, 0);
68 void MDNodeOperand::allUsesReplacedWith(Value *NV) {
69 Parent->replaceOperand(this, NV);
74 //===----------------------------------------------------------------------===//
75 // MDNode implementation.
78 /// getOperandPtr - Helper function to get the MDNodeOperand's coallocated on
79 /// the end of the MDNode.
80 static MDNodeOperand *getOperandPtr(MDNode *N, unsigned Op) {
81 assert(Op < N->getNumOperands() && "Invalid operand number");
82 return reinterpret_cast<MDNodeOperand*>(N+1)+Op;
85 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals,
87 : Value(Type::getMetadataTy(C), Value::MDNodeVal) {
88 NumOperands = NumVals;
91 setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit);
93 // Initialize the operand list, which is co-allocated on the end of the node.
94 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
95 Op != E; ++Op, ++Vals)
96 new (Op) MDNodeOperand(*Vals, this);
100 /// ~MDNode - Destroy MDNode.
102 assert((getSubclassDataFromValue() & DestroyFlag) != 0 &&
103 "Not being destroyed through destroy()?");
104 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
105 if (isNotUniqued()) {
106 pImpl->NonUniquedMDNodes.erase(this);
108 pImpl->MDNodeSet.RemoveNode(this);
111 // Destroy the operands.
112 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
114 Op->~MDNodeOperand();
117 static const Function *getFunctionForValue(Value *V) {
118 assert(!isa<MDNode>(V) && "does not iterate over metadata operands");
120 if (Instruction *I = dyn_cast<Instruction>(V))
121 return I->getParent()->getParent();
122 if (BasicBlock *BB = dyn_cast<BasicBlock>(V))
123 return BB->getParent();
124 if (Argument *A = dyn_cast<Argument>(V))
125 return A->getParent();
130 static const Function *assertLocalFunction(const MDNode *N) {
131 if (!N->isFunctionLocal()) return 0;
133 const Function *F = 0, *NewF = 0;
134 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
135 if (Value *V = N->getOperand(i)) {
136 if (MDNode *MD = dyn_cast<MDNode>(V))
137 NewF = assertLocalFunction(MD);
139 NewF = getFunctionForValue(V);
144 assert((NewF == 0 || F == NewF) &&"inconsistent function-local metadata");
150 // getFunction - If this metadata is function-local and recursively has a
151 // function-local operand, return the first such operand's parent function.
152 // Otherwise, return null. getFunction() should not be used for performance-
153 // critical code because it recursively visits all the MDNode's operands.
154 const Function *MDNode::getFunction() const {
156 return assertLocalFunction(this);
158 if (!isFunctionLocal()) return NULL;
160 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
161 if (Value *V = getOperand(i)) {
162 if (MDNode *MD = dyn_cast<MDNode>(V)) {
163 if (const Function *F = MD->getFunction())
166 return getFunctionForValue(V);
173 // destroy - Delete this node. Only when there are no uses.
174 void MDNode::destroy() {
175 setValueSubclassData(getSubclassDataFromValue() | DestroyFlag);
176 // Placement delete, the free the memory.
181 MDNode *MDNode::getMDNode(LLVMContext &Context, Value *const *Vals,
182 unsigned NumVals, FunctionLocalness FL,
184 LLVMContextImpl *pImpl = Context.pImpl;
186 for (unsigned i = 0; i != NumVals; ++i)
187 ID.AddPointer(Vals[i]);
192 if ((N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint)))
198 bool isFunctionLocal = false;
201 for (unsigned i = 0; i != NumVals; ++i) {
204 if (isa<Instruction>(V) || isa<Argument>(V) || isa<BasicBlock>(V) ||
205 (isa<MDNode>(V) && cast<MDNode>(V)->isFunctionLocal())) {
206 isFunctionLocal = true;
212 isFunctionLocal = false;
215 isFunctionLocal = true;
219 // Coallocate space for the node and Operands together, then placement new.
220 void *Ptr = malloc(sizeof(MDNode)+NumVals*sizeof(MDNodeOperand));
221 N = new (Ptr) MDNode(Context, Vals, NumVals, isFunctionLocal);
223 // InsertPoint will have been set by the FindNodeOrInsertPos call.
224 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
229 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals) {
230 return getMDNode(Context, Vals, NumVals, FL_Unknown);
233 MDNode *MDNode::getWhenValsUnresolved(LLVMContext &Context, Value *const *Vals,
234 unsigned NumVals, bool isFunctionLocal) {
235 return getMDNode(Context, Vals, NumVals, isFunctionLocal ? FL_Yes : FL_No);
238 MDNode *MDNode::getIfExists(LLVMContext &Context, Value *const *Vals,
240 return getMDNode(Context, Vals, NumVals, FL_Unknown, false);
243 /// getOperand - Return specified operand.
244 Value *MDNode::getOperand(unsigned i) const {
245 return *getOperandPtr(const_cast<MDNode*>(this), i);
248 void MDNode::Profile(FoldingSetNodeID &ID) const {
249 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
250 ID.AddPointer(getOperand(i));
251 ID.AddBoolean(isFunctionLocal());
254 void MDNode::setIsNotUniqued() {
255 setValueSubclassData(getSubclassDataFromValue() | NotUniquedBit);
256 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
257 pImpl->NonUniquedMDNodes.insert(this);
260 // Replace value from this node's operand list.
261 void MDNode::replaceOperand(MDNodeOperand *Op, Value *To) {
267 // Update the operand.
270 // If this node is already not being uniqued (because one of the operands
271 // already went to null), then there is nothing else to do here.
272 if (isNotUniqued()) return;
274 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
276 // Remove "this" from the context map. FoldingSet doesn't have to reprofile
277 // this node to remove it, so we don't care what state the operands are in.
278 pImpl->MDNodeSet.RemoveNode(this);
280 // If we are dropping an argument to null, we choose to not unique the MDNode
281 // anymore. This commonly occurs during destruction, and uniquing these
282 // brings little reuse.
288 // Now that the node is out of the folding set, get ready to reinsert it.
289 // First, check to see if another node with the same operands already exists
290 // in the set. If it doesn't exist, this returns the position to insert it.
294 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
297 N->replaceAllUsesWith(this);
299 N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
300 assert(N == 0 && "shouldn't be in the map now!"); (void)N;
303 // InsertPoint will have been set by the FindNodeOrInsertPos call.
304 pImpl->MDNodeSet.InsertNode(this, InsertPoint);
307 //===----------------------------------------------------------------------===//
308 // NamedMDNode implementation.
312 // SymbolTableListTraits specialization for MDSymbolTable.
313 void ilist_traits<NamedMDNode>
314 ::addNodeToList(NamedMDNode *N) {
315 assert(N->getParent() == 0 && "Value already in a container!!");
316 Module *Owner = getListOwner();
318 MDSymbolTable &ST = Owner->getMDSymbolTable();
319 ST.insert(N->getName(), N);
322 void ilist_traits<NamedMDNode>::removeNodeFromList(NamedMDNode *N) {
324 Module *Owner = getListOwner();
325 MDSymbolTable &ST = Owner->getMDSymbolTable();
326 ST.remove(N->getName());
330 static SmallVector<WeakVH, 4> &getNMDOps(void *Operands) {
331 return *(SmallVector<WeakVH, 4>*)Operands;
334 NamedMDNode::NamedMDNode(LLVMContext &C, const Twine &N,
336 unsigned NumMDs, Module *ParentModule)
337 : Value(Type::getMetadataTy(C), Value::NamedMDNodeVal), Parent(0) {
339 Operands = new SmallVector<WeakVH, 4>();
341 SmallVector<WeakVH, 4> &Node = getNMDOps(Operands);
342 for (unsigned i = 0; i != NumMDs; ++i)
343 Node.push_back(WeakVH(MDs[i]));
346 ParentModule->getNamedMDList().push_back(this);
349 NamedMDNode *NamedMDNode::Create(const NamedMDNode *NMD, Module *M) {
350 assert(NMD && "Invalid source NamedMDNode!");
351 SmallVector<MDNode *, 4> Elems;
352 Elems.reserve(NMD->getNumOperands());
354 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
355 Elems.push_back(NMD->getOperand(i));
356 return new NamedMDNode(NMD->getContext(), NMD->getName().data(),
357 Elems.data(), Elems.size(), M);
360 NamedMDNode::~NamedMDNode() {
362 delete &getNMDOps(Operands);
365 /// getNumOperands - Return number of NamedMDNode operands.
366 unsigned NamedMDNode::getNumOperands() const {
367 return (unsigned)getNMDOps(Operands).size();
370 /// getOperand - Return specified operand.
371 MDNode *NamedMDNode::getOperand(unsigned i) const {
372 assert(i < getNumOperands() && "Invalid Operand number!");
373 return dyn_cast_or_null<MDNode>(getNMDOps(Operands)[i]);
376 /// addOperand - Add metadata Operand.
377 void NamedMDNode::addOperand(MDNode *M) {
378 getNMDOps(Operands).push_back(WeakVH(M));
381 /// eraseFromParent - Drop all references and remove the node from parent
383 void NamedMDNode::eraseFromParent() {
384 getParent()->getNamedMDList().erase(this);
387 /// dropAllReferences - Remove all uses and clear node vector.
388 void NamedMDNode::dropAllReferences() {
389 getNMDOps(Operands).clear();
392 /// setName - Set the name of this named metadata.
393 void NamedMDNode::setName(const Twine &NewName) {
394 assert (!NewName.isTriviallyEmpty() && "Invalid named metadata name!");
396 SmallString<256> NameData;
397 StringRef NameRef = NewName.toStringRef(NameData);
399 // Name isn't changing?
400 if (getName() == NameRef)
403 Name = NameRef.str();
405 Parent->getMDSymbolTable().insert(NameRef, this);
408 /// getName - Return a constant reference to this named metadata's name.
409 StringRef NamedMDNode::getName() const {
410 return StringRef(Name);
413 //===----------------------------------------------------------------------===//
414 // LLVMContext MDKind naming implementation.
418 /// isValidName - Return true if Name is a valid custom metadata handler name.
419 static bool isValidName(StringRef MDName) {
423 if (!isalpha(MDName[0]))
426 for (StringRef::iterator I = MDName.begin() + 1, E = MDName.end(); I != E;
428 if (!isalnum(*I) && *I != '_' && *I != '-' && *I != '.')
435 /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
436 unsigned LLVMContext::getMDKindID(StringRef Name) const {
437 assert(isValidName(Name) && "Invalid MDNode name");
439 unsigned &Entry = pImpl->CustomMDKindNames[Name];
441 // If this is new, assign it its ID.
442 if (Entry == 0) Entry = pImpl->CustomMDKindNames.size();
446 /// getHandlerNames - Populate client supplied smallvector using custome
447 /// metadata name and ID.
448 void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
449 Names.resize(pImpl->CustomMDKindNames.size()+1);
451 for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
452 E = pImpl->CustomMDKindNames.end(); I != E; ++I)
453 // MD Handlers are numbered from 1.
454 Names[I->second] = I->first();
457 //===----------------------------------------------------------------------===//
458 // Instruction Metadata method implementations.
461 void Instruction::setMetadata(const char *Kind, MDNode *Node) {
462 if (Node == 0 && !hasMetadata()) return;
463 setMetadata(getContext().getMDKindID(Kind), Node);
466 MDNode *Instruction::getMetadataImpl(const char *Kind) const {
467 return getMetadataImpl(getContext().getMDKindID(Kind));
470 /// setMetadata - Set the metadata of of the specified kind to the specified
471 /// node. This updates/replaces metadata if already present, or removes it if
473 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
474 if (Node == 0 && !hasMetadata()) return;
476 // Handle the case when we're adding/updating metadata on an instruction.
478 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
479 assert(!Info.empty() == hasMetadata() && "HasMetadata bit is wonked");
481 setHasMetadata(true);
483 // Handle replacement of an existing value.
484 for (unsigned i = 0, e = Info.size(); i != e; ++i)
485 if (Info[i].first == KindID) {
486 Info[i].second = Node;
491 // No replacement, just add it to the list.
492 Info.push_back(std::make_pair(KindID, Node));
496 // Otherwise, we're removing metadata from an instruction.
497 assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
498 "HasMetadata bit out of date!");
499 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
501 // Common case is removing the only entry.
502 if (Info.size() == 1 && Info[0].first == KindID) {
503 getContext().pImpl->MetadataStore.erase(this);
504 setHasMetadata(false);
508 // Handle replacement of an existing value.
509 for (unsigned i = 0, e = Info.size(); i != e; ++i)
510 if (Info[i].first == KindID) {
511 Info[i] = Info.back();
513 assert(!Info.empty() && "Removing last entry should be handled above");
516 // Otherwise, removing an entry that doesn't exist on the instruction.
519 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
520 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
521 assert(hasMetadata() && !Info.empty() && "Shouldn't have called this");
523 for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end();
525 if (I->first == KindID)
530 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
531 MDNode*> > &Result)const {
532 assert(hasMetadata() && getContext().pImpl->MetadataStore.count(this) &&
533 "Shouldn't have called this");
534 const LLVMContextImpl::MDMapTy &Info =
535 getContext().pImpl->MetadataStore.find(this)->second;
536 assert(!Info.empty() && "Shouldn't have called this");
539 Result.append(Info.begin(), Info.end());
541 // Sort the resulting array so it is stable.
542 if (Result.size() > 1)
543 array_pod_sort(Result.begin(), Result.end());
546 /// removeAllMetadata - Remove all metadata from this instruction.
547 void Instruction::removeAllMetadata() {
548 assert(hasMetadata() && "Caller should check");
549 getContext().pImpl->MetadataStore.erase(this);
550 setHasMetadata(false);