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/LeakDetector.h"
24 #include "llvm/Support/ValueHandle.h"
27 //===----------------------------------------------------------------------===//
28 // MDString implementation.
31 MDString::MDString(LLVMContext
&C
, StringRef S
)
32 : Value(Type::getMetadataTy(C
), Value::MDStringVal
), Str(S
) {}
34 MDString
*MDString::get(LLVMContext
&Context
, StringRef Str
) {
35 LLVMContextImpl
*pImpl
= Context
.pImpl
;
36 StringMapEntry
<MDString
*> &Entry
=
37 pImpl
->MDStringCache
.GetOrCreateValue(Str
);
38 MDString
*&S
= Entry
.getValue();
39 if (!S
) S
= new MDString(Context
, Entry
.getKey());
43 //===----------------------------------------------------------------------===//
44 // MDNodeOperand implementation.
47 // Use CallbackVH to hold MDNode operands.
49 class MDNodeOperand
: public CallbackVH
{
52 MDNodeOperand(Value
*V
, MDNode
*P
) : CallbackVH(V
), Parent(P
) {}
59 virtual void deleted();
60 virtual void allUsesReplacedWith(Value
*NV
);
62 } // end namespace llvm.
65 void MDNodeOperand::deleted() {
66 Parent
->replaceOperand(this, 0);
69 void MDNodeOperand::allUsesReplacedWith(Value
*NV
) {
70 Parent
->replaceOperand(this, NV
);
75 //===----------------------------------------------------------------------===//
76 // MDNode implementation.
79 /// getOperandPtr - Helper function to get the MDNodeOperand's coallocated on
80 /// the end of the MDNode.
81 static MDNodeOperand
*getOperandPtr(MDNode
*N
, unsigned Op
) {
82 // Use <= instead of < to permit a one-past-the-end address.
83 assert(Op
<= N
->getNumOperands() && "Invalid operand number");
84 return reinterpret_cast<MDNodeOperand
*>(N
+1)+Op
;
87 MDNode::MDNode(LLVMContext
&C
, Value
*const *Vals
, unsigned NumVals
,
89 : Value(Type::getMetadataTy(C
), Value::MDNodeVal
) {
90 NumOperands
= NumVals
;
93 setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit
);
95 // Initialize the operand list, which is co-allocated on the end of the node.
96 for (MDNodeOperand
*Op
= getOperandPtr(this, 0), *E
= Op
+NumOperands
;
97 Op
!= E
; ++Op
, ++Vals
)
98 new (Op
) MDNodeOperand(*Vals
, this);
102 /// ~MDNode - Destroy MDNode.
104 assert((getSubclassDataFromValue() & DestroyFlag
) != 0 &&
105 "Not being destroyed through destroy()?");
106 LLVMContextImpl
*pImpl
= getType()->getContext().pImpl
;
107 if (isNotUniqued()) {
108 pImpl
->NonUniquedMDNodes
.erase(this);
110 pImpl
->MDNodeSet
.RemoveNode(this);
113 // Destroy the operands.
114 for (MDNodeOperand
*Op
= getOperandPtr(this, 0), *E
= Op
+NumOperands
;
116 Op
->~MDNodeOperand();
119 static const Function
*getFunctionForValue(Value
*V
) {
121 if (Instruction
*I
= dyn_cast
<Instruction
>(V
)) {
122 BasicBlock
*BB
= I
->getParent();
123 return BB
? BB
->getParent() : 0;
125 if (Argument
*A
= dyn_cast
<Argument
>(V
))
126 return A
->getParent();
127 if (BasicBlock
*BB
= dyn_cast
<BasicBlock
>(V
))
128 return BB
->getParent();
129 if (MDNode
*MD
= dyn_cast
<MDNode
>(V
))
130 return MD
->getFunction();
135 static const Function
*assertLocalFunction(const MDNode
*N
) {
136 if (!N
->isFunctionLocal()) return 0;
138 // FIXME: This does not handle cyclic function local metadata.
139 const Function
*F
= 0, *NewF
= 0;
140 for (unsigned i
= 0, e
= N
->getNumOperands(); i
!= e
; ++i
) {
141 if (Value
*V
= N
->getOperand(i
)) {
142 if (MDNode
*MD
= dyn_cast
<MDNode
>(V
))
143 NewF
= assertLocalFunction(MD
);
145 NewF
= getFunctionForValue(V
);
150 assert((NewF
== 0 || F
== NewF
) &&"inconsistent function-local metadata");
156 // getFunction - If this metadata is function-local and recursively has a
157 // function-local operand, return the first such operand's parent function.
158 // Otherwise, return null. getFunction() should not be used for performance-
159 // critical code because it recursively visits all the MDNode's operands.
160 const Function
*MDNode::getFunction() const {
162 return assertLocalFunction(this);
164 if (!isFunctionLocal()) return NULL
;
165 for (unsigned i
= 0, e
= getNumOperands(); i
!= e
; ++i
)
166 if (const Function
*F
= getFunctionForValue(getOperand(i
)))
171 // destroy - Delete this node. Only when there are no uses.
172 void MDNode::destroy() {
173 setValueSubclassData(getSubclassDataFromValue() | DestroyFlag
);
174 // Placement delete, the free the memory.
179 /// isFunctionLocalValue - Return true if this is a value that would require a
180 /// function-local MDNode.
181 static bool isFunctionLocalValue(Value
*V
) {
182 return isa
<Instruction
>(V
) || isa
<Argument
>(V
) || isa
<BasicBlock
>(V
) ||
183 (isa
<MDNode
>(V
) && cast
<MDNode
>(V
)->isFunctionLocal());
186 MDNode
*MDNode::getMDNode(LLVMContext
&Context
, Value
*const *Vals
,
187 unsigned NumVals
, FunctionLocalness FL
,
189 LLVMContextImpl
*pImpl
= Context
.pImpl
;
191 // Add all the operand pointers. Note that we don't have to add the
192 // isFunctionLocal bit because that's implied by the operands.
193 // Note that if the operands are later nulled out, the node will be
194 // removed from the uniquing map.
196 for (unsigned i
= 0; i
!= NumVals
; ++i
)
197 ID
.AddPointer(Vals
[i
]);
202 if ((N
= pImpl
->MDNodeSet
.FindNodeOrInsertPos(ID
, InsertPoint
)))
205 bool isFunctionLocal
= false;
208 for (unsigned i
= 0; i
!= NumVals
; ++i
) {
211 if (isFunctionLocalValue(V
)) {
212 isFunctionLocal
= true;
218 isFunctionLocal
= false;
221 isFunctionLocal
= true;
225 // Coallocate space for the node and Operands together, then placement new.
226 void *Ptr
= malloc(sizeof(MDNode
)+NumVals
*sizeof(MDNodeOperand
));
227 N
= new (Ptr
) MDNode(Context
, Vals
, NumVals
, isFunctionLocal
);
229 // InsertPoint will have been set by the FindNodeOrInsertPos call.
230 pImpl
->MDNodeSet
.InsertNode(N
, InsertPoint
);
235 MDNode
*MDNode::get(LLVMContext
&Context
, ArrayRef
<Value
*> Vals
) {
236 return getMDNode(Context
, Vals
.data(), Vals
.size(), FL_Unknown
);
238 MDNode
*MDNode::get(LLVMContext
&Context
, Value
*const* Vals
, unsigned NumVals
) {
239 return getMDNode(Context
, Vals
, NumVals
, FL_Unknown
);
242 MDNode
*MDNode::getWhenValsUnresolved(LLVMContext
&Context
, Value
*const *Vals
,
243 unsigned NumVals
, bool isFunctionLocal
) {
244 return getMDNode(Context
, Vals
, NumVals
, isFunctionLocal
? FL_Yes
: FL_No
);
247 MDNode
*MDNode::getIfExists(LLVMContext
&Context
, Value
*const *Vals
,
249 return getMDNode(Context
, Vals
, NumVals
, FL_Unknown
, false);
252 MDNode
*MDNode::getTemporary(LLVMContext
&Context
, Value
*const *Vals
,
254 MDNode
*N
= (MDNode
*)malloc(sizeof(MDNode
)+NumVals
*sizeof(MDNodeOperand
));
255 N
= new (N
) MDNode(Context
, Vals
, NumVals
, FL_No
);
256 N
->setValueSubclassData(N
->getSubclassDataFromValue() |
258 LeakDetector::addGarbageObject(N
);
262 void MDNode::deleteTemporary(MDNode
*N
) {
263 assert(N
->use_empty() && "Temporary MDNode has uses!");
264 assert(!N
->getContext().pImpl
->MDNodeSet
.RemoveNode(N
) &&
265 "Deleting a non-temporary uniqued node!");
266 assert(!N
->getContext().pImpl
->NonUniquedMDNodes
.erase(N
) &&
267 "Deleting a non-temporary non-uniqued node!");
268 assert((N
->getSubclassDataFromValue() & NotUniquedBit
) &&
269 "Temporary MDNode does not have NotUniquedBit set!");
270 assert((N
->getSubclassDataFromValue() & DestroyFlag
) == 0 &&
271 "Temporary MDNode has DestroyFlag set!");
272 LeakDetector::removeGarbageObject(N
);
276 /// getOperand - Return specified operand.
277 Value
*MDNode::getOperand(unsigned i
) const {
278 return *getOperandPtr(const_cast<MDNode
*>(this), i
);
281 void MDNode::Profile(FoldingSetNodeID
&ID
) const {
282 // Add all the operand pointers. Note that we don't have to add the
283 // isFunctionLocal bit because that's implied by the operands.
284 // Note that if the operands are later nulled out, the node will be
285 // removed from the uniquing map.
286 for (unsigned i
= 0, e
= getNumOperands(); i
!= e
; ++i
)
287 ID
.AddPointer(getOperand(i
));
290 void MDNode::setIsNotUniqued() {
291 setValueSubclassData(getSubclassDataFromValue() | NotUniquedBit
);
292 LLVMContextImpl
*pImpl
= getType()->getContext().pImpl
;
293 pImpl
->NonUniquedMDNodes
.insert(this);
296 // Replace value from this node's operand list.
297 void MDNode::replaceOperand(MDNodeOperand
*Op
, Value
*To
) {
300 // If is possible that someone did GV->RAUW(inst), replacing a global variable
301 // with an instruction or some other function-local object. If this is a
302 // non-function-local MDNode, it can't point to a function-local object.
303 // Handle this case by implicitly dropping the MDNode reference to null.
304 // Likewise if the MDNode is function-local but for a different function.
305 if (To
&& isFunctionLocalValue(To
)) {
306 if (!isFunctionLocal())
309 const Function
*F
= getFunction();
310 const Function
*FV
= getFunctionForValue(To
);
311 // Metadata can be function-local without having an associated function.
312 // So only consider functions to have changed if non-null.
313 if (F
&& FV
&& F
!= FV
)
321 // Update the operand.
324 // If this node is already not being uniqued (because one of the operands
325 // already went to null), then there is nothing else to do here.
326 if (isNotUniqued()) return;
328 LLVMContextImpl
*pImpl
= getType()->getContext().pImpl
;
330 // Remove "this" from the context map. FoldingSet doesn't have to reprofile
331 // this node to remove it, so we don't care what state the operands are in.
332 pImpl
->MDNodeSet
.RemoveNode(this);
334 // If we are dropping an argument to null, we choose to not unique the MDNode
335 // anymore. This commonly occurs during destruction, and uniquing these
336 // brings little reuse. Also, this means we don't need to include
337 // isFunctionLocal bits in FoldingSetNodeIDs for MDNodes.
343 // Now that the node is out of the folding set, get ready to reinsert it.
344 // First, check to see if another node with the same operands already exists
345 // in the set. If so, then this node is redundant.
349 if (MDNode
*N
= pImpl
->MDNodeSet
.FindNodeOrInsertPos(ID
, InsertPoint
)) {
350 replaceAllUsesWith(N
);
355 // InsertPoint will have been set by the FindNodeOrInsertPos call.
356 pImpl
->MDNodeSet
.InsertNode(this, InsertPoint
);
358 // If this MDValue was previously function-local but no longer is, clear
359 // its function-local flag.
360 if (isFunctionLocal() && !isFunctionLocalValue(To
)) {
361 bool isStillFunctionLocal
= false;
362 for (unsigned i
= 0, e
= getNumOperands(); i
!= e
; ++i
) {
363 Value
*V
= getOperand(i
);
365 if (isFunctionLocalValue(V
)) {
366 isStillFunctionLocal
= true;
370 if (!isStillFunctionLocal
)
371 setValueSubclassData(getSubclassDataFromValue() & ~FunctionLocalBit
);
375 //===----------------------------------------------------------------------===//
376 // NamedMDNode implementation.
379 static SmallVector
<TrackingVH
<MDNode
>, 4> &getNMDOps(void *Operands
) {
380 return *(SmallVector
<TrackingVH
<MDNode
>, 4>*)Operands
;
383 NamedMDNode::NamedMDNode(const Twine
&N
)
384 : Name(N
.str()), Parent(0),
385 Operands(new SmallVector
<TrackingVH
<MDNode
>, 4>()) {
388 NamedMDNode::~NamedMDNode() {
390 delete &getNMDOps(Operands
);
393 /// getNumOperands - Return number of NamedMDNode operands.
394 unsigned NamedMDNode::getNumOperands() const {
395 return (unsigned)getNMDOps(Operands
).size();
398 /// getOperand - Return specified operand.
399 MDNode
*NamedMDNode::getOperand(unsigned i
) const {
400 assert(i
< getNumOperands() && "Invalid Operand number!");
401 return dyn_cast
<MDNode
>(&*getNMDOps(Operands
)[i
]);
404 /// addOperand - Add metadata Operand.
405 void NamedMDNode::addOperand(MDNode
*M
) {
406 assert(!M
->isFunctionLocal() &&
407 "NamedMDNode operands must not be function-local!");
408 getNMDOps(Operands
).push_back(TrackingVH
<MDNode
>(M
));
411 /// eraseFromParent - Drop all references and remove the node from parent
413 void NamedMDNode::eraseFromParent() {
414 getParent()->eraseNamedMetadata(this);
417 /// dropAllReferences - Remove all uses and clear node vector.
418 void NamedMDNode::dropAllReferences() {
419 getNMDOps(Operands
).clear();
422 /// getName - Return a constant reference to this named metadata's name.
423 StringRef
NamedMDNode::getName() const {
424 return StringRef(Name
);
427 //===----------------------------------------------------------------------===//
428 // Instruction Metadata method implementations.
431 void Instruction::setMetadata(const char *Kind
, MDNode
*Node
) {
432 if (Node
== 0 && !hasMetadata()) return;
433 setMetadata(getContext().getMDKindID(Kind
), Node
);
436 MDNode
*Instruction::getMetadataImpl(const char *Kind
) const {
437 return getMetadataImpl(getContext().getMDKindID(Kind
));
440 /// setMetadata - Set the metadata of of the specified kind to the specified
441 /// node. This updates/replaces metadata if already present, or removes it if
443 void Instruction::setMetadata(unsigned KindID
, MDNode
*Node
) {
444 if (Node
== 0 && !hasMetadata()) return;
446 // Handle 'dbg' as a special case since it is not stored in the hash table.
447 if (KindID
== LLVMContext::MD_dbg
) {
448 DbgLoc
= DebugLoc::getFromDILocation(Node
);
452 // Handle the case when we're adding/updating metadata on an instruction.
454 LLVMContextImpl::MDMapTy
&Info
= getContext().pImpl
->MetadataStore
[this];
455 assert(!Info
.empty() == hasMetadataHashEntry() &&
456 "HasMetadata bit is wonked");
458 setHasMetadataHashEntry(true);
460 // Handle replacement of an existing value.
461 for (unsigned i
= 0, e
= Info
.size(); i
!= e
; ++i
)
462 if (Info
[i
].first
== KindID
) {
463 Info
[i
].second
= Node
;
468 // No replacement, just add it to the list.
469 Info
.push_back(std::make_pair(KindID
, Node
));
473 // Otherwise, we're removing metadata from an instruction.
474 assert(hasMetadataHashEntry() &&
475 getContext().pImpl
->MetadataStore
.count(this) &&
476 "HasMetadata bit out of date!");
477 LLVMContextImpl::MDMapTy
&Info
= getContext().pImpl
->MetadataStore
[this];
479 // Common case is removing the only entry.
480 if (Info
.size() == 1 && Info
[0].first
== KindID
) {
481 getContext().pImpl
->MetadataStore
.erase(this);
482 setHasMetadataHashEntry(false);
486 // Handle removal of an existing value.
487 for (unsigned i
= 0, e
= Info
.size(); i
!= e
; ++i
)
488 if (Info
[i
].first
== KindID
) {
489 Info
[i
] = Info
.back();
491 assert(!Info
.empty() && "Removing last entry should be handled above");
494 // Otherwise, removing an entry that doesn't exist on the instruction.
497 MDNode
*Instruction::getMetadataImpl(unsigned KindID
) const {
498 // Handle 'dbg' as a special case since it is not stored in the hash table.
499 if (KindID
== LLVMContext::MD_dbg
)
500 return DbgLoc
.getAsMDNode(getContext());
502 if (!hasMetadataHashEntry()) return 0;
504 LLVMContextImpl::MDMapTy
&Info
= getContext().pImpl
->MetadataStore
[this];
505 assert(!Info
.empty() && "bit out of sync with hash table");
507 for (LLVMContextImpl::MDMapTy::iterator I
= Info
.begin(), E
= Info
.end();
509 if (I
->first
== KindID
)
514 void Instruction::getAllMetadataImpl(SmallVectorImpl
<std::pair
<unsigned,
515 MDNode
*> > &Result
) const {
518 // Handle 'dbg' as a special case since it is not stored in the hash table.
519 if (!DbgLoc
.isUnknown()) {
520 Result
.push_back(std::make_pair((unsigned)LLVMContext::MD_dbg
,
521 DbgLoc
.getAsMDNode(getContext())));
522 if (!hasMetadataHashEntry()) return;
525 assert(hasMetadataHashEntry() &&
526 getContext().pImpl
->MetadataStore
.count(this) &&
527 "Shouldn't have called this");
528 const LLVMContextImpl::MDMapTy
&Info
=
529 getContext().pImpl
->MetadataStore
.find(this)->second
;
530 assert(!Info
.empty() && "Shouldn't have called this");
532 Result
.append(Info
.begin(), Info
.end());
534 // Sort the resulting array so it is stable.
535 if (Result
.size() > 1)
536 array_pod_sort(Result
.begin(), Result
.end());
540 getAllMetadataOtherThanDebugLocImpl(SmallVectorImpl
<std::pair
<unsigned,
541 MDNode
*> > &Result
) const {
543 assert(hasMetadataHashEntry() &&
544 getContext().pImpl
->MetadataStore
.count(this) &&
545 "Shouldn't have called this");
546 const LLVMContextImpl::MDMapTy
&Info
=
547 getContext().pImpl
->MetadataStore
.find(this)->second
;
548 assert(!Info
.empty() && "Shouldn't have called this");
550 Result
.append(Info
.begin(), Info
.end());
552 // Sort the resulting array so it is stable.
553 if (Result
.size() > 1)
554 array_pod_sort(Result
.begin(), Result
.end());
558 /// clearMetadataHashEntries - Clear all hashtable-based metadata from
559 /// this instruction.
560 void Instruction::clearMetadataHashEntries() {
561 assert(hasMetadataHashEntry() && "Caller should check");
562 getContext().pImpl
->MetadataStore
.erase(this);
563 setHasMetadataHashEntry(false);