blob: b1da0301ecfcf02573875e52d00d6583529ada2b [file] [log] [blame]
Duncan P. N. Exon Smith71db6422015-02-02 18:20:15 +00001//===- Metadata.cpp - Implement Metadata classes --------------------------===//
Devang Patela4f43fb2009-07-28 21:49:47 +00002//
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 Carruth9fb823b2013-01-02 11:36:10 +000014#include "llvm/IR/Metadata.h"
Chris Lattner1300f452009-12-28 08:24:16 +000015#include "LLVMContextImpl.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000016#include "MetadataImpl.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "SymbolTableListTraitsImpl.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/STLExtras.h"
Rafael Espindolaab73c492014-01-28 16:56:46 +000020#include "llvm/ADT/SmallSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/SmallString.h"
22#include "llvm/ADT/StringMap.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000023#include "llvm/IR/ConstantRange.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000024#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Instruction.h"
26#include "llvm/IR/LLVMContext.h"
27#include "llvm/IR/Module.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000028#include "llvm/IR/ValueHandle.h"
Duncan P. N. Exon Smith46d91ad2014-11-14 18:42:06 +000029
Devang Patela4f43fb2009-07-28 21:49:47 +000030using namespace llvm;
31
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +000032MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
33 : Value(Ty, MetadataAsValueVal), MD(MD) {
34 track();
35}
36
37MetadataAsValue::~MetadataAsValue() {
38 getType()->getContext().pImpl->MetadataAsValues.erase(MD);
39 untrack();
40}
41
42/// \brief Canonicalize metadata arguments to intrinsics.
43///
44/// To support bitcode upgrades (and assembly semantic sugar) for \a
45/// MetadataAsValue, we need to canonicalize certain metadata.
46///
47/// - nullptr is replaced by an empty MDNode.
48/// - An MDNode with a single null operand is replaced by an empty MDNode.
49/// - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
50///
51/// This maintains readability of bitcode from when metadata was a type of
52/// value, and these bridges were unnecessary.
53static Metadata *canonicalizeMetadataForValue(LLVMContext &Context,
54 Metadata *MD) {
55 if (!MD)
56 // !{}
57 return MDNode::get(Context, None);
58
59 // Return early if this isn't a single-operand MDNode.
60 auto *N = dyn_cast<MDNode>(MD);
61 if (!N || N->getNumOperands() != 1)
62 return MD;
63
64 if (!N->getOperand(0))
65 // !{}
66 return MDNode::get(Context, None);
67
68 if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
69 // Look through the MDNode.
70 return C;
71
72 return MD;
73}
74
75MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
76 MD = canonicalizeMetadataForValue(Context, MD);
77 auto *&Entry = Context.pImpl->MetadataAsValues[MD];
78 if (!Entry)
79 Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
80 return Entry;
81}
82
83MetadataAsValue *MetadataAsValue::getIfExists(LLVMContext &Context,
84 Metadata *MD) {
85 MD = canonicalizeMetadataForValue(Context, MD);
86 auto &Store = Context.pImpl->MetadataAsValues;
Benjamin Kramer4c1f0972015-02-08 21:56:09 +000087 return Store.lookup(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +000088}
89
90void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
91 LLVMContext &Context = getContext();
92 MD = canonicalizeMetadataForValue(Context, MD);
93 auto &Store = Context.pImpl->MetadataAsValues;
94
95 // Stop tracking the old metadata.
96 Store.erase(this->MD);
97 untrack();
98 this->MD = nullptr;
99
100 // Start tracking MD, or RAUW if necessary.
101 auto *&Entry = Store[MD];
102 if (Entry) {
103 replaceAllUsesWith(Entry);
104 delete this;
105 return;
106 }
107
108 this->MD = MD;
109 track();
110 Entry = this;
111}
112
113void MetadataAsValue::track() {
114 if (MD)
115 MetadataTracking::track(&MD, *MD, *this);
116}
117
118void MetadataAsValue::untrack() {
119 if (MD)
120 MetadataTracking::untrack(MD);
121}
122
123void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000124 bool WasInserted =
125 UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
126 .second;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000127 (void)WasInserted;
128 assert(WasInserted && "Expected to add a reference");
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000129
130 ++NextIndex;
131 assert(NextIndex != 0 && "Unexpected overflow");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000132}
133
134void ReplaceableMetadataImpl::dropRef(void *Ref) {
135 bool WasErased = UseMap.erase(Ref);
136 (void)WasErased;
137 assert(WasErased && "Expected to drop a reference");
138}
139
140void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
141 const Metadata &MD) {
142 auto I = UseMap.find(Ref);
143 assert(I != UseMap.end() && "Expected to move a reference");
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000144 auto OwnerAndIndex = I->second;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000145 UseMap.erase(I);
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000146 bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
147 (void)WasInserted;
148 assert(WasInserted && "Expected to add a reference");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000149
150 // Check that the references are direct if there's no owner.
151 (void)MD;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000152 assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000153 "Reference without owner must be direct");
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000154 assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000155 "Reference without owner must be direct");
156}
157
158void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000159 assert(!(MD && isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary()) &&
160 "Expected non-temp node");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000161
162 if (UseMap.empty())
163 return;
164
165 // Copy out uses since UseMap will get touched below.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000166 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
167 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
168 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
169 return L.second.second < R.second.second;
170 });
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000171 for (const auto &Pair : Uses) {
Duncan P. N. Exon Smith4a4f7852015-01-14 19:56:10 +0000172 // Check that this Ref hasn't disappeared after RAUW (when updating a
173 // previous Ref).
174 if (!UseMap.count(Pair.first))
175 continue;
176
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000177 OwnerTy Owner = Pair.second.first;
178 if (!Owner) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000179 // Update unowned tracking references directly.
180 Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
181 Ref = MD;
Duncan P. N. Exon Smith121eeff2014-12-12 19:24:33 +0000182 if (MD)
183 MetadataTracking::track(Ref);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000184 UseMap.erase(Pair.first);
185 continue;
186 }
187
188 // Check for MetadataAsValue.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000189 if (Owner.is<MetadataAsValue *>()) {
190 Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000191 continue;
192 }
193
194 // There's a Metadata owner -- dispatch.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000195 Metadata *OwnerMD = Owner.get<Metadata *>();
196 switch (OwnerMD->getMetadataID()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000197#define HANDLE_METADATA_LEAF(CLASS) \
198 case Metadata::CLASS##Kind: \
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000199 cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000200 continue;
201#include "llvm/IR/Metadata.def"
202 default:
203 llvm_unreachable("Invalid metadata subclass");
204 }
205 }
206 assert(UseMap.empty() && "Expected all uses to be replaced");
207}
208
209void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
210 if (UseMap.empty())
211 return;
212
213 if (!ResolveUsers) {
214 UseMap.clear();
215 return;
216 }
217
218 // Copy out uses since UseMap could get touched below.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000219 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
220 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
221 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
222 return L.second.second < R.second.second;
223 });
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000224 UseMap.clear();
225 for (const auto &Pair : Uses) {
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000226 auto Owner = Pair.second.first;
227 if (!Owner)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000228 continue;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000229 if (Owner.is<MetadataAsValue *>())
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000230 continue;
231
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000232 // Resolve MDNodes that point at this.
233 auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000234 if (!OwnerMD)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000235 continue;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000236 if (OwnerMD->isResolved())
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000237 continue;
Duncan P. N. Exon Smith34c3d102015-01-12 19:43:15 +0000238 OwnerMD->decrementUnresolvedOperandCount();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000239 }
240}
241
242static Function *getLocalFunction(Value *V) {
243 assert(V && "Expected value");
244 if (auto *A = dyn_cast<Argument>(V))
245 return A->getParent();
246 if (BasicBlock *BB = cast<Instruction>(V)->getParent())
247 return BB->getParent();
248 return nullptr;
249}
250
251ValueAsMetadata *ValueAsMetadata::get(Value *V) {
252 assert(V && "Unexpected null Value");
253
254 auto &Context = V->getContext();
255 auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
256 if (!Entry) {
257 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
258 "Expected constant or function-local value");
Owen Anderson7349ab92015-06-01 22:24:01 +0000259 assert(!V->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000260 "Expected this to be the only metadata use");
Owen Anderson7349ab92015-06-01 22:24:01 +0000261 V->IsUsedByMD = true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000262 if (auto *C = dyn_cast<Constant>(V))
Duncan P. N. Exon Smith1c00c9f2015-01-05 20:41:25 +0000263 Entry = new ConstantAsMetadata(C);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000264 else
Duncan P. N. Exon Smith1c00c9f2015-01-05 20:41:25 +0000265 Entry = new LocalAsMetadata(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000266 }
267
268 return Entry;
269}
270
271ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
272 assert(V && "Unexpected null Value");
273 return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
274}
275
276void ValueAsMetadata::handleDeletion(Value *V) {
277 assert(V && "Expected valid value");
278
279 auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
280 auto I = Store.find(V);
281 if (I == Store.end())
282 return;
283
284 // Remove old entry from the map.
285 ValueAsMetadata *MD = I->second;
286 assert(MD && "Expected valid metadata");
287 assert(MD->getValue() == V && "Expected valid mapping");
288 Store.erase(I);
289
290 // Delete the metadata.
291 MD->replaceAllUsesWith(nullptr);
292 delete MD;
293}
294
295void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
296 assert(From && "Expected valid value");
297 assert(To && "Expected valid value");
298 assert(From != To && "Expected changed value");
299 assert(From->getType() == To->getType() && "Unexpected type change");
300
301 LLVMContext &Context = From->getType()->getContext();
302 auto &Store = Context.pImpl->ValuesAsMetadata;
303 auto I = Store.find(From);
304 if (I == Store.end()) {
Owen Anderson7349ab92015-06-01 22:24:01 +0000305 assert(!From->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000306 "Expected From not to be used by metadata");
307 return;
308 }
309
310 // Remove old entry from the map.
Owen Anderson7349ab92015-06-01 22:24:01 +0000311 assert(From->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000312 "Expected From to be used by metadata");
Owen Anderson7349ab92015-06-01 22:24:01 +0000313 From->IsUsedByMD = false;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000314 ValueAsMetadata *MD = I->second;
315 assert(MD && "Expected valid metadata");
316 assert(MD->getValue() == From && "Expected valid mapping");
317 Store.erase(I);
318
319 if (isa<LocalAsMetadata>(MD)) {
320 if (auto *C = dyn_cast<Constant>(To)) {
321 // Local became a constant.
322 MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
323 delete MD;
324 return;
325 }
326 if (getLocalFunction(From) && getLocalFunction(To) &&
327 getLocalFunction(From) != getLocalFunction(To)) {
328 // Function changed.
329 MD->replaceAllUsesWith(nullptr);
330 delete MD;
331 return;
332 }
333 } else if (!isa<Constant>(To)) {
334 // Changed to function-local value.
335 MD->replaceAllUsesWith(nullptr);
336 delete MD;
337 return;
338 }
339
340 auto *&Entry = Store[To];
341 if (Entry) {
342 // The target already exists.
343 MD->replaceAllUsesWith(Entry);
344 delete MD;
345 return;
346 }
347
348 // Update MD in place (and update the map entry).
Owen Anderson7349ab92015-06-01 22:24:01 +0000349 assert(!To->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000350 "Expected this to be the only metadata use");
Owen Anderson7349ab92015-06-01 22:24:01 +0000351 To->IsUsedByMD = true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000352 MD->V = To;
353 Entry = MD;
354}
Duncan P. N. Exon Smitha69934f2014-11-14 18:42:09 +0000355
Devang Patela4f43fb2009-07-28 21:49:47 +0000356//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000357// MDString implementation.
Owen Anderson0087fe62009-07-31 21:35:40 +0000358//
Chris Lattner5a409bd2009-12-28 08:30:43 +0000359
Devang Pateldcb99d32009-10-22 00:10:15 +0000360MDString *MDString::get(LLVMContext &Context, StringRef Str) {
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000361 auto &Store = Context.pImpl->MDStringCache;
362 auto I = Store.find(Str);
363 if (I != Store.end())
364 return &I->second;
365
Duncan P. N. Exon Smith56228312014-12-09 18:52:38 +0000366 auto *Entry =
367 StringMapEntry<MDString>::Create(Str, Store.getAllocator(), MDString());
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000368 bool WasInserted = Store.insert(Entry);
369 (void)WasInserted;
370 assert(WasInserted && "Expected entry to be inserted");
Duncan P. N. Exon Smithc1a664f2014-12-05 01:41:34 +0000371 Entry->second.Entry = Entry;
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000372 return &Entry->second;
373}
374
375StringRef MDString::getString() const {
Duncan P. N. Exon Smithc1a664f2014-12-05 01:41:34 +0000376 assert(Entry && "Expected to find string map entry");
377 return Entry->first();
Owen Anderson0087fe62009-07-31 21:35:40 +0000378}
379
380//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000381// MDNode implementation.
Devang Patela4f43fb2009-07-28 21:49:47 +0000382//
Chris Lattner74a6ad62009-12-28 07:41:54 +0000383
James Y Knight8096d342015-06-17 01:21:20 +0000384// Assert that the MDNode types will not be unaligned by the objects
385// prepended to them.
386#define HANDLE_MDNODE_LEAF(CLASS) \
James Y Knightf27e4412015-06-17 13:53:12 +0000387 static_assert( \
388 llvm::AlignOf<uint64_t>::Alignment >= llvm::AlignOf<CLASS>::Alignment, \
389 "Alignment is insufficient after objects prepended to " #CLASS);
James Y Knight8096d342015-06-17 01:21:20 +0000390#include "llvm/IR/Metadata.def"
391
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000392void *MDNode::operator new(size_t Size, unsigned NumOps) {
James Y Knight8096d342015-06-17 01:21:20 +0000393 size_t OpSize = NumOps * sizeof(MDOperand);
394 // uint64_t is the most aligned type we need support (ensured by static_assert
395 // above)
396 OpSize = RoundUpToAlignment(OpSize, llvm::alignOf<uint64_t>());
397 void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
Duncan P. N. Exon Smith22600ff2014-12-09 23:56:39 +0000398 MDOperand *O = static_cast<MDOperand *>(Ptr);
James Y Knight8096d342015-06-17 01:21:20 +0000399 for (MDOperand *E = O - NumOps; O != E; --O)
400 (void)new (O - 1) MDOperand;
401 return Ptr;
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000402}
403
Naomi Musgrave21c1bc42015-08-31 21:06:08 +0000404void MDNode::operator delete(void *Mem) {
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000405 MDNode *N = static_cast<MDNode *>(Mem);
James Y Knight8096d342015-06-17 01:21:20 +0000406 size_t OpSize = N->NumOperands * sizeof(MDOperand);
407 OpSize = RoundUpToAlignment(OpSize, llvm::alignOf<uint64_t>());
408
Duncan P. N. Exon Smith22600ff2014-12-09 23:56:39 +0000409 MDOperand *O = static_cast<MDOperand *>(Mem);
410 for (MDOperand *E = O - N->NumOperands; O != E; --O)
411 (O - 1)->~MDOperand();
James Y Knight8096d342015-06-17 01:21:20 +0000412 ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000413}
414
Duncan P. N. Exon Smithf1340452015-01-19 18:36:18 +0000415MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
Duncan P. N. Exon Smithfed199a2015-01-20 00:01:43 +0000416 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
417 : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
418 NumUnresolved(0), Context(Context) {
419 unsigned Op = 0;
420 for (Metadata *MD : Ops1)
421 setOperand(Op++, MD);
422 for (Metadata *MD : Ops2)
423 setOperand(Op++, MD);
Duncan P. N. Exon Smith2711ca72015-01-19 19:02:06 +0000424
Duncan P. N. Exon Smitha1ae4f62015-01-19 23:15:21 +0000425 if (isDistinct())
Duncan P. N. Exon Smith5e5b8502015-01-07 22:24:46 +0000426 return;
427
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000428 if (isUniqued())
429 // Check whether any operands are unresolved, requiring re-uniquing. If
430 // not, don't support RAUW.
431 if (!countUnresolvedOperands())
Duncan P. N. Exon Smitha1ae4f62015-01-19 23:15:21 +0000432 return;
433
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000434 this->Context.makeReplaceable(make_unique<ReplaceableMetadataImpl>(Context));
Devang Patela4f43fb2009-07-28 21:49:47 +0000435}
436
Duncan P. N. Exon Smith03e05832015-01-20 02:56:57 +0000437TempMDNode MDNode::clone() const {
438 switch (getMetadataID()) {
439 default:
440 llvm_unreachable("Invalid MDNode subclass");
441#define HANDLE_MDNODE_LEAF(CLASS) \
442 case CLASS##Kind: \
443 return cast<CLASS>(this)->cloneImpl();
444#include "llvm/IR/Metadata.def"
445 }
446}
447
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000448static bool isOperandUnresolved(Metadata *Op) {
449 if (auto *N = dyn_cast_or_null<MDNode>(Op))
450 return !N->isResolved();
451 return false;
452}
453
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000454unsigned MDNode::countUnresolvedOperands() {
455 assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000456 NumUnresolved = std::count_if(op_begin(), op_end(), isOperandUnresolved);
Duncan P. N. Exon Smithc5a0e2e2015-01-19 22:18:29 +0000457 return NumUnresolved;
458}
459
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000460void MDNode::makeUniqued() {
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000461 assert(isTemporary() && "Expected this to be temporary");
462 assert(!isResolved() && "Expected this to be unresolved");
463
Duncan P. N. Exon Smithcb33d6f2015-03-31 20:50:50 +0000464 // Enable uniquing callbacks.
465 for (auto &Op : mutable_operands())
466 Op.reset(Op.get(), this);
467
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000468 // Make this 'uniqued'.
469 Storage = Uniqued;
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000470 if (!countUnresolvedOperands())
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000471 resolve();
472
473 assert(isUniqued() && "Expected this to be uniqued");
474}
475
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000476void MDNode::makeDistinct() {
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000477 assert(isTemporary() && "Expected this to be temporary");
478 assert(!isResolved() && "Expected this to be unresolved");
479
480 // Pretend to be uniqued, resolve the node, and then store in distinct table.
481 Storage = Uniqued;
482 resolve();
483 storeDistinctInContext();
484
485 assert(isDistinct() && "Expected this to be distinct");
486 assert(isResolved() && "Expected this to be resolved");
487}
488
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000489void MDNode::resolve() {
Duncan P. N. Exon Smithb8f79602015-01-19 19:26:24 +0000490 assert(isUniqued() && "Expected this to be uniqued");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000491 assert(!isResolved() && "Expected this to be unresolved");
492
493 // Move the map, so that this immediately looks resolved.
Duncan P. N. Exon Smith2711ca72015-01-19 19:02:06 +0000494 auto Uses = Context.takeReplaceableUses();
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000495 NumUnresolved = 0;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000496 assert(isResolved() && "Expected this to be resolved");
497
498 // Drop RAUW support.
499 Uses->resolveAllUses();
500}
501
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000502void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000503 assert(NumUnresolved != 0 && "Expected unresolved operands");
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000504
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000505 // Check if an operand was resolved.
Duncan P. N. Exon Smith845755c42015-01-13 00:46:34 +0000506 if (!isOperandUnresolved(Old)) {
507 if (isOperandUnresolved(New))
508 // An operand was un-resolved!
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000509 ++NumUnresolved;
Duncan P. N. Exon Smith845755c42015-01-13 00:46:34 +0000510 } else if (!isOperandUnresolved(New))
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000511 decrementUnresolvedOperandCount();
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000512}
513
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000514void MDNode::decrementUnresolvedOperandCount() {
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000515 if (!--NumUnresolved)
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000516 // Last unresolved operand has just been resolved.
Duncan P. N. Exon Smith34c3d102015-01-12 19:43:15 +0000517 resolve();
518}
519
Teresa Johnsone5a61912015-12-17 17:14:09 +0000520void MDNode::resolveCycles(bool MDMaterialized) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000521 if (isResolved())
522 return;
523
524 // Resolve this node immediately.
525 resolve();
526
527 // Resolve all operands.
528 for (const auto &Op : operands()) {
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000529 auto *N = dyn_cast_or_null<MDNode>(Op);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000530 if (!N)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000531 continue;
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000532
Teresa Johnsone5a61912015-12-17 17:14:09 +0000533 if (N->isTemporary() && !MDMaterialized)
534 continue;
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000535 assert(!N->isTemporary() &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000536 "Expected all forward declarations to be resolved");
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000537 if (!N->isResolved())
538 N->resolveCycles();
Chris Lattner8cb6c342009-12-31 01:05:46 +0000539 }
Duncan P. N. Exon Smith50846f82014-11-18 00:37:17 +0000540}
541
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000542static bool hasSelfReference(MDNode *N) {
543 for (Metadata *MD : N->operands())
544 if (MD == N)
545 return true;
546 return false;
547}
548
549MDNode *MDNode::replaceWithPermanentImpl() {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000550 switch (getMetadataID()) {
551 default:
552 // If this type isn't uniquable, replace with a distinct node.
553 return replaceWithDistinctImpl();
554
555#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
556 case CLASS##Kind: \
557 break;
558#include "llvm/IR/Metadata.def"
559 }
560
561 // Even if this type is uniquable, self-references have to be distinct.
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000562 if (hasSelfReference(this))
563 return replaceWithDistinctImpl();
564 return replaceWithUniquedImpl();
565}
566
Duncan P. N. Exon Smith86475292015-01-19 23:17:09 +0000567MDNode *MDNode::replaceWithUniquedImpl() {
568 // Try to uniquify in place.
569 MDNode *UniquedNode = uniquify();
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000570
Duncan P. N. Exon Smith86475292015-01-19 23:17:09 +0000571 if (UniquedNode == this) {
572 makeUniqued();
573 return this;
574 }
575
576 // Collision, so RAUW instead.
577 replaceAllUsesWith(UniquedNode);
578 deleteAsSubclass();
579 return UniquedNode;
580}
581
582MDNode *MDNode::replaceWithDistinctImpl() {
583 makeDistinct();
584 return this;
585}
586
Duncan P. N. Exon Smith118632d2015-01-12 20:09:34 +0000587void MDTuple::recalculateHash() {
Duncan P. N. Exon Smith93e983e2015-01-19 22:53:18 +0000588 setHash(MDTupleInfo::KeyTy::calculateHash(this));
Duncan P. N. Exon Smith967629e2015-01-12 19:16:34 +0000589}
590
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000591void MDNode::dropAllReferences() {
592 for (unsigned I = 0, E = NumOperands; I != E; ++I)
593 setOperand(I, nullptr);
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000594 if (!isResolved()) {
595 Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
596 (void)Context.takeReplaceableUses();
597 }
Chris Lattner8cb6c342009-12-31 01:05:46 +0000598}
599
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000600void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000601 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
602 assert(Op < getNumOperands() && "Expected valid operand");
603
Duncan P. N. Exon Smith3d580562015-01-19 19:28:28 +0000604 if (!isUniqued()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000605 // This node is not uniqued. Just set the operand and be done with it.
606 setOperand(Op, New);
607 return;
Duncan Sandsc2928c62010-05-04 12:43:36 +0000608 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000609
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000610 // This node is uniqued.
611 eraseFromStore();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000612
613 Metadata *Old = getOperand(Op);
614 setOperand(Op, New);
615
Duncan P. N. Exon Smithbcd960a2015-01-05 23:31:54 +0000616 // Drop uniquing for self-reference cycles.
617 if (New == this) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000618 if (!isResolved())
619 resolve();
Duncan P. N. Exon Smithf08b8b42015-01-19 19:25:33 +0000620 storeDistinctInContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000621 return;
622 }
623
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000624 // Re-unique the node.
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000625 auto *Uniqued = uniquify();
626 if (Uniqued == this) {
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000627 if (!isResolved())
628 resolveAfterOperandChange(Old, New);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000629 return;
630 }
631
632 // Collision.
633 if (!isResolved()) {
634 // Still unresolved, so RAUW.
Duncan P. N. Exon Smithd9e6eb72015-01-12 19:36:35 +0000635 //
636 // First, clear out all operands to prevent any recursion (similar to
637 // dropAllReferences(), but we still need the use-list).
638 for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
639 setOperand(O, nullptr);
Duncan P. N. Exon Smith2711ca72015-01-19 19:02:06 +0000640 Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000641 deleteAsSubclass();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000642 return;
643 }
644
Duncan P. N. Exon Smithd9e6eb72015-01-12 19:36:35 +0000645 // Store in non-uniqued form if RAUW isn't possible.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000646 storeDistinctInContext();
Victor Hernandeze5f2af72010-01-20 04:45:57 +0000647}
648
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000649void MDNode::deleteAsSubclass() {
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000650 switch (getMetadataID()) {
651 default:
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000652 llvm_unreachable("Invalid subclass of MDNode");
653#define HANDLE_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000654 case CLASS##Kind: \
655 delete cast<CLASS>(this); \
656 break;
657#include "llvm/IR/Metadata.def"
658 }
659}
660
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000661template <class T, class InfoT>
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000662static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
663 if (T *U = getUniqued(Store, N))
664 return U;
665
666 Store.insert(N);
667 return N;
668}
669
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000670template <class NodeTy> struct MDNode::HasCachedHash {
671 typedef char Yes[1];
672 typedef char No[2];
673 template <class U, U Val> struct SFINAE {};
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000674
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000675 template <class U>
676 static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
677 template <class U> static No &check(...);
678
679 static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
680};
681
682MDNode *MDNode::uniquify() {
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000683 assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
684
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000685 // Try to insert into uniquing store.
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000686 switch (getMetadataID()) {
687 default:
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000688 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
689#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000690 case CLASS##Kind: { \
691 CLASS *SubclassThis = cast<CLASS>(this); \
692 std::integral_constant<bool, HasCachedHash<CLASS>::value> \
693 ShouldRecalculateHash; \
694 dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
695 return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
696 }
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000697#include "llvm/IR/Metadata.def"
698 }
699}
700
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000701void MDNode::eraseFromStore() {
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000702 switch (getMetadataID()) {
703 default:
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000704 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
705#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000706 case CLASS##Kind: \
Duncan P. N. Exon Smith6cf10d22015-01-19 22:47:08 +0000707 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000708 break;
709#include "llvm/IR/Metadata.def"
710 }
711}
712
Duncan P. N. Exon Smithac3128d2015-01-12 20:13:56 +0000713MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000714 StorageType Storage, bool ShouldCreate) {
715 unsigned Hash = 0;
716 if (Storage == Uniqued) {
717 MDTupleInfo::KeyTy Key(MDs);
Duncan P. N. Exon Smithb57f9e92015-01-19 20:16:50 +0000718 if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
719 return N;
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000720 if (!ShouldCreate)
721 return nullptr;
Duncan P. N. Exon Smith93e983e2015-01-19 22:53:18 +0000722 Hash = Key.getHash();
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000723 } else {
724 assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
725 }
Duncan Sands26a80f32012-03-31 08:20:11 +0000726
Duncan P. N. Exon Smith5b8c4402015-01-19 20:18:13 +0000727 return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
728 Storage, Context.pImpl->MDTuples);
Duncan P. N. Exon Smith5e5b8502015-01-07 22:24:46 +0000729}
730
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000731void MDNode::deleteTemporary(MDNode *N) {
732 assert(N->isTemporary() && "Expected temporary node");
Duncan P. N. Exon Smith8d536972015-01-22 21:36:45 +0000733 N->replaceAllUsesWith(nullptr);
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000734 N->deleteAsSubclass();
Dan Gohman16a5d982010-08-20 22:02:26 +0000735}
736
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000737void MDNode::storeDistinctInContext() {
Duncan P. N. Exon Smithf08b8b42015-01-19 19:25:33 +0000738 assert(isResolved() && "Expected resolved nodes");
Duncan P. N. Exon Smithf1340452015-01-19 18:36:18 +0000739 Storage = Distinct;
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000740
741 // Reset the hash.
742 switch (getMetadataID()) {
743 default:
744 llvm_unreachable("Invalid subclass of MDNode");
745#define HANDLE_MDNODE_LEAF(CLASS) \
746 case CLASS##Kind: { \
747 std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
748 dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
749 break; \
750 }
751#include "llvm/IR/Metadata.def"
752 }
753
Duncan P. N. Exon Smithde03ff52015-01-13 20:44:56 +0000754 getContext().pImpl->DistinctMDNodes.insert(this);
Devang Patel82ab3f82010-02-18 20:53:16 +0000755}
Chris Lattnerf543eff2009-12-28 09:12:35 +0000756
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000757void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
758 if (getOperand(I) == New)
Devang Patelf7188322009-09-03 01:39:20 +0000759 return;
Devang Patelf7188322009-09-03 01:39:20 +0000760
Duncan P. N. Exon Smithde03a8b2015-01-19 18:45:35 +0000761 if (!isUniqued()) {
Duncan P. N. Exon Smithdaa335a2015-01-12 18:01:45 +0000762 setOperand(I, New);
Duncan P. N. Exon Smithf39c3b82014-11-17 23:28:21 +0000763 return;
764 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +0000765
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000766 handleChangedOperand(mutable_begin() + I, New);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000767}
Chris Lattnerc6d17e22009-12-28 09:24:53 +0000768
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000769void MDNode::setOperand(unsigned I, Metadata *New) {
770 assert(I < NumOperands);
Duncan P. N. Exon Smithefdf2852015-01-19 19:29:25 +0000771 mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
Devang Patelf7188322009-09-03 01:39:20 +0000772}
773
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000774/// \brief Get a node, or a self-reference that looks like it.
775///
776/// Special handling for finding self-references, for use by \a
777/// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
778/// when self-referencing nodes were still uniqued. If the first operand has
779/// the same operands as \c Ops, return the first operand instead.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000780static MDNode *getOrSelfReference(LLVMContext &Context,
781 ArrayRef<Metadata *> Ops) {
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000782 if (!Ops.empty())
783 if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
784 if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
785 for (unsigned I = 1, E = Ops.size(); I != E; ++I)
786 if (Ops[I] != N->getOperand(I))
787 return MDNode::get(Context, Ops);
788 return N;
789 }
790
791 return MDNode::get(Context, Ops);
792}
793
Hal Finkel94146652014-07-24 14:25:39 +0000794MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
795 if (!A)
796 return B;
797 if (!B)
798 return A;
799
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000800 SmallVector<Metadata *, 4> MDs;
801 MDs.reserve(A->getNumOperands() + B->getNumOperands());
802 MDs.append(A->op_begin(), A->op_end());
803 MDs.append(B->op_begin(), B->op_end());
Hal Finkel94146652014-07-24 14:25:39 +0000804
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000805 // FIXME: This preserves long-standing behaviour, but is it really the right
806 // behaviour? Or was that an unintended side-effect of node uniquing?
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000807 return getOrSelfReference(A->getContext(), MDs);
Hal Finkel94146652014-07-24 14:25:39 +0000808}
809
810MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
811 if (!A || !B)
812 return nullptr;
813
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000814 SmallVector<Metadata *, 4> MDs;
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000815 for (Metadata *MD : A->operands())
816 if (std::find(B->op_begin(), B->op_end(), MD) != B->op_end())
817 MDs.push_back(MD);
Hal Finkel94146652014-07-24 14:25:39 +0000818
Duncan P. N. Exon Smithac8ee282014-12-07 19:52:06 +0000819 // FIXME: This preserves long-standing behaviour, but is it really the right
820 // behaviour? Or was that an unintended side-effect of node uniquing?
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000821 return getOrSelfReference(A->getContext(), MDs);
Hal Finkel94146652014-07-24 14:25:39 +0000822}
823
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +0000824MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
825 if (!A || !B)
826 return nullptr;
827
828 SmallVector<Metadata *, 4> MDs(B->op_begin(), B->op_end());
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000829 for (Metadata *MD : A->operands())
830 if (std::find(B->op_begin(), B->op_end(), MD) == B->op_end())
831 MDs.push_back(MD);
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +0000832
833 // FIXME: This preserves long-standing behaviour, but is it really the right
834 // behaviour? Or was that an unintended side-effect of node uniquing?
835 return getOrSelfReference(A->getContext(), MDs);
836}
837
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000838MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
839 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000840 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000841
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000842 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
843 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000844 if (AVal.compare(BVal) == APFloat::cmpLessThan)
845 return A;
846 return B;
847}
848
849static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
850 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
851}
852
853static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
854 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
855}
856
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000857static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
858 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000859 ConstantRange NewRange(Low->getValue(), High->getValue());
860 unsigned Size = EndPoints.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000861 APInt LB = EndPoints[Size - 2]->getValue();
862 APInt LE = EndPoints[Size - 1]->getValue();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000863 ConstantRange LastRange(LB, LE);
864 if (canBeMerged(NewRange, LastRange)) {
865 ConstantRange Union = LastRange.unionWith(NewRange);
866 Type *Ty = High->getType();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000867 EndPoints[Size - 2] =
868 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
869 EndPoints[Size - 1] =
870 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000871 return true;
872 }
873 return false;
874}
875
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000876static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
877 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000878 if (!EndPoints.empty())
879 if (tryMergeRange(EndPoints, Low, High))
880 return;
881
882 EndPoints.push_back(Low);
883 EndPoints.push_back(High);
884}
885
886MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
887 // Given two ranges, we want to compute the union of the ranges. This
888 // is slightly complitade by having to combine the intervals and merge
889 // the ones that overlap.
890
891 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000892 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000893
894 if (A == B)
895 return A;
896
897 // First, walk both lists in older of the lower boundary of each interval.
898 // At each step, try to merge the new interval to the last one we adedd.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000899 SmallVector<ConstantInt *, 4> EndPoints;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000900 int AI = 0;
901 int BI = 0;
902 int AN = A->getNumOperands() / 2;
903 int BN = B->getNumOperands() / 2;
904 while (AI < AN && BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000905 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
906 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000907
908 if (ALow->getValue().slt(BLow->getValue())) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000909 addRange(EndPoints, ALow,
910 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000911 ++AI;
912 } else {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000913 addRange(EndPoints, BLow,
914 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000915 ++BI;
916 }
917 }
918 while (AI < AN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000919 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
920 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000921 ++AI;
922 }
923 while (BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000924 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
925 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000926 ++BI;
927 }
928
929 // If we have more than 2 ranges (4 endpoints) we have to try to merge
930 // the last and first ones.
931 unsigned Size = EndPoints.size();
932 if (Size > 4) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000933 ConstantInt *FB = EndPoints[0];
934 ConstantInt *FE = EndPoints[1];
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000935 if (tryMergeRange(EndPoints, FB, FE)) {
936 for (unsigned i = 0; i < Size - 2; ++i) {
937 EndPoints[i] = EndPoints[i + 2];
938 }
939 EndPoints.resize(Size - 2);
940 }
941 }
942
943 // If in the end we have a single range, it is possible that it is now the
944 // full range. Just drop the metadata in that case.
945 if (EndPoints.size() == 2) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000946 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000947 if (Range.isFullSet())
Craig Topperc6207612014-04-09 06:08:46 +0000948 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000949 }
950
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000951 SmallVector<Metadata *, 4> MDs;
952 MDs.reserve(EndPoints.size());
953 for (auto *I : EndPoints)
954 MDs.push_back(ConstantAsMetadata::get(I));
955 return MDNode::get(A->getContext(), MDs);
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000956}
957
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000958MDNode *MDNode::getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B) {
959 if (!A || !B)
960 return nullptr;
961
962 ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
963 ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
964 if (AVal->getZExtValue() < BVal->getZExtValue())
965 return A;
966 return B;
967}
968
Devang Patel05a26fb2009-07-29 00:33:07 +0000969//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000970// NamedMDNode implementation.
Devang Patel05a26fb2009-07-29 00:33:07 +0000971//
Devang Patel943ddf62010-01-12 18:34:06 +0000972
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000973static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
974 return *(SmallVector<TrackingMDRef, 4> *)Operands;
Chris Lattner1bc810b2009-12-28 08:07:14 +0000975}
976
Dan Gohman2637cc12010-07-21 23:38:33 +0000977NamedMDNode::NamedMDNode(const Twine &N)
Duncan P. N. Exon Smithc5754a62014-11-05 18:16:03 +0000978 : Name(N.str()), Parent(nullptr),
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000979 Operands(new SmallVector<TrackingMDRef, 4>()) {}
Devang Patel5c310be2009-08-11 18:01:24 +0000980
Chris Lattner1bc810b2009-12-28 08:07:14 +0000981NamedMDNode::~NamedMDNode() {
982 dropAllReferences();
983 delete &getNMDOps(Operands);
984}
985
Chris Lattner9b493022009-12-31 01:22:29 +0000986unsigned NamedMDNode::getNumOperands() const {
Chris Lattner1bc810b2009-12-28 08:07:14 +0000987 return (unsigned)getNMDOps(Operands).size();
988}
989
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000990MDNode *NamedMDNode::getOperand(unsigned i) const {
Chris Lattner9b493022009-12-31 01:22:29 +0000991 assert(i < getNumOperands() && "Invalid Operand number!");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000992 auto *N = getNMDOps(Operands)[i].get();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000993 return cast_or_null<MDNode>(N);
Chris Lattner1bc810b2009-12-28 08:07:14 +0000994}
995
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000996void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
Chris Lattner1bc810b2009-12-28 08:07:14 +0000997
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +0000998void NamedMDNode::setOperand(unsigned I, MDNode *New) {
999 assert(I < getNumOperands() && "Invalid operand number");
1000 getNMDOps(Operands)[I].reset(New);
1001}
1002
Devang Patel79238d72009-08-03 06:19:01 +00001003void NamedMDNode::eraseFromParent() {
Dan Gohman2637cc12010-07-21 23:38:33 +00001004 getParent()->eraseNamedMetadata(this);
Devang Patel79238d72009-08-03 06:19:01 +00001005}
1006
Devang Patel79238d72009-08-03 06:19:01 +00001007void NamedMDNode::dropAllReferences() {
Chris Lattner1bc810b2009-12-28 08:07:14 +00001008 getNMDOps(Operands).clear();
Devang Patel79238d72009-08-03 06:19:01 +00001009}
1010
Devang Patelfcfee0f2010-01-07 19:39:36 +00001011StringRef NamedMDNode::getName() const {
1012 return StringRef(Name);
1013}
Devang Pateld5497a4b2009-09-16 18:09:00 +00001014
1015//===----------------------------------------------------------------------===//
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001016// Instruction Metadata method implementations.
1017//
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001018void MDAttachmentMap::set(unsigned ID, MDNode &MD) {
1019 for (auto &I : Attachments)
1020 if (I.first == ID) {
1021 I.second.reset(&MD);
1022 return;
1023 }
1024 Attachments.emplace_back(std::piecewise_construct, std::make_tuple(ID),
1025 std::make_tuple(&MD));
1026}
1027
1028void MDAttachmentMap::erase(unsigned ID) {
1029 if (empty())
1030 return;
1031
1032 // Common case is one/last value.
1033 if (Attachments.back().first == ID) {
1034 Attachments.pop_back();
1035 return;
1036 }
1037
1038 for (auto I = Attachments.begin(), E = std::prev(Attachments.end()); I != E;
1039 ++I)
1040 if (I->first == ID) {
1041 *I = std::move(Attachments.back());
1042 Attachments.pop_back();
1043 return;
1044 }
1045}
1046
1047MDNode *MDAttachmentMap::lookup(unsigned ID) const {
1048 for (const auto &I : Attachments)
1049 if (I.first == ID)
1050 return I.second;
1051 return nullptr;
1052}
1053
1054void MDAttachmentMap::getAll(
1055 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1056 Result.append(Attachments.begin(), Attachments.end());
1057
1058 // Sort the resulting array so it is stable.
1059 if (Result.size() > 1)
1060 array_pod_sort(Result.begin(), Result.end());
1061}
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001062
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001063void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
1064 if (!Node && !hasMetadata())
1065 return;
1066 setMetadata(getContext().getMDKindID(Kind), Node);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001067}
1068
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001069MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
Chris Lattnera0566972009-12-29 09:01:33 +00001070 return getMetadataImpl(getContext().getMDKindID(Kind));
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001071}
1072
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00001073void Instruction::dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs) {
Rafael Espindolaab73c492014-01-28 16:56:46 +00001074 SmallSet<unsigned, 5> KnownSet;
1075 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1076
Rafael Espindolaab73c492014-01-28 16:56:46 +00001077 if (!hasMetadataHashEntry())
1078 return; // Nothing to remove!
1079
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001080 auto &InstructionMetadata = getContext().pImpl->InstructionMetadata;
Rafael Espindolaab73c492014-01-28 16:56:46 +00001081
1082 if (KnownSet.empty()) {
1083 // Just drop our entry at the store.
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001084 InstructionMetadata.erase(this);
Rafael Espindolaab73c492014-01-28 16:56:46 +00001085 setHasMetadataHashEntry(false);
1086 return;
1087 }
1088
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001089 auto &Info = InstructionMetadata[this];
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001090 Info.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1091 return !KnownSet.count(I.first);
1092 });
Rafael Espindolaab73c492014-01-28 16:56:46 +00001093
Duncan P. N. Exon Smith75ef0c02015-04-24 20:23:44 +00001094 if (Info.empty()) {
Rafael Espindolaab73c492014-01-28 16:56:46 +00001095 // Drop our entry at the store.
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001096 InstructionMetadata.erase(this);
Rafael Espindolaab73c492014-01-28 16:56:46 +00001097 setHasMetadataHashEntry(false);
1098 }
1099}
1100
Sanjay Patel942b46a2015-08-24 23:18:44 +00001101/// setMetadata - Set the metadata of the specified kind to the specified
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001102/// node. This updates/replaces metadata if already present, or removes it if
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001103/// Node is null.
1104void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1105 if (!Node && !hasMetadata())
1106 return;
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001107
Chris Lattnerc263b422010-03-30 23:03:27 +00001108 // Handle 'dbg' as a special case since it is not stored in the hash table.
1109 if (KindID == LLVMContext::MD_dbg) {
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00001110 DbgLoc = DebugLoc(Node);
Chris Lattnerc263b422010-03-30 23:03:27 +00001111 return;
1112 }
1113
Chris Lattnera0566972009-12-29 09:01:33 +00001114 // Handle the case when we're adding/updating metadata on an instruction.
1115 if (Node) {
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001116 auto &Info = getContext().pImpl->InstructionMetadata[this];
Chris Lattnerc263b422010-03-30 23:03:27 +00001117 assert(!Info.empty() == hasMetadataHashEntry() &&
1118 "HasMetadata bit is wonked");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001119 if (Info.empty())
Chris Lattnerc263b422010-03-30 23:03:27 +00001120 setHasMetadataHashEntry(true);
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001121 Info.set(KindID, *Node);
Chris Lattnera0566972009-12-29 09:01:33 +00001122 return;
1123 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001124
Chris Lattnera0566972009-12-29 09:01:33 +00001125 // Otherwise, we're removing metadata from an instruction.
Nick Lewycky4c131382011-12-27 01:17:40 +00001126 assert((hasMetadataHashEntry() ==
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001127 (getContext().pImpl->InstructionMetadata.count(this) > 0)) &&
Chris Lattnera0566972009-12-29 09:01:33 +00001128 "HasMetadata bit out of date!");
Nick Lewycky4c131382011-12-27 01:17:40 +00001129 if (!hasMetadataHashEntry())
1130 return; // Nothing to remove!
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001131 auto &Info = getContext().pImpl->InstructionMetadata[this];
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001132
Chris Lattnerc263b422010-03-30 23:03:27 +00001133 // Handle removal of an existing value.
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001134 Info.erase(KindID);
1135
1136 if (!Info.empty())
1137 return;
1138
1139 getContext().pImpl->InstructionMetadata.erase(this);
1140 setHasMetadataHashEntry(false);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001141}
1142
Hal Finkelcc39b672014-07-24 12:16:19 +00001143void Instruction::setAAMetadata(const AAMDNodes &N) {
1144 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
Hal Finkel94146652014-07-24 14:25:39 +00001145 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1146 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
Hal Finkelcc39b672014-07-24 12:16:19 +00001147}
1148
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001149MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
Chris Lattnerc263b422010-03-30 23:03:27 +00001150 // Handle 'dbg' as a special case since it is not stored in the hash table.
1151 if (KindID == LLVMContext::MD_dbg)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001152 return DbgLoc.getAsMDNode();
1153
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001154 if (!hasMetadataHashEntry())
1155 return nullptr;
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001156 auto &Info = getContext().pImpl->InstructionMetadata[this];
Chris Lattnerc263b422010-03-30 23:03:27 +00001157 assert(!Info.empty() && "bit out of sync with hash table");
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001158
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001159 return Info.lookup(KindID);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001160}
1161
Duncan P. N. Exon Smith4abd1a02014-11-01 00:26:42 +00001162void Instruction::getAllMetadataImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001163 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc263b422010-03-30 23:03:27 +00001164 Result.clear();
1165
1166 // Handle 'dbg' as a special case since it is not stored in the hash table.
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00001167 if (DbgLoc) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001168 Result.push_back(
1169 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
Chris Lattnerc263b422010-03-30 23:03:27 +00001170 if (!hasMetadataHashEntry()) return;
1171 }
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001172
Chris Lattnerc263b422010-03-30 23:03:27 +00001173 assert(hasMetadataHashEntry() &&
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001174 getContext().pImpl->InstructionMetadata.count(this) &&
Chris Lattnera0566972009-12-29 09:01:33 +00001175 "Shouldn't have called this");
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001176 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
Chris Lattnera0566972009-12-29 09:01:33 +00001177 assert(!Info.empty() && "Shouldn't have called this");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001178 Info.getAll(Result);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001179}
1180
Duncan P. N. Exon Smith3d5a02f2014-11-03 18:13:57 +00001181void Instruction::getAllMetadataOtherThanDebugLocImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001182 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001183 Result.clear();
1184 assert(hasMetadataHashEntry() &&
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001185 getContext().pImpl->InstructionMetadata.count(this) &&
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001186 "Shouldn't have called this");
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001187 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001188 assert(!Info.empty() && "Shouldn't have called this");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001189 Info.getAll(Result);
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001190}
1191
Dan Gohman48a995f2010-07-20 22:25:04 +00001192/// clearMetadataHashEntries - Clear all hashtable-based metadata from
1193/// this instruction.
1194void Instruction::clearMetadataHashEntries() {
1195 assert(hasMetadataHashEntry() && "Caller should check");
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001196 getContext().pImpl->InstructionMetadata.erase(this);
Dan Gohman48a995f2010-07-20 22:25:04 +00001197 setHasMetadataHashEntry(false);
Chris Lattner68017802009-12-29 07:44:16 +00001198}
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001199
1200MDNode *Function::getMetadata(unsigned KindID) const {
1201 if (!hasMetadata())
1202 return nullptr;
1203 return getContext().pImpl->FunctionMetadata[this].lookup(KindID);
1204}
1205
1206MDNode *Function::getMetadata(StringRef Kind) const {
1207 if (!hasMetadata())
1208 return nullptr;
1209 return getMetadata(getContext().getMDKindID(Kind));
1210}
1211
1212void Function::setMetadata(unsigned KindID, MDNode *MD) {
1213 if (MD) {
1214 if (!hasMetadata())
1215 setHasMetadataHashEntry(true);
1216
1217 getContext().pImpl->FunctionMetadata[this].set(KindID, *MD);
1218 return;
1219 }
1220
1221 // Nothing to unset.
1222 if (!hasMetadata())
1223 return;
1224
1225 auto &Store = getContext().pImpl->FunctionMetadata[this];
1226 Store.erase(KindID);
1227 if (Store.empty())
1228 clearMetadata();
1229}
1230
1231void Function::setMetadata(StringRef Kind, MDNode *MD) {
1232 if (!MD && !hasMetadata())
1233 return;
1234 setMetadata(getContext().getMDKindID(Kind), MD);
1235}
1236
1237void Function::getAllMetadata(
1238 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
1239 MDs.clear();
1240
1241 if (!hasMetadata())
1242 return;
1243
1244 getContext().pImpl->FunctionMetadata[this].getAll(MDs);
1245}
1246
1247void Function::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
1248 if (!hasMetadata())
1249 return;
1250 if (KnownIDs.empty()) {
1251 clearMetadata();
1252 return;
1253 }
1254
1255 SmallSet<unsigned, 5> KnownSet;
1256 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1257
1258 auto &Store = getContext().pImpl->FunctionMetadata[this];
1259 assert(!Store.empty());
1260
1261 Store.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1262 return !KnownSet.count(I.first);
1263 });
1264
1265 if (Store.empty())
1266 clearMetadata();
1267}
1268
1269void Function::clearMetadata() {
1270 if (!hasMetadata())
1271 return;
1272 getContext().pImpl->FunctionMetadata.erase(this);
1273 setHasMetadataHashEntry(false);
1274}
Duncan P. N. Exon Smithb56b5af2015-08-28 21:55:35 +00001275
1276void Function::setSubprogram(DISubprogram *SP) {
1277 setMetadata(LLVMContext::MD_dbg, SP);
1278}
1279
1280DISubprogram *Function::getSubprogram() const {
1281 return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));
1282}