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 // Use <= instead of < to permit a one-past-the-end address.
82 assert(Op <= N->getNumOperands() && "Invalid operand number");
83 return reinterpret_cast<MDNodeOperand*>(N+1)+Op;
86 MDNode::MDNode(LLVMContext &C, Value *const *Vals, unsigned NumVals,
88 : Value(Type::getMetadataTy(C), Value::MDNodeVal) {
89 NumOperands = NumVals;
92 setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit);
94 // Initialize the operand list, which is co-allocated on the end of the node.
95 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
96 Op != E; ++Op, ++Vals)
97 new (Op) MDNodeOperand(*Vals, this);
101 /// ~MDNode - Destroy MDNode.
103 assert((getSubclassDataFromValue() & DestroyFlag) != 0 &&
104 "Not being destroyed through destroy()?");
105 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
106 if (isNotUniqued()) {
107 pImpl->NonUniquedMDNodes.erase(this);
109 pImpl->MDNodeSet.RemoveNode(this);
112 // Destroy the operands.
113 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
115 Op->~MDNodeOperand();
118 static const Function *getFunctionForValue(Value *V) {
120 if (Instruction *I = dyn_cast<Instruction>(V)) {
121 BasicBlock *BB = I->getParent();
122 return BB ? BB->getParent() : 0;
124 if (Argument *A = dyn_cast<Argument>(V))
125 return A->getParent();
126 if (BasicBlock *BB = dyn_cast<BasicBlock>(V))
127 return BB->getParent();
128 if (MDNode *MD = dyn_cast<MDNode>(V))
129 return MD->getFunction();
134 static const Function *assertLocalFunction(const MDNode *N) {
135 if (!N->isFunctionLocal()) return 0;
137 // FIXME: This does not handle cyclic function local metadata.
138 const Function *F = 0, *NewF = 0;
139 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
140 if (Value *V = N->getOperand(i)) {
141 if (MDNode *MD = dyn_cast<MDNode>(V))
142 NewF = assertLocalFunction(MD);
144 NewF = getFunctionForValue(V);
149 assert((NewF == 0 || F == NewF) &&"inconsistent function-local metadata");
155 // getFunction - If this metadata is function-local and recursively has a
156 // function-local operand, return the first such operand's parent function.
157 // Otherwise, return null. getFunction() should not be used for performance-
158 // critical code because it recursively visits all the MDNode's operands.
159 const Function *MDNode::getFunction() const {
161 return assertLocalFunction(this);
163 if (!isFunctionLocal()) return NULL;
164 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
165 if (const Function *F = getFunctionForValue(getOperand(i)))
170 // destroy - Delete this node. Only when there are no uses.
171 void MDNode::destroy() {
172 setValueSubclassData(getSubclassDataFromValue() | DestroyFlag);
173 // Placement delete, the free the memory.
178 /// isFunctionLocalValue - Return true if this is a value that would require a
179 /// function-local MDNode.
180 static bool isFunctionLocalValue(Value *V) {
181 return isa<Instruction>(V) || isa<Argument>(V) || isa<BasicBlock>(V) ||
182 (isa<MDNode>(V) && cast<MDNode>(V)->isFunctionLocal());
185 MDNode *MDNode::getMDNode(LLVMContext &Context, Value *const *Vals,
186 unsigned NumVals, FunctionLocalness FL,
188 LLVMContextImpl *pImpl = Context.pImpl;
189 bool isFunctionLocal = false;
192 for (unsigned i = 0; i != NumVals; ++i) {
195 if (isFunctionLocalValue(V)) {
196 isFunctionLocal = true;
202 isFunctionLocal = false;
205 isFunctionLocal = true;
210 for (unsigned i = 0; i != NumVals; ++i)
211 ID.AddPointer(Vals[i]);
212 ID.AddBoolean(isFunctionLocal);
217 if ((N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint)))
223 // Coallocate space for the node and Operands together, then placement new.
224 void *Ptr = malloc(sizeof(MDNode)+NumVals*sizeof(MDNodeOperand));
225 N = new (Ptr) MDNode(Context, Vals, NumVals, isFunctionLocal);
227 // InsertPoint will have been set by the FindNodeOrInsertPos call.
228 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
233 MDNode *MDNode::get(LLVMContext &Context, Value*const* Vals, unsigned NumVals) {
234 return getMDNode(Context, Vals, NumVals, FL_Unknown);
237 MDNode *MDNode::getWhenValsUnresolved(LLVMContext &Context, Value *const *Vals,
238 unsigned NumVals, bool isFunctionLocal) {
239 return getMDNode(Context, Vals, NumVals, isFunctionLocal ? FL_Yes : FL_No);
242 MDNode *MDNode::getIfExists(LLVMContext &Context, Value *const *Vals,
244 return getMDNode(Context, Vals, NumVals, FL_Unknown, false);
247 /// getOperand - Return specified operand.
248 Value *MDNode::getOperand(unsigned i) const {
249 return *getOperandPtr(const_cast<MDNode*>(this), i);
252 void MDNode::Profile(FoldingSetNodeID &ID) const {
253 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
254 ID.AddPointer(getOperand(i));
255 ID.AddBoolean(isFunctionLocal());
258 void MDNode::setIsNotUniqued() {
259 setValueSubclassData(getSubclassDataFromValue() | NotUniquedBit);
260 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
261 pImpl->NonUniquedMDNodes.insert(this);
264 // Replace value from this node's operand list.
265 void MDNode::replaceOperand(MDNodeOperand *Op, Value *To) {
268 // If is possible that someone did GV->RAUW(inst), replacing a global variable
269 // with an instruction or some other function-local object. If this is a
270 // non-function-local MDNode, it can't point to a function-local object.
271 // Handle this case by implicitly dropping the MDNode reference to null.
272 // Likewise if the MDNode is function-local but for a different function.
273 if (To && isFunctionLocalValue(To)) {
274 if (!isFunctionLocal())
277 const Function *F = getFunction();
278 const Function *FV = getFunctionForValue(To);
279 // Metadata can be function-local without having an associated function.
280 // So only consider functions to have changed if non-null.
281 if (F && FV && F != FV)
289 // Update the operand.
292 // If this node is already not being uniqued (because one of the operands
293 // already went to null), then there is nothing else to do here.
294 if (isNotUniqued()) return;
296 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
298 // Remove "this" from the context map. FoldingSet doesn't have to reprofile
299 // this node to remove it, so we don't care what state the operands are in.
300 pImpl->MDNodeSet.RemoveNode(this);
302 // If we are dropping an argument to null, we choose to not unique the MDNode
303 // anymore. This commonly occurs during destruction, and uniquing these
304 // brings little reuse.
310 // Now that the node is out of the folding set, get ready to reinsert it.
311 // First, check to see if another node with the same operands already exists
312 // in the set. If it doesn't exist, this returns the position to insert it.
316 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
319 N->replaceAllUsesWith(this);
321 N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
322 assert(N == 0 && "shouldn't be in the map now!"); (void)N;
325 // InsertPoint will have been set by the FindNodeOrInsertPos call.
326 pImpl->MDNodeSet.InsertNode(this, InsertPoint);
329 //===----------------------------------------------------------------------===//
330 // NamedMDNode implementation.
333 static SmallVector<TrackingVH<MDNode>, 4> &getNMDOps(void *Operands) {
334 return *(SmallVector<TrackingVH<MDNode>, 4>*)Operands;
337 NamedMDNode::NamedMDNode(const Twine &N)
338 : Name(N.str()), Parent(0),
339 Operands(new SmallVector<TrackingVH<MDNode>, 4>()) {
342 NamedMDNode::~NamedMDNode() {
344 delete &getNMDOps(Operands);
347 /// getNumOperands - Return number of NamedMDNode operands.
348 unsigned NamedMDNode::getNumOperands() const {
349 return (unsigned)getNMDOps(Operands).size();
352 /// getOperand - Return specified operand.
353 MDNode *NamedMDNode::getOperand(unsigned i) const {
354 assert(i < getNumOperands() && "Invalid Operand number!");
355 return dyn_cast<MDNode>(&*getNMDOps(Operands)[i]);
358 /// addOperand - Add metadata Operand.
359 void NamedMDNode::addOperand(MDNode *M) {
360 getNMDOps(Operands).push_back(TrackingVH<MDNode>(M));
363 /// eraseFromParent - Drop all references and remove the node from parent
365 void NamedMDNode::eraseFromParent() {
366 getParent()->eraseNamedMetadata(this);
369 /// dropAllReferences - Remove all uses and clear node vector.
370 void NamedMDNode::dropAllReferences() {
371 getNMDOps(Operands).clear();
374 /// getName - Return a constant reference to this named metadata's name.
375 StringRef NamedMDNode::getName() const {
376 return StringRef(Name);
379 //===----------------------------------------------------------------------===//
380 // Instruction Metadata method implementations.
383 void Instruction::setMetadata(const char *Kind, MDNode *Node) {
384 if (Node == 0 && !hasMetadata()) return;
385 setMetadata(getContext().getMDKindID(Kind), Node);
388 MDNode *Instruction::getMetadataImpl(const char *Kind) const {
389 return getMetadataImpl(getContext().getMDKindID(Kind));
392 /// setMetadata - Set the metadata of of the specified kind to the specified
393 /// node. This updates/replaces metadata if already present, or removes it if
395 void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
396 if (Node == 0 && !hasMetadata()) return;
398 // Handle 'dbg' as a special case since it is not stored in the hash table.
399 if (KindID == LLVMContext::MD_dbg) {
400 DbgLoc = DebugLoc::getFromDILocation(Node);
404 // Handle the case when we're adding/updating metadata on an instruction.
406 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
407 assert(!Info.empty() == hasMetadataHashEntry() &&
408 "HasMetadata bit is wonked");
410 setHasMetadataHashEntry(true);
412 // Handle replacement of an existing value.
413 for (unsigned i = 0, e = Info.size(); i != e; ++i)
414 if (Info[i].first == KindID) {
415 Info[i].second = Node;
420 // No replacement, just add it to the list.
421 Info.push_back(std::make_pair(KindID, Node));
425 // Otherwise, we're removing metadata from an instruction.
426 assert(hasMetadataHashEntry() &&
427 getContext().pImpl->MetadataStore.count(this) &&
428 "HasMetadata bit out of date!");
429 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
431 // Common case is removing the only entry.
432 if (Info.size() == 1 && Info[0].first == KindID) {
433 getContext().pImpl->MetadataStore.erase(this);
434 setHasMetadataHashEntry(false);
438 // Handle removal of an existing value.
439 for (unsigned i = 0, e = Info.size(); i != e; ++i)
440 if (Info[i].first == KindID) {
441 Info[i] = Info.back();
443 assert(!Info.empty() && "Removing last entry should be handled above");
446 // Otherwise, removing an entry that doesn't exist on the instruction.
449 MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
450 // Handle 'dbg' as a special case since it is not stored in the hash table.
451 if (KindID == LLVMContext::MD_dbg)
452 return DbgLoc.getAsMDNode(getContext());
454 if (!hasMetadataHashEntry()) return 0;
456 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
457 assert(!Info.empty() && "bit out of sync with hash table");
459 for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end();
461 if (I->first == KindID)
466 void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
467 MDNode*> > &Result) const {
470 // Handle 'dbg' as a special case since it is not stored in the hash table.
471 if (!DbgLoc.isUnknown()) {
472 Result.push_back(std::make_pair((unsigned)LLVMContext::MD_dbg,
473 DbgLoc.getAsMDNode(getContext())));
474 if (!hasMetadataHashEntry()) return;
477 assert(hasMetadataHashEntry() &&
478 getContext().pImpl->MetadataStore.count(this) &&
479 "Shouldn't have called this");
480 const LLVMContextImpl::MDMapTy &Info =
481 getContext().pImpl->MetadataStore.find(this)->second;
482 assert(!Info.empty() && "Shouldn't have called this");
484 Result.append(Info.begin(), Info.end());
486 // Sort the resulting array so it is stable.
487 if (Result.size() > 1)
488 array_pod_sort(Result.begin(), Result.end());
492 getAllMetadataOtherThanDebugLocImpl(SmallVectorImpl<std::pair<unsigned,
493 MDNode*> > &Result) const {
495 assert(hasMetadataHashEntry() &&
496 getContext().pImpl->MetadataStore.count(this) &&
497 "Shouldn't have called this");
498 const LLVMContextImpl::MDMapTy &Info =
499 getContext().pImpl->MetadataStore.find(this)->second;
500 assert(!Info.empty() && "Shouldn't have called this");
502 Result.append(Info.begin(), Info.end());
504 // Sort the resulting array so it is stable.
505 if (Result.size() > 1)
506 array_pod_sort(Result.begin(), Result.end());
510 /// clearMetadataHashEntries - Clear all hashtable-based metadata from
511 /// this instruction.
512 void Instruction::clearMetadataHashEntries() {
513 assert(hasMetadataHashEntry() && "Caller should check");
514 getContext().pImpl->MetadataStore.erase(this);
515 setHasMetadataHashEntry(false);