blob: d751064e2227bb1ce385340be55ac489ea61967a [file] [log] [blame]
Devang Patel0a9f7b92009-07-28 21:49:47 +00001//===-- 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
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000014#include "llvm/IR/Metadata.h"
Chris Lattner37da0ad2009-12-28 08:24:16 +000015#include "LLVMContextImpl.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "SymbolTableListTraitsImpl.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallString.h"
20#include "llvm/ADT/StringMap.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000021#include "llvm/IR/Instruction.h"
22#include "llvm/IR/LLVMContext.h"
23#include "llvm/IR/Module.h"
Hal Finkel7b4ff932012-06-16 20:33:37 +000024#include "llvm/Support/ConstantRange.h"
Dan Gohman489b29b2010-08-20 22:02:26 +000025#include "llvm/Support/LeakDetector.h"
Chris Lattner37da0ad2009-12-28 08:24:16 +000026#include "llvm/Support/ValueHandle.h"
Devang Patel0a9f7b92009-07-28 21:49:47 +000027using namespace llvm;
28
29//===----------------------------------------------------------------------===//
Chris Lattnerb2a33b462009-10-19 07:10:59 +000030// MDString implementation.
Owen Anderson647e3012009-07-31 21:35:40 +000031//
Chris Lattner5e9cd432009-12-28 08:30:43 +000032
David Blaikie2d24e2a2011-12-20 02:50:00 +000033void MDString::anchor() { }
34
Bill Wendling3ecb4472012-04-10 20:12:16 +000035MDString::MDString(LLVMContext &C)
36 : Value(Type::getMetadataTy(C), Value::MDStringVal) {}
Chris Lattner5e9cd432009-12-28 08:30:43 +000037
Devang Patel49b63a12009-10-22 00:10:15 +000038MDString *MDString::get(LLVMContext &Context, StringRef Str) {
Owen Anderson647e3012009-07-31 21:35:40 +000039 LLVMContextImpl *pImpl = Context.pImpl;
Bill Wendling3ecb4472012-04-10 20:12:16 +000040 StringMapEntry<Value*> &Entry =
Owen Anderson647e3012009-07-31 21:35:40 +000041 pImpl->MDStringCache.GetOrCreateValue(Str);
Bill Wendling3ecb4472012-04-10 20:12:16 +000042 Value *&S = Entry.getValue();
43 if (!S) S = new MDString(Context);
44 S->setValueName(&Entry);
45 return cast<MDString>(S);
Owen Anderson647e3012009-07-31 21:35:40 +000046}
47
48//===----------------------------------------------------------------------===//
Chris Lattner5d0cacd2009-12-31 01:22:29 +000049// MDNodeOperand implementation.
Chris Lattnerc5e08a92009-12-28 07:41:54 +000050//
51
Chris Lattner5d0cacd2009-12-31 01:22:29 +000052// Use CallbackVH to hold MDNode operands.
Chris Lattnerc5e08a92009-12-28 07:41:54 +000053namespace llvm {
Chris Lattner5d0cacd2009-12-31 01:22:29 +000054class MDNodeOperand : public CallbackVH {
Bill Wendling69b2c712012-04-08 10:20:49 +000055 MDNode *getParent() {
56 MDNodeOperand *Cur = this;
57
58 while (Cur->getValPtrInt() != 1)
59 --Cur;
60
61 assert(Cur->getValPtrInt() == 1 &&
62 "Couldn't find the beginning of the operand list!");
63 return reinterpret_cast<MDNode*>(Cur) - 1;
64 }
65
Chris Lattnerc5e08a92009-12-28 07:41:54 +000066public:
Bill Wendling69b2c712012-04-08 10:20:49 +000067 MDNodeOperand(Value *V) : CallbackVH(V) {}
Chris Lattner5d0cacd2009-12-31 01:22:29 +000068 ~MDNodeOperand() {}
Mikhail Glushenkov0d75d872010-01-10 18:48:49 +000069
Bill Wendling48663632012-04-26 00:38:42 +000070 void set(Value *V) {
71 unsigned IsFirst = this->getValPtrInt();
72 this->setValPtr(V);
73 this->setAsFirstOperand(IsFirst);
74 }
Bill Wendling69b2c712012-04-08 10:20:49 +000075
76 /// setAsFirstOperand - Accessor method to mark the operand as the first in
77 /// the list.
78 void setAsFirstOperand(unsigned V) { this->setValPtrInt(V); }
Mikhail Glushenkov0d75d872010-01-10 18:48:49 +000079
Chris Lattnerc5e08a92009-12-28 07:41:54 +000080 virtual void deleted();
81 virtual void allUsesReplacedWith(Value *NV);
82};
83} // end namespace llvm.
84
85
Chris Lattner5d0cacd2009-12-31 01:22:29 +000086void MDNodeOperand::deleted() {
Bill Wendling69b2c712012-04-08 10:20:49 +000087 getParent()->replaceOperand(this, 0);
Chris Lattnerc5e08a92009-12-28 07:41:54 +000088}
89
Chris Lattner5d0cacd2009-12-31 01:22:29 +000090void MDNodeOperand::allUsesReplacedWith(Value *NV) {
Bill Wendling69b2c712012-04-08 10:20:49 +000091 getParent()->replaceOperand(this, NV);
Chris Lattnerc5e08a92009-12-28 07:41:54 +000092}
93
Chris Lattnerc5e08a92009-12-28 07:41:54 +000094//===----------------------------------------------------------------------===//
Chris Lattnerb2a33b462009-10-19 07:10:59 +000095// MDNode implementation.
Devang Patel0a9f7b92009-07-28 21:49:47 +000096//
Chris Lattnerc5e08a92009-12-28 07:41:54 +000097
Chris Lattner5d0cacd2009-12-31 01:22:29 +000098/// getOperandPtr - Helper function to get the MDNodeOperand's coallocated on
Chris Lattnerb76359e2009-12-31 01:05:46 +000099/// the end of the MDNode.
Chris Lattner5d0cacd2009-12-31 01:22:29 +0000100static MDNodeOperand *getOperandPtr(MDNode *N, unsigned Op) {
Dan Gohmanac809752010-07-13 19:33:27 +0000101 // Use <= instead of < to permit a one-past-the-end address.
102 assert(Op <= N->getNumOperands() && "Invalid operand number");
Bill Wendling48663632012-04-26 00:38:42 +0000103 return reinterpret_cast<MDNodeOperand*>(N + 1) + Op;
Chris Lattnerf2410182009-12-28 09:12:35 +0000104}
105
Eric Christopherf32a9602012-02-15 09:09:29 +0000106void MDNode::replaceOperandWith(unsigned i, Value *Val) {
107 MDNodeOperand *Op = getOperandPtr(this, i);
108 replaceOperand(Op, Val);
109}
110
Jay Foadec9186b2011-04-21 19:59:31 +0000111MDNode::MDNode(LLVMContext &C, ArrayRef<Value*> Vals, bool isFunctionLocal)
Devang Patelbc5201f2010-01-22 22:52:10 +0000112: Value(Type::getMetadataTy(C), Value::MDNodeVal) {
Jay Foadec9186b2011-04-21 19:59:31 +0000113 NumOperands = Vals.size();
Mikhail Glushenkov0d75d872010-01-10 18:48:49 +0000114
Victor Hernandez5d301622009-12-18 20:09:14 +0000115 if (isFunctionLocal)
Chris Lattnercafe9bb2009-12-29 02:14:09 +0000116 setValueSubclassData(getSubclassDataFromValue() | FunctionLocalBit);
Chris Lattnerb76359e2009-12-31 01:05:46 +0000117
118 // Initialize the operand list, which is co-allocated on the end of the node.
Jay Foadec9186b2011-04-21 19:59:31 +0000119 unsigned i = 0;
Chris Lattner5d0cacd2009-12-31 01:22:29 +0000120 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
Bill Wendling69b2c712012-04-08 10:20:49 +0000121 Op != E; ++Op, ++i) {
122 new (Op) MDNodeOperand(Vals[i]);
123
124 // Mark the first MDNodeOperand as being the first in the list of operands.
125 if (i == 0)
126 Op->setAsFirstOperand(1);
127 }
Devang Patel0a9f7b92009-07-28 21:49:47 +0000128}
129
Chris Lattnerb76359e2009-12-31 01:05:46 +0000130/// ~MDNode - Destroy MDNode.
131MDNode::~MDNode() {
Mikhail Glushenkov0d75d872010-01-10 18:48:49 +0000132 assert((getSubclassDataFromValue() & DestroyFlag) != 0 &&
Chris Lattnerb76359e2009-12-31 01:05:46 +0000133 "Not being destroyed through destroy()?");
Jeffrey Yasskin6f555ca2010-03-13 01:26:15 +0000134 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
135 if (isNotUniqued()) {
136 pImpl->NonUniquedMDNodes.erase(this);
137 } else {
Chris Lattnerb76359e2009-12-31 01:05:46 +0000138 pImpl->MDNodeSet.RemoveNode(this);
139 }
Mikhail Glushenkov0d75d872010-01-10 18:48:49 +0000140
Chris Lattnerb76359e2009-12-31 01:05:46 +0000141 // Destroy the operands.
Chris Lattner5d0cacd2009-12-31 01:22:29 +0000142 for (MDNodeOperand *Op = getOperandPtr(this, 0), *E = Op+NumOperands;
Chris Lattnerb76359e2009-12-31 01:05:46 +0000143 Op != E; ++Op)
Chris Lattner5d0cacd2009-12-31 01:22:29 +0000144 Op->~MDNodeOperand();
Chris Lattnerb76359e2009-12-31 01:05:46 +0000145}
146
Victor Hernandez8fffff52010-01-20 04:45:57 +0000147static const Function *getFunctionForValue(Value *V) {
148 if (!V) return NULL;
Duncan Sands203f7cb2010-05-04 12:43:36 +0000149 if (Instruction *I = dyn_cast<Instruction>(V)) {
150 BasicBlock *BB = I->getParent();
151 return BB ? BB->getParent() : 0;
152 }
Chris Lattnerd3a6d902010-01-21 21:01:47 +0000153 if (Argument *A = dyn_cast<Argument>(V))
154 return A->getParent();
Duncan Sands203f7cb2010-05-04 12:43:36 +0000155 if (BasicBlock *BB = dyn_cast<BasicBlock>(V))
156 return BB->getParent();
157 if (MDNode *MD = dyn_cast<MDNode>(V))
158 return MD->getFunction();
Victor Hernandez8fffff52010-01-20 04:45:57 +0000159 return NULL;
160}
161
Victor Hernandeze05f66e2010-01-14 20:12:34 +0000162#ifndef NDEBUG
Victor Hernandez8fffff52010-01-20 04:45:57 +0000163static const Function *assertLocalFunction(const MDNode *N) {
Chris Lattnerd3a6d902010-01-21 21:01:47 +0000164 if (!N->isFunctionLocal()) return 0;
Victor Hernandeze05f66e2010-01-14 20:12:34 +0000165
Devang Patel6db23892010-07-06 21:05:17 +0000166 // FIXME: This does not handle cyclic function local metadata.
Chris Lattnerd3a6d902010-01-21 21:01:47 +0000167 const Function *F = 0, *NewF = 0;
Victor Hernandezc7650b42010-01-14 01:45:14 +0000168 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Victor Hernandez8fffff52010-01-20 04:45:57 +0000169 if (Value *V = N->getOperand(i)) {
Chris Lattnerd3a6d902010-01-21 21:01:47 +0000170 if (MDNode *MD = dyn_cast<MDNode>(V))
171 NewF = assertLocalFunction(MD);
172 else
173 NewF = getFunctionForValue(V);
Victor Hernandez54630e12010-01-18 20:36:54 +0000174 }
Chris Lattnerd3a6d902010-01-21 21:01:47 +0000175 if (F == 0)
176 F = NewF;
177 else
178 assert((NewF == 0 || F == NewF) &&"inconsistent function-local metadata");
Victor Hernandezc7650b42010-01-14 01:45:14 +0000179 }
Victor Hernandezc7650b42010-01-14 01:45:14 +0000180 return F;
181}
Victor Hernandez54630e12010-01-18 20:36:54 +0000182#endif
Victor Hernandezc7650b42010-01-14 01:45:14 +0000183
184// getFunction - If this metadata is function-local and recursively has a
185// function-local operand, return the first such operand's parent function.
Victor Hernandez6cead782010-01-18 22:55:08 +0000186// Otherwise, return null. getFunction() should not be used for performance-
187// critical code because it recursively visits all the MDNode's operands.
Victor Hernandez8fffff52010-01-20 04:45:57 +0000188const Function *MDNode::getFunction() const {
Victor Hernandez54630e12010-01-18 20:36:54 +0000189#ifndef NDEBUG
190 return assertLocalFunction(this);
David Blaikie4d6ccb52012-01-20 21:51:11 +0000191#else
Victor Hernandezc7650b42010-01-14 01:45:14 +0000192 if (!isFunctionLocal()) return NULL;
Duncan Sandsd29f5282010-05-04 14:25:42 +0000193 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
194 if (const Function *F = getFunctionForValue(getOperand(i)))
195 return F;
Victor Hernandez54630e12010-01-18 20:36:54 +0000196 return NULL;
David Blaikie4d6ccb52012-01-20 21:51:11 +0000197#endif
Victor Hernandezc7650b42010-01-14 01:45:14 +0000198}
199
Chris Lattnerb76359e2009-12-31 01:05:46 +0000200// destroy - Delete this node. Only when there are no uses.
201void MDNode::destroy() {
202 setValueSubclassData(getSubclassDataFromValue() | DestroyFlag);
Eric Christophera61d3a92012-08-14 01:09:10 +0000203 // Placement delete, then free the memory.
Chris Lattnerb76359e2009-12-31 01:05:46 +0000204 this->~MDNode();
205 free(this);
206}
207
Chris Lattnerf3f325b2010-04-28 20:16:12 +0000208/// isFunctionLocalValue - Return true if this is a value that would require a
209/// function-local MDNode.
210static bool isFunctionLocalValue(Value *V) {
211 return isa<Instruction>(V) || isa<Argument>(V) || isa<BasicBlock>(V) ||
212 (isa<MDNode>(V) && cast<MDNode>(V)->isFunctionLocal());
213}
214
Jay Foadec9186b2011-04-21 19:59:31 +0000215MDNode *MDNode::getMDNode(LLVMContext &Context, ArrayRef<Value*> Vals,
216 FunctionLocalness FL, bool Insert) {
Devang Patel5f4ac842009-09-03 01:39:20 +0000217 LLVMContextImpl *pImpl = Context.pImpl;
Dan Gohman7548fb32010-08-24 23:21:12 +0000218
219 // Add all the operand pointers. Note that we don't have to add the
220 // isFunctionLocal bit because that's implied by the operands.
Dan Gohman56b092e2010-08-30 21:18:41 +0000221 // Note that if the operands are later nulled out, the node will be
222 // removed from the uniquing map.
Dan Gohman7548fb32010-08-24 23:21:12 +0000223 FoldingSetNodeID ID;
Jay Foadec9186b2011-04-21 19:59:31 +0000224 for (unsigned i = 0; i != Vals.size(); ++i)
Dan Gohman7548fb32010-08-24 23:21:12 +0000225 ID.AddPointer(Vals[i]);
226
227 void *InsertPoint;
Duncan Sands4000afe2012-03-31 08:20:11 +0000228 MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
229
230 if (N || !Insert)
Dan Gohman7548fb32010-08-24 23:21:12 +0000231 return N;
Duncan Sands4000afe2012-03-31 08:20:11 +0000232
Victor Hernandeze685f232010-01-26 02:36:35 +0000233 bool isFunctionLocal = false;
234 switch (FL) {
235 case FL_Unknown:
Jay Foadec9186b2011-04-21 19:59:31 +0000236 for (unsigned i = 0; i != Vals.size(); ++i) {
Victor Hernandeze685f232010-01-26 02:36:35 +0000237 Value *V = Vals[i];
238 if (!V) continue;
Chris Lattnerf3f325b2010-04-28 20:16:12 +0000239 if (isFunctionLocalValue(V)) {
Victor Hernandeze685f232010-01-26 02:36:35 +0000240 isFunctionLocal = true;
241 break;
Victor Hernandez24e64df2010-01-10 07:14:18 +0000242 }
Victor Hernandez24e64df2010-01-10 07:14:18 +0000243 }
Victor Hernandeze685f232010-01-26 02:36:35 +0000244 break;
245 case FL_No:
246 isFunctionLocal = false;
247 break;
248 case FL_Yes:
249 isFunctionLocal = true;
250 break;
Devang Patel5f4ac842009-09-03 01:39:20 +0000251 }
Victor Hernandeze685f232010-01-26 02:36:35 +0000252
253 // Coallocate space for the node and Operands together, then placement new.
Bill Wendling48663632012-04-26 00:38:42 +0000254 void *Ptr = malloc(sizeof(MDNode) + Vals.size() * sizeof(MDNodeOperand));
Jay Foadec9186b2011-04-21 19:59:31 +0000255 N = new (Ptr) MDNode(Context, Vals, isFunctionLocal);
Victor Hernandeze685f232010-01-26 02:36:35 +0000256
Benjamin Kramer611afc02012-04-11 14:06:54 +0000257 // Cache the operand hash.
258 N->Hash = ID.ComputeHash();
259
Victor Hernandeze685f232010-01-26 02:36:35 +0000260 // InsertPoint will have been set by the FindNodeOrInsertPos call.
261 pImpl->MDNodeSet.InsertNode(N, InsertPoint);
262
Devang Patel5f4ac842009-09-03 01:39:20 +0000263 return N;
Owen Anderson647e3012009-07-31 21:35:40 +0000264}
265
Devang Patel566bd122011-03-04 01:20:33 +0000266MDNode *MDNode::get(LLVMContext &Context, ArrayRef<Value*> Vals) {
Jay Foadec9186b2011-04-21 19:59:31 +0000267 return getMDNode(Context, Vals, FL_Unknown);
Victor Hernandez24e64df2010-01-10 07:14:18 +0000268}
269
Jay Foadec9186b2011-04-21 19:59:31 +0000270MDNode *MDNode::getWhenValsUnresolved(LLVMContext &Context,
271 ArrayRef<Value*> Vals,
272 bool isFunctionLocal) {
273 return getMDNode(Context, Vals, isFunctionLocal ? FL_Yes : FL_No);
Victor Hernandez24e64df2010-01-10 07:14:18 +0000274}
275
Jay Foadec9186b2011-04-21 19:59:31 +0000276MDNode *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Value*> Vals) {
277 return getMDNode(Context, Vals, FL_Unknown, false);
Victor Hernandeze685f232010-01-26 02:36:35 +0000278}
279
Jay Foadec9186b2011-04-21 19:59:31 +0000280MDNode *MDNode::getTemporary(LLVMContext &Context, ArrayRef<Value*> Vals) {
281 MDNode *N =
Bill Wendling48663632012-04-26 00:38:42 +0000282 (MDNode *)malloc(sizeof(MDNode) + Vals.size() * sizeof(MDNodeOperand));
Jay Foadec9186b2011-04-21 19:59:31 +0000283 N = new (N) MDNode(Context, Vals, FL_No);
Dan Gohman489b29b2010-08-20 22:02:26 +0000284 N->setValueSubclassData(N->getSubclassDataFromValue() |
285 NotUniquedBit);
286 LeakDetector::addGarbageObject(N);
287 return N;
288}
289
290void MDNode::deleteTemporary(MDNode *N) {
291 assert(N->use_empty() && "Temporary MDNode has uses!");
Dan Gohman990bdd52010-08-21 02:52:29 +0000292 assert(!N->getContext().pImpl->MDNodeSet.RemoveNode(N) &&
Dan Gohman97cfa7d2010-08-23 22:32:05 +0000293 "Deleting a non-temporary uniqued node!");
294 assert(!N->getContext().pImpl->NonUniquedMDNodes.erase(N) &&
295 "Deleting a non-temporary non-uniqued node!");
Dan Gohman489b29b2010-08-20 22:02:26 +0000296 assert((N->getSubclassDataFromValue() & NotUniquedBit) &&
297 "Temporary MDNode does not have NotUniquedBit set!");
298 assert((N->getSubclassDataFromValue() & DestroyFlag) == 0 &&
Dan Gohman990bdd52010-08-21 02:52:29 +0000299 "Temporary MDNode has DestroyFlag set!");
Dan Gohman489b29b2010-08-20 22:02:26 +0000300 LeakDetector::removeGarbageObject(N);
Benjamin Kramer9dd3e922010-08-21 15:07:23 +0000301 N->destroy();
Dan Gohman489b29b2010-08-20 22:02:26 +0000302}
303
Chris Lattner5d0cacd2009-12-31 01:22:29 +0000304/// getOperand - Return specified operand.
305Value *MDNode::getOperand(unsigned i) const {
Chris Lattnerb76359e2009-12-31 01:05:46 +0000306 return *getOperandPtr(const_cast<MDNode*>(this), i);
307}
308
Chris Lattnerf2410182009-12-28 09:12:35 +0000309void MDNode::Profile(FoldingSetNodeID &ID) const {
Dan Gohman7548fb32010-08-24 23:21:12 +0000310 // Add all the operand pointers. Note that we don't have to add the
311 // isFunctionLocal bit because that's implied by the operands.
Dan Gohman56b092e2010-08-30 21:18:41 +0000312 // Note that if the operands are later nulled out, the node will be
313 // removed from the uniquing map.
Chris Lattner5d0cacd2009-12-31 01:22:29 +0000314 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
315 ID.AddPointer(getOperand(i));
Devang Patel4771e162009-08-03 22:51:10 +0000316}
Devang Patelab67e702009-08-11 18:01:24 +0000317
Jeffrey Yasskin6f555ca2010-03-13 01:26:15 +0000318void MDNode::setIsNotUniqued() {
319 setValueSubclassData(getSubclassDataFromValue() | NotUniquedBit);
320 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
321 pImpl->NonUniquedMDNodes.insert(this);
Devang Patel06fdacc2010-02-18 20:53:16 +0000322}
Chris Lattnerf2410182009-12-28 09:12:35 +0000323
Chris Lattner5d0cacd2009-12-31 01:22:29 +0000324// Replace value from this node's operand list.
325void MDNode::replaceOperand(MDNodeOperand *Op, Value *To) {
Chris Lattnerdf583892009-12-28 09:32:10 +0000326 Value *From = *Op;
Mikhail Glushenkov0d75d872010-01-10 18:48:49 +0000327
Chris Lattnerf3f325b2010-04-28 20:16:12 +0000328 // If is possible that someone did GV->RAUW(inst), replacing a global variable
329 // with an instruction or some other function-local object. If this is a
330 // non-function-local MDNode, it can't point to a function-local object.
331 // Handle this case by implicitly dropping the MDNode reference to null.
Duncan Sands203f7cb2010-05-04 12:43:36 +0000332 // Likewise if the MDNode is function-local but for a different function.
333 if (To && isFunctionLocalValue(To)) {
334 if (!isFunctionLocal())
335 To = 0;
336 else {
337 const Function *F = getFunction();
338 const Function *FV = getFunctionForValue(To);
339 // Metadata can be function-local without having an associated function.
340 // So only consider functions to have changed if non-null.
341 if (F && FV && F != FV)
342 To = 0;
343 }
344 }
Chris Lattnerf3f325b2010-04-28 20:16:12 +0000345
Chris Lattnerdf583892009-12-28 09:32:10 +0000346 if (From == To)
Devang Patel5f4ac842009-09-03 01:39:20 +0000347 return;
Devang Patel5f4ac842009-09-03 01:39:20 +0000348
Chris Lattner54a1f9f2009-12-30 21:42:11 +0000349 // Update the operand.
Chris Lattnerb76359e2009-12-31 01:05:46 +0000350 Op->set(To);
Chris Lattner54a1f9f2009-12-30 21:42:11 +0000351
352 // If this node is already not being uniqued (because one of the operands
353 // already went to null), then there is nothing else to do here.
354 if (isNotUniqued()) return;
Mikhail Glushenkov0d75d872010-01-10 18:48:49 +0000355
Chris Lattner49642572009-12-28 09:24:53 +0000356 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
357
358 // Remove "this" from the context map. FoldingSet doesn't have to reprofile
359 // this node to remove it, so we don't care what state the operands are in.
360 pImpl->MDNodeSet.RemoveNode(this);
Chris Lattnerdf583892009-12-28 09:32:10 +0000361
Chris Lattner54a1f9f2009-12-30 21:42:11 +0000362 // If we are dropping an argument to null, we choose to not unique the MDNode
363 // anymore. This commonly occurs during destruction, and uniquing these
Dan Gohman56b092e2010-08-30 21:18:41 +0000364 // brings little reuse. Also, this means we don't need to include
365 // isFunctionLocal bits in FoldingSetNodeIDs for MDNodes.
Chris Lattner54a1f9f2009-12-30 21:42:11 +0000366 if (To == 0) {
367 setIsNotUniqued();
368 return;
369 }
Mikhail Glushenkov0d75d872010-01-10 18:48:49 +0000370
Chris Lattner54a1f9f2009-12-30 21:42:11 +0000371 // Now that the node is out of the folding set, get ready to reinsert it.
372 // First, check to see if another node with the same operands already exists
Dan Gohmanf53458f2010-09-28 22:07:19 +0000373 // in the set. If so, then this node is redundant.
Devang Patel5f4ac842009-09-03 01:39:20 +0000374 FoldingSetNodeID ID;
375 Profile(ID);
Devang Patel5f4ac842009-09-03 01:39:20 +0000376 void *InsertPoint;
Dan Gohmanf375ebe2010-09-28 21:02:55 +0000377 if (MDNode *N = pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint)) {
Dan Gohmanf53458f2010-09-28 22:07:19 +0000378 replaceAllUsesWith(N);
379 destroy();
380 return;
Devang Patel5f4ac842009-09-03 01:39:20 +0000381 }
382
Benjamin Kramer611afc02012-04-11 14:06:54 +0000383 // Cache the operand hash.
384 Hash = ID.ComputeHash();
Chris Lattner49642572009-12-28 09:24:53 +0000385 // InsertPoint will have been set by the FindNodeOrInsertPos call.
386 pImpl->MDNodeSet.InsertNode(this, InsertPoint);
Dan Gohman5781f3e2010-09-14 01:37:57 +0000387
388 // If this MDValue was previously function-local but no longer is, clear
389 // its function-local flag.
390 if (isFunctionLocal() && !isFunctionLocalValue(To)) {
391 bool isStillFunctionLocal = false;
392 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
393 Value *V = getOperand(i);
394 if (!V) continue;
395 if (isFunctionLocalValue(V)) {
396 isStillFunctionLocal = true;
397 break;
398 }
399 }
400 if (!isStillFunctionLocal)
401 setValueSubclassData(getSubclassDataFromValue() & ~FunctionLocalBit);
402 }
Devang Patel5f4ac842009-09-03 01:39:20 +0000403}
404
Hal Finkel7b4ff932012-06-16 20:33:37 +0000405MDNode *MDNode::getMostGenericTBAA(MDNode *A, MDNode *B) {
406 if (!A || !B)
407 return NULL;
408
409 if (A == B)
410 return A;
411
412 SmallVector<MDNode *, 4> PathA;
413 MDNode *T = A;
414 while (T) {
415 PathA.push_back(T);
416 T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1)) : 0;
417 }
418
419 SmallVector<MDNode *, 4> PathB;
420 T = B;
421 while (T) {
422 PathB.push_back(T);
423 T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1)) : 0;
424 }
425
426 int IA = PathA.size() - 1;
427 int IB = PathB.size() - 1;
428
429 MDNode *Ret = 0;
430 while (IA >= 0 && IB >=0) {
431 if (PathA[IA] == PathB[IB])
432 Ret = PathA[IA];
433 else
434 break;
435 --IA;
436 --IB;
437 }
438 return Ret;
439}
440
441MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
442 if (!A || !B)
443 return NULL;
444
445 APFloat AVal = cast<ConstantFP>(A->getOperand(0))->getValueAPF();
446 APFloat BVal = cast<ConstantFP>(B->getOperand(0))->getValueAPF();
447 if (AVal.compare(BVal) == APFloat::cmpLessThan)
448 return A;
449 return B;
450}
451
452static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
453 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
454}
455
456static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
457 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
458}
459
460static bool tryMergeRange(SmallVector<Value*, 4> &EndPoints, ConstantInt *Low,
461 ConstantInt *High) {
462 ConstantRange NewRange(Low->getValue(), High->getValue());
463 unsigned Size = EndPoints.size();
464 APInt LB = cast<ConstantInt>(EndPoints[Size - 2])->getValue();
465 APInt LE = cast<ConstantInt>(EndPoints[Size - 1])->getValue();
466 ConstantRange LastRange(LB, LE);
467 if (canBeMerged(NewRange, LastRange)) {
468 ConstantRange Union = LastRange.unionWith(NewRange);
469 Type *Ty = High->getType();
470 EndPoints[Size - 2] = ConstantInt::get(Ty, Union.getLower());
471 EndPoints[Size - 1] = ConstantInt::get(Ty, Union.getUpper());
472 return true;
473 }
474 return false;
475}
476
477static void addRange(SmallVector<Value*, 4> &EndPoints, ConstantInt *Low,
478 ConstantInt *High) {
479 if (!EndPoints.empty())
480 if (tryMergeRange(EndPoints, Low, High))
481 return;
482
483 EndPoints.push_back(Low);
484 EndPoints.push_back(High);
485}
486
487MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
488 // Given two ranges, we want to compute the union of the ranges. This
489 // is slightly complitade by having to combine the intervals and merge
490 // the ones that overlap.
491
492 if (!A || !B)
493 return NULL;
494
495 if (A == B)
496 return A;
497
498 // First, walk both lists in older of the lower boundary of each interval.
499 // At each step, try to merge the new interval to the last one we adedd.
500 SmallVector<Value*, 4> EndPoints;
501 int AI = 0;
502 int BI = 0;
503 int AN = A->getNumOperands() / 2;
504 int BN = B->getNumOperands() / 2;
505 while (AI < AN && BI < BN) {
506 ConstantInt *ALow = cast<ConstantInt>(A->getOperand(2 * AI));
507 ConstantInt *BLow = cast<ConstantInt>(B->getOperand(2 * BI));
508
509 if (ALow->getValue().slt(BLow->getValue())) {
510 addRange(EndPoints, ALow, cast<ConstantInt>(A->getOperand(2 * AI + 1)));
511 ++AI;
512 } else {
513 addRange(EndPoints, BLow, cast<ConstantInt>(B->getOperand(2 * BI + 1)));
514 ++BI;
515 }
516 }
517 while (AI < AN) {
518 addRange(EndPoints, cast<ConstantInt>(A->getOperand(2 * AI)),
519 cast<ConstantInt>(A->getOperand(2 * AI + 1)));
520 ++AI;
521 }
522 while (BI < BN) {
523 addRange(EndPoints, cast<ConstantInt>(B->getOperand(2 * BI)),
524 cast<ConstantInt>(B->getOperand(2 * BI + 1)));
525 ++BI;
526 }
527
528 // If we have more than 2 ranges (4 endpoints) we have to try to merge
529 // the last and first ones.
530 unsigned Size = EndPoints.size();
531 if (Size > 4) {
532 ConstantInt *FB = cast<ConstantInt>(EndPoints[0]);
533 ConstantInt *FE = cast<ConstantInt>(EndPoints[1]);
534 if (tryMergeRange(EndPoints, FB, FE)) {
535 for (unsigned i = 0; i < Size - 2; ++i) {
536 EndPoints[i] = EndPoints[i + 2];
537 }
538 EndPoints.resize(Size - 2);
539 }
540 }
541
542 // If in the end we have a single range, it is possible that it is now the
543 // full range. Just drop the metadata in that case.
544 if (EndPoints.size() == 2) {
545 ConstantRange Range(cast<ConstantInt>(EndPoints[0])->getValue(),
546 cast<ConstantInt>(EndPoints[1])->getValue());
547 if (Range.isFullSet())
548 return NULL;
549 }
550
551 return MDNode::get(A->getContext(), EndPoints);
552}
553
Devang Patelf457d132009-07-29 00:33:07 +0000554//===----------------------------------------------------------------------===//
Chris Lattnerb2a33b462009-10-19 07:10:59 +0000555// NamedMDNode implementation.
Devang Patelf457d132009-07-29 00:33:07 +0000556//
Devang Patel26028f22010-01-12 18:34:06 +0000557
Dan Gohmand9c86dc2010-07-21 18:01:42 +0000558static SmallVector<TrackingVH<MDNode>, 4> &getNMDOps(void *Operands) {
559 return *(SmallVector<TrackingVH<MDNode>, 4>*)Operands;
Chris Lattner57109692009-12-28 08:07:14 +0000560}
561
Dan Gohman17aa92c2010-07-21 23:38:33 +0000562NamedMDNode::NamedMDNode(const Twine &N)
563 : Name(N.str()), Parent(0),
564 Operands(new SmallVector<TrackingVH<MDNode>, 4>()) {
Devang Patelab67e702009-08-11 18:01:24 +0000565}
566
Chris Lattner57109692009-12-28 08:07:14 +0000567NamedMDNode::~NamedMDNode() {
568 dropAllReferences();
569 delete &getNMDOps(Operands);
570}
571
Chris Lattner5d0cacd2009-12-31 01:22:29 +0000572/// getNumOperands - Return number of NamedMDNode operands.
573unsigned NamedMDNode::getNumOperands() const {
Chris Lattner57109692009-12-28 08:07:14 +0000574 return (unsigned)getNMDOps(Operands).size();
575}
576
Chris Lattner5d0cacd2009-12-31 01:22:29 +0000577/// getOperand - Return specified operand.
Devang Patel3e30c2a2010-01-05 20:41:31 +0000578MDNode *NamedMDNode::getOperand(unsigned i) const {
Chris Lattner5d0cacd2009-12-31 01:22:29 +0000579 assert(i < getNumOperands() && "Invalid Operand number!");
Dan Gohman872814a2010-07-21 18:54:18 +0000580 return dyn_cast<MDNode>(&*getNMDOps(Operands)[i]);
Chris Lattner57109692009-12-28 08:07:14 +0000581}
582
Chris Lattner5d0cacd2009-12-31 01:22:29 +0000583/// addOperand - Add metadata Operand.
Devang Patel3e30c2a2010-01-05 20:41:31 +0000584void NamedMDNode::addOperand(MDNode *M) {
Dan Gohman5781f3e2010-09-14 01:37:57 +0000585 assert(!M->isFunctionLocal() &&
586 "NamedMDNode operands must not be function-local!");
Dan Gohmand9c86dc2010-07-21 18:01:42 +0000587 getNMDOps(Operands).push_back(TrackingVH<MDNode>(M));
Chris Lattner57109692009-12-28 08:07:14 +0000588}
589
Devang Patela82f8832009-08-03 06:19:01 +0000590/// eraseFromParent - Drop all references and remove the node from parent
591/// module.
592void NamedMDNode::eraseFromParent() {
Dan Gohman17aa92c2010-07-21 23:38:33 +0000593 getParent()->eraseNamedMetadata(this);
Devang Patela82f8832009-08-03 06:19:01 +0000594}
595
596/// dropAllReferences - Remove all uses and clear node vector.
597void NamedMDNode::dropAllReferences() {
Chris Lattner57109692009-12-28 08:07:14 +0000598 getNMDOps(Operands).clear();
Devang Patela82f8832009-08-03 06:19:01 +0000599}
600
Devang Patel0386f012010-01-07 19:39:36 +0000601/// getName - Return a constant reference to this named metadata's name.
602StringRef NamedMDNode::getName() const {
603 return StringRef(Name);
604}
Devang Patel937b1e92009-09-16 18:09:00 +0000605
606//===----------------------------------------------------------------------===//
Chris Lattner3990b122009-12-28 23:41:32 +0000607// Instruction Metadata method implementations.
608//
609
Benjamin Kramer85dadec2011-12-06 11:50:26 +0000610void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
Chris Lattner3990b122009-12-28 23:41:32 +0000611 if (Node == 0 && !hasMetadata()) return;
Chris Lattner08113472009-12-29 09:01:33 +0000612 setMetadata(getContext().getMDKindID(Kind), Node);
Chris Lattner3990b122009-12-28 23:41:32 +0000613}
614
Benjamin Kramer85dadec2011-12-06 11:50:26 +0000615MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
Chris Lattner08113472009-12-29 09:01:33 +0000616 return getMetadataImpl(getContext().getMDKindID(Kind));
Chris Lattner3990b122009-12-28 23:41:32 +0000617}
618
619/// setMetadata - Set the metadata of of the specified kind to the specified
620/// node. This updates/replaces metadata if already present, or removes it if
621/// Node is null.
622void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
623 if (Node == 0 && !hasMetadata()) return;
Mikhail Glushenkov0d75d872010-01-10 18:48:49 +0000624
Chris Lattnerec39f092010-03-30 23:03:27 +0000625 // Handle 'dbg' as a special case since it is not stored in the hash table.
626 if (KindID == LLVMContext::MD_dbg) {
Chris Lattner84e679b2010-04-02 20:21:22 +0000627 DbgLoc = DebugLoc::getFromDILocation(Node);
Chris Lattnerec39f092010-03-30 23:03:27 +0000628 return;
629 }
630
Chris Lattner08113472009-12-29 09:01:33 +0000631 // Handle the case when we're adding/updating metadata on an instruction.
632 if (Node) {
633 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
Chris Lattnerec39f092010-03-30 23:03:27 +0000634 assert(!Info.empty() == hasMetadataHashEntry() &&
635 "HasMetadata bit is wonked");
Chris Lattner08113472009-12-29 09:01:33 +0000636 if (Info.empty()) {
Chris Lattnerec39f092010-03-30 23:03:27 +0000637 setHasMetadataHashEntry(true);
Chris Lattner08113472009-12-29 09:01:33 +0000638 } else {
639 // Handle replacement of an existing value.
640 for (unsigned i = 0, e = Info.size(); i != e; ++i)
641 if (Info[i].first == KindID) {
642 Info[i].second = Node;
643 return;
644 }
645 }
Mikhail Glushenkov0d75d872010-01-10 18:48:49 +0000646
Chris Lattner08113472009-12-29 09:01:33 +0000647 // No replacement, just add it to the list.
648 Info.push_back(std::make_pair(KindID, Node));
649 return;
650 }
Mikhail Glushenkov0d75d872010-01-10 18:48:49 +0000651
Chris Lattner08113472009-12-29 09:01:33 +0000652 // Otherwise, we're removing metadata from an instruction.
Nick Lewyckyda32cc62011-12-27 01:17:40 +0000653 assert((hasMetadataHashEntry() ==
654 getContext().pImpl->MetadataStore.count(this)) &&
Chris Lattner08113472009-12-29 09:01:33 +0000655 "HasMetadata bit out of date!");
Nick Lewyckyda32cc62011-12-27 01:17:40 +0000656 if (!hasMetadataHashEntry())
657 return; // Nothing to remove!
Chris Lattner08113472009-12-29 09:01:33 +0000658 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
Mikhail Glushenkov0d75d872010-01-10 18:48:49 +0000659
Chris Lattner08113472009-12-29 09:01:33 +0000660 // Common case is removing the only entry.
661 if (Info.size() == 1 && Info[0].first == KindID) {
662 getContext().pImpl->MetadataStore.erase(this);
Chris Lattnerec39f092010-03-30 23:03:27 +0000663 setHasMetadataHashEntry(false);
Chris Lattner08113472009-12-29 09:01:33 +0000664 return;
665 }
Mikhail Glushenkov0d75d872010-01-10 18:48:49 +0000666
Chris Lattnerec39f092010-03-30 23:03:27 +0000667 // Handle removal of an existing value.
Chris Lattner08113472009-12-29 09:01:33 +0000668 for (unsigned i = 0, e = Info.size(); i != e; ++i)
669 if (Info[i].first == KindID) {
670 Info[i] = Info.back();
671 Info.pop_back();
672 assert(!Info.empty() && "Removing last entry should be handled above");
673 return;
674 }
675 // Otherwise, removing an entry that doesn't exist on the instruction.
Chris Lattner3990b122009-12-28 23:41:32 +0000676}
677
678MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
Chris Lattnerec39f092010-03-30 23:03:27 +0000679 // Handle 'dbg' as a special case since it is not stored in the hash table.
680 if (KindID == LLVMContext::MD_dbg)
Chris Lattner61336ae2010-04-01 05:23:13 +0000681 return DbgLoc.getAsMDNode(getContext());
Chris Lattnerec39f092010-03-30 23:03:27 +0000682
683 if (!hasMetadataHashEntry()) return 0;
684
Chris Lattner08113472009-12-29 09:01:33 +0000685 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
Chris Lattnerec39f092010-03-30 23:03:27 +0000686 assert(!Info.empty() && "bit out of sync with hash table");
Mikhail Glushenkov0d75d872010-01-10 18:48:49 +0000687
Chris Lattner08113472009-12-29 09:01:33 +0000688 for (LLVMContextImpl::MDMapTy::iterator I = Info.begin(), E = Info.end();
689 I != E; ++I)
690 if (I->first == KindID)
691 return I->second;
692 return 0;
Chris Lattner3990b122009-12-28 23:41:32 +0000693}
694
695void Instruction::getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,
Chris Lattnerec39f092010-03-30 23:03:27 +0000696 MDNode*> > &Result) const {
697 Result.clear();
698
699 // Handle 'dbg' as a special case since it is not stored in the hash table.
Chris Lattner61336ae2010-04-01 05:23:13 +0000700 if (!DbgLoc.isUnknown()) {
701 Result.push_back(std::make_pair((unsigned)LLVMContext::MD_dbg,
702 DbgLoc.getAsMDNode(getContext())));
Chris Lattnerec39f092010-03-30 23:03:27 +0000703 if (!hasMetadataHashEntry()) return;
704 }
705
706 assert(hasMetadataHashEntry() &&
707 getContext().pImpl->MetadataStore.count(this) &&
Chris Lattner08113472009-12-29 09:01:33 +0000708 "Shouldn't have called this");
709 const LLVMContextImpl::MDMapTy &Info =
710 getContext().pImpl->MetadataStore.find(this)->second;
711 assert(!Info.empty() && "Shouldn't have called this");
Mikhail Glushenkov0d75d872010-01-10 18:48:49 +0000712
Chris Lattner08113472009-12-29 09:01:33 +0000713 Result.append(Info.begin(), Info.end());
Mikhail Glushenkov0d75d872010-01-10 18:48:49 +0000714
Chris Lattner08113472009-12-29 09:01:33 +0000715 // Sort the resulting array so it is stable.
716 if (Result.size() > 1)
717 array_pod_sort(Result.begin(), Result.end());
Chris Lattner3990b122009-12-28 23:41:32 +0000718}
719
Chris Lattner61336ae2010-04-01 05:23:13 +0000720void Instruction::
721getAllMetadataOtherThanDebugLocImpl(SmallVectorImpl<std::pair<unsigned,
722 MDNode*> > &Result) const {
723 Result.clear();
724 assert(hasMetadataHashEntry() &&
725 getContext().pImpl->MetadataStore.count(this) &&
726 "Shouldn't have called this");
727 const LLVMContextImpl::MDMapTy &Info =
Bill Wendlingf563fc32012-04-03 10:50:09 +0000728 getContext().pImpl->MetadataStore.find(this)->second;
Chris Lattner61336ae2010-04-01 05:23:13 +0000729 assert(!Info.empty() && "Shouldn't have called this");
Chris Lattner61336ae2010-04-01 05:23:13 +0000730 Result.append(Info.begin(), Info.end());
Bill Wendlingf563fc32012-04-03 10:50:09 +0000731
Chris Lattner61336ae2010-04-01 05:23:13 +0000732 // Sort the resulting array so it is stable.
733 if (Result.size() > 1)
734 array_pod_sort(Result.begin(), Result.end());
735}
736
Dan Gohman4f1be4a2010-07-20 22:25:04 +0000737/// clearMetadataHashEntries - Clear all hashtable-based metadata from
738/// this instruction.
739void Instruction::clearMetadataHashEntries() {
740 assert(hasMetadataHashEntry() && "Caller should check");
741 getContext().pImpl->MetadataStore.erase(this);
742 setHasMetadataHashEntry(false);
Chris Lattner508b19a2009-12-29 07:44:16 +0000743}
744