blob: fc134e4b5d9986e2b2a78f4f8fd9e30a7e5310b7 [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
Sanjay Patel9da9c762016-03-12 20:44:58 +000042/// Canonicalize metadata arguments to intrinsics.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +000043///
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
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000123bool MetadataTracking::track(void *Ref, Metadata &MD, OwnerTy Owner) {
124 assert(Ref && "Expected live reference");
125 assert((Owner || *static_cast<Metadata **>(Ref) == &MD) &&
126 "Reference without owner must be direct");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000127 if (auto *R = ReplaceableMetadataImpl::getOrCreate(MD)) {
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000128 R->addRef(Ref, Owner);
129 return true;
130 }
131 return false;
132}
133
134void MetadataTracking::untrack(void *Ref, Metadata &MD) {
135 assert(Ref && "Expected live reference");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000136 if (auto *R = ReplaceableMetadataImpl::getIfExists(MD))
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000137 R->dropRef(Ref);
138}
139
140bool MetadataTracking::retrack(void *Ref, Metadata &MD, void *New) {
141 assert(Ref && "Expected live reference");
142 assert(New && "Expected live reference");
143 assert(Ref != New && "Expected change");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000144 if (auto *R = ReplaceableMetadataImpl::getIfExists(MD)) {
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000145 R->moveRef(Ref, New, MD);
146 return true;
147 }
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000148 assert(!isReplaceable(MD) &&
149 "Expected un-replaceable metadata, since we didn't move a reference");
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000150 return false;
151}
152
153bool MetadataTracking::isReplaceable(const Metadata &MD) {
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000154 return ReplaceableMetadataImpl::isReplaceable(MD);
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000155}
156
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000157void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000158 bool WasInserted =
159 UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
160 .second;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000161 (void)WasInserted;
162 assert(WasInserted && "Expected to add a reference");
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000163
164 ++NextIndex;
165 assert(NextIndex != 0 && "Unexpected overflow");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000166}
167
168void ReplaceableMetadataImpl::dropRef(void *Ref) {
169 bool WasErased = UseMap.erase(Ref);
170 (void)WasErased;
171 assert(WasErased && "Expected to drop a reference");
172}
173
174void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
175 const Metadata &MD) {
176 auto I = UseMap.find(Ref);
177 assert(I != UseMap.end() && "Expected to move a reference");
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000178 auto OwnerAndIndex = I->second;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000179 UseMap.erase(I);
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000180 bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
181 (void)WasInserted;
182 assert(WasInserted && "Expected to add a reference");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000183
184 // Check that the references are direct if there's no owner.
185 (void)MD;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000186 assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000187 "Reference without owner must be direct");
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000188 assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000189 "Reference without owner must be direct");
190}
191
192void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000193 if (UseMap.empty())
194 return;
195
196 // Copy out uses since UseMap will get touched below.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000197 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
198 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
199 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
200 return L.second.second < R.second.second;
201 });
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000202 for (const auto &Pair : Uses) {
Duncan P. N. Exon Smith4a4f7852015-01-14 19:56:10 +0000203 // Check that this Ref hasn't disappeared after RAUW (when updating a
204 // previous Ref).
205 if (!UseMap.count(Pair.first))
206 continue;
207
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000208 OwnerTy Owner = Pair.second.first;
209 if (!Owner) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000210 // Update unowned tracking references directly.
211 Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
212 Ref = MD;
Duncan P. N. Exon Smith121eeff2014-12-12 19:24:33 +0000213 if (MD)
214 MetadataTracking::track(Ref);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000215 UseMap.erase(Pair.first);
216 continue;
217 }
218
219 // Check for MetadataAsValue.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000220 if (Owner.is<MetadataAsValue *>()) {
221 Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000222 continue;
223 }
224
225 // There's a Metadata owner -- dispatch.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000226 Metadata *OwnerMD = Owner.get<Metadata *>();
227 switch (OwnerMD->getMetadataID()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000228#define HANDLE_METADATA_LEAF(CLASS) \
229 case Metadata::CLASS##Kind: \
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000230 cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000231 continue;
232#include "llvm/IR/Metadata.def"
233 default:
234 llvm_unreachable("Invalid metadata subclass");
235 }
236 }
237 assert(UseMap.empty() && "Expected all uses to be replaced");
238}
239
240void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
241 if (UseMap.empty())
242 return;
243
244 if (!ResolveUsers) {
245 UseMap.clear();
246 return;
247 }
248
249 // Copy out uses since UseMap could get touched below.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000250 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
251 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
252 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
253 return L.second.second < R.second.second;
254 });
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000255 UseMap.clear();
256 for (const auto &Pair : Uses) {
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000257 auto Owner = Pair.second.first;
258 if (!Owner)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000259 continue;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000260 if (Owner.is<MetadataAsValue *>())
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000261 continue;
262
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000263 // Resolve MDNodes that point at this.
264 auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000265 if (!OwnerMD)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000266 continue;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000267 if (OwnerMD->isResolved())
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000268 continue;
Duncan P. N. Exon Smith34c3d102015-01-12 19:43:15 +0000269 OwnerMD->decrementUnresolvedOperandCount();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000270 }
271}
272
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000273ReplaceableMetadataImpl *ReplaceableMetadataImpl::getOrCreate(Metadata &MD) {
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000274 if (auto *N = dyn_cast<MDNode>(&MD))
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000275 return N->isResolved() ? nullptr : N->Context.getOrCreateReplaceableUses();
276 return dyn_cast<ValueAsMetadata>(&MD);
277}
278
279ReplaceableMetadataImpl *ReplaceableMetadataImpl::getIfExists(Metadata &MD) {
280 if (auto *N = dyn_cast<MDNode>(&MD))
281 return N->isResolved() ? nullptr : N->Context.getReplaceableUses();
282 return dyn_cast<ValueAsMetadata>(&MD);
283}
284
285bool ReplaceableMetadataImpl::isReplaceable(const Metadata &MD) {
286 if (auto *N = dyn_cast<MDNode>(&MD))
287 return !N->isResolved();
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000288 return dyn_cast<ValueAsMetadata>(&MD);
289}
290
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000291static Function *getLocalFunction(Value *V) {
292 assert(V && "Expected value");
293 if (auto *A = dyn_cast<Argument>(V))
294 return A->getParent();
295 if (BasicBlock *BB = cast<Instruction>(V)->getParent())
296 return BB->getParent();
297 return nullptr;
298}
299
300ValueAsMetadata *ValueAsMetadata::get(Value *V) {
301 assert(V && "Unexpected null Value");
302
303 auto &Context = V->getContext();
304 auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
305 if (!Entry) {
306 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
307 "Expected constant or function-local value");
Owen Anderson7349ab92015-06-01 22:24:01 +0000308 assert(!V->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000309 "Expected this to be the only metadata use");
Owen Anderson7349ab92015-06-01 22:24:01 +0000310 V->IsUsedByMD = true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000311 if (auto *C = dyn_cast<Constant>(V))
Duncan P. N. Exon Smith1c00c9f2015-01-05 20:41:25 +0000312 Entry = new ConstantAsMetadata(C);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000313 else
Duncan P. N. Exon Smith1c00c9f2015-01-05 20:41:25 +0000314 Entry = new LocalAsMetadata(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000315 }
316
317 return Entry;
318}
319
320ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
321 assert(V && "Unexpected null Value");
322 return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
323}
324
325void ValueAsMetadata::handleDeletion(Value *V) {
326 assert(V && "Expected valid value");
327
328 auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
329 auto I = Store.find(V);
330 if (I == Store.end())
331 return;
332
333 // Remove old entry from the map.
334 ValueAsMetadata *MD = I->second;
335 assert(MD && "Expected valid metadata");
336 assert(MD->getValue() == V && "Expected valid mapping");
337 Store.erase(I);
338
339 // Delete the metadata.
340 MD->replaceAllUsesWith(nullptr);
341 delete MD;
342}
343
344void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
345 assert(From && "Expected valid value");
346 assert(To && "Expected valid value");
347 assert(From != To && "Expected changed value");
348 assert(From->getType() == To->getType() && "Unexpected type change");
349
350 LLVMContext &Context = From->getType()->getContext();
351 auto &Store = Context.pImpl->ValuesAsMetadata;
352 auto I = Store.find(From);
353 if (I == Store.end()) {
Owen Anderson7349ab92015-06-01 22:24:01 +0000354 assert(!From->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000355 "Expected From not to be used by metadata");
356 return;
357 }
358
359 // Remove old entry from the map.
Owen Anderson7349ab92015-06-01 22:24:01 +0000360 assert(From->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000361 "Expected From to be used by metadata");
Owen Anderson7349ab92015-06-01 22:24:01 +0000362 From->IsUsedByMD = false;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000363 ValueAsMetadata *MD = I->second;
364 assert(MD && "Expected valid metadata");
365 assert(MD->getValue() == From && "Expected valid mapping");
366 Store.erase(I);
367
368 if (isa<LocalAsMetadata>(MD)) {
369 if (auto *C = dyn_cast<Constant>(To)) {
370 // Local became a constant.
371 MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
372 delete MD;
373 return;
374 }
375 if (getLocalFunction(From) && getLocalFunction(To) &&
376 getLocalFunction(From) != getLocalFunction(To)) {
377 // Function changed.
378 MD->replaceAllUsesWith(nullptr);
379 delete MD;
380 return;
381 }
382 } else if (!isa<Constant>(To)) {
383 // Changed to function-local value.
384 MD->replaceAllUsesWith(nullptr);
385 delete MD;
386 return;
387 }
388
389 auto *&Entry = Store[To];
390 if (Entry) {
391 // The target already exists.
392 MD->replaceAllUsesWith(Entry);
393 delete MD;
394 return;
395 }
396
397 // Update MD in place (and update the map entry).
Owen Anderson7349ab92015-06-01 22:24:01 +0000398 assert(!To->IsUsedByMD &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000399 "Expected this to be the only metadata use");
Owen Anderson7349ab92015-06-01 22:24:01 +0000400 To->IsUsedByMD = true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000401 MD->V = To;
402 Entry = MD;
403}
Duncan P. N. Exon Smitha69934f2014-11-14 18:42:09 +0000404
Devang Patela4f43fb2009-07-28 21:49:47 +0000405//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000406// MDString implementation.
Owen Anderson0087fe62009-07-31 21:35:40 +0000407//
Chris Lattner5a409bd2009-12-28 08:30:43 +0000408
Devang Pateldcb99d32009-10-22 00:10:15 +0000409MDString *MDString::get(LLVMContext &Context, StringRef Str) {
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000410 auto &Store = Context.pImpl->MDStringCache;
Mehdi Aminicb708b22016-03-25 05:58:04 +0000411 auto I = Store.emplace_second(Str);
412 auto &MapEntry = I.first->getValue();
413 if (!I.second)
414 return &MapEntry;
415 MapEntry.Entry = &*I.first;
416 return &MapEntry;
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000417}
418
419StringRef MDString::getString() const {
Duncan P. N. Exon Smithc1a664f2014-12-05 01:41:34 +0000420 assert(Entry && "Expected to find string map entry");
421 return Entry->first();
Owen Anderson0087fe62009-07-31 21:35:40 +0000422}
423
424//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000425// MDNode implementation.
Devang Patela4f43fb2009-07-28 21:49:47 +0000426//
Chris Lattner74a6ad62009-12-28 07:41:54 +0000427
James Y Knight8096d342015-06-17 01:21:20 +0000428// Assert that the MDNode types will not be unaligned by the objects
429// prepended to them.
430#define HANDLE_MDNODE_LEAF(CLASS) \
James Y Knightf27e4412015-06-17 13:53:12 +0000431 static_assert( \
432 llvm::AlignOf<uint64_t>::Alignment >= llvm::AlignOf<CLASS>::Alignment, \
433 "Alignment is insufficient after objects prepended to " #CLASS);
James Y Knight8096d342015-06-17 01:21:20 +0000434#include "llvm/IR/Metadata.def"
435
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000436void *MDNode::operator new(size_t Size, unsigned NumOps) {
James Y Knight8096d342015-06-17 01:21:20 +0000437 size_t OpSize = NumOps * sizeof(MDOperand);
438 // uint64_t is the most aligned type we need support (ensured by static_assert
439 // above)
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000440 OpSize = alignTo(OpSize, llvm::alignOf<uint64_t>());
James Y Knight8096d342015-06-17 01:21:20 +0000441 void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
Duncan P. N. Exon Smith22600ff2014-12-09 23:56:39 +0000442 MDOperand *O = static_cast<MDOperand *>(Ptr);
James Y Knight8096d342015-06-17 01:21:20 +0000443 for (MDOperand *E = O - NumOps; O != E; --O)
444 (void)new (O - 1) MDOperand;
445 return Ptr;
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000446}
447
Naomi Musgrave21c1bc42015-08-31 21:06:08 +0000448void MDNode::operator delete(void *Mem) {
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000449 MDNode *N = static_cast<MDNode *>(Mem);
James Y Knight8096d342015-06-17 01:21:20 +0000450 size_t OpSize = N->NumOperands * sizeof(MDOperand);
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000451 OpSize = alignTo(OpSize, llvm::alignOf<uint64_t>());
James Y Knight8096d342015-06-17 01:21:20 +0000452
Duncan P. N. Exon Smith22600ff2014-12-09 23:56:39 +0000453 MDOperand *O = static_cast<MDOperand *>(Mem);
454 for (MDOperand *E = O - N->NumOperands; O != E; --O)
455 (O - 1)->~MDOperand();
James Y Knight8096d342015-06-17 01:21:20 +0000456 ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000457}
458
Duncan P. N. Exon Smithf1340452015-01-19 18:36:18 +0000459MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
Duncan P. N. Exon Smithfed199a2015-01-20 00:01:43 +0000460 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
461 : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
462 NumUnresolved(0), Context(Context) {
463 unsigned Op = 0;
464 for (Metadata *MD : Ops1)
465 setOperand(Op++, MD);
466 for (Metadata *MD : Ops2)
467 setOperand(Op++, MD);
Duncan P. N. Exon Smith2711ca72015-01-19 19:02:06 +0000468
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000469 if (!isUniqued())
Duncan P. N. Exon Smith5e5b8502015-01-07 22:24:46 +0000470 return;
471
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000472 // Count the unresolved operands. If there are any, RAUW support will be
473 // added lazily on first reference.
474 countUnresolvedOperands();
Devang Patela4f43fb2009-07-28 21:49:47 +0000475}
476
Duncan P. N. Exon Smith03e05832015-01-20 02:56:57 +0000477TempMDNode MDNode::clone() const {
478 switch (getMetadataID()) {
479 default:
480 llvm_unreachable("Invalid MDNode subclass");
481#define HANDLE_MDNODE_LEAF(CLASS) \
482 case CLASS##Kind: \
483 return cast<CLASS>(this)->cloneImpl();
484#include "llvm/IR/Metadata.def"
485 }
486}
487
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000488static bool isOperandUnresolved(Metadata *Op) {
489 if (auto *N = dyn_cast_or_null<MDNode>(Op))
490 return !N->isResolved();
491 return false;
492}
493
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000494void MDNode::countUnresolvedOperands() {
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000495 assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000496 assert(isUniqued() && "Expected this to be uniqued");
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000497 NumUnresolved = std::count_if(op_begin(), op_end(), isOperandUnresolved);
Duncan P. N. Exon Smithc5a0e2e2015-01-19 22:18:29 +0000498}
499
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000500void MDNode::makeUniqued() {
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000501 assert(isTemporary() && "Expected this to be temporary");
502 assert(!isResolved() && "Expected this to be unresolved");
503
Duncan P. N. Exon Smithcb33d6f2015-03-31 20:50:50 +0000504 // Enable uniquing callbacks.
505 for (auto &Op : mutable_operands())
506 Op.reset(Op.get(), this);
507
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000508 // Make this 'uniqued'.
509 Storage = Uniqued;
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000510 countUnresolvedOperands();
511 if (!NumUnresolved) {
512 dropReplaceableUses();
513 assert(isResolved() && "Expected this to be resolved");
514 }
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000515
516 assert(isUniqued() && "Expected this to be uniqued");
517}
518
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000519void MDNode::makeDistinct() {
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000520 assert(isTemporary() && "Expected this to be temporary");
521 assert(!isResolved() && "Expected this to be unresolved");
522
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000523 // Drop RAUW support and store as a distinct node.
524 dropReplaceableUses();
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000525 storeDistinctInContext();
526
527 assert(isDistinct() && "Expected this to be distinct");
528 assert(isResolved() && "Expected this to be resolved");
529}
530
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000531void MDNode::resolve() {
Duncan P. N. Exon Smithb8f79602015-01-19 19:26:24 +0000532 assert(isUniqued() && "Expected this to be uniqued");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000533 assert(!isResolved() && "Expected this to be unresolved");
534
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000535 NumUnresolved = 0;
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000536 dropReplaceableUses();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000537
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000538 assert(isResolved() && "Expected this to be resolved");
539}
540
541void MDNode::dropReplaceableUses() {
542 assert(!NumUnresolved && "Unexpected unresolved operand");
543
544 // Drop any RAUW support.
545 if (Context.hasReplaceableUses())
546 Context.takeReplaceableUses()->resolveAllUses();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000547}
548
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000549void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000550 assert(isUniqued() && "Expected this to be uniqued");
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000551 assert(NumUnresolved != 0 && "Expected unresolved operands");
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000552
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000553 // Check if an operand was resolved.
Duncan P. N. Exon Smith845755c42015-01-13 00:46:34 +0000554 if (!isOperandUnresolved(Old)) {
555 if (isOperandUnresolved(New))
556 // An operand was un-resolved!
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000557 ++NumUnresolved;
Duncan P. N. Exon Smith845755c42015-01-13 00:46:34 +0000558 } else if (!isOperandUnresolved(New))
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000559 decrementUnresolvedOperandCount();
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000560}
561
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000562void MDNode::decrementUnresolvedOperandCount() {
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000563 assert(!isResolved() && "Expected this to be unresolved");
564 if (isTemporary())
565 return;
566
567 assert(isUniqued() && "Expected this to be uniqued");
568 if (--NumUnresolved)
569 return;
570
571 // Last unresolved operand has just been resolved.
572 dropReplaceableUses();
573 assert(isResolved() && "Expected this to become resolved");
Duncan P. N. Exon Smith34c3d102015-01-12 19:43:15 +0000574}
575
Teresa Johnsonb703c772016-03-29 18:24:19 +0000576void MDNode::resolveCycles() {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000577 if (isResolved())
578 return;
579
580 // Resolve this node immediately.
581 resolve();
582
583 // Resolve all operands.
584 for (const auto &Op : operands()) {
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000585 auto *N = dyn_cast_or_null<MDNode>(Op);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000586 if (!N)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000587 continue;
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000588
589 assert(!N->isTemporary() &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000590 "Expected all forward declarations to be resolved");
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000591 if (!N->isResolved())
592 N->resolveCycles();
Chris Lattner8cb6c342009-12-31 01:05:46 +0000593 }
Duncan P. N. Exon Smith50846f82014-11-18 00:37:17 +0000594}
595
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000596static bool hasSelfReference(MDNode *N) {
597 for (Metadata *MD : N->operands())
598 if (MD == N)
599 return true;
600 return false;
601}
602
603MDNode *MDNode::replaceWithPermanentImpl() {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000604 switch (getMetadataID()) {
605 default:
606 // If this type isn't uniquable, replace with a distinct node.
607 return replaceWithDistinctImpl();
608
609#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
610 case CLASS##Kind: \
611 break;
612#include "llvm/IR/Metadata.def"
613 }
614
615 // Even if this type is uniquable, self-references have to be distinct.
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000616 if (hasSelfReference(this))
617 return replaceWithDistinctImpl();
618 return replaceWithUniquedImpl();
619}
620
Duncan P. N. Exon Smith86475292015-01-19 23:17:09 +0000621MDNode *MDNode::replaceWithUniquedImpl() {
622 // Try to uniquify in place.
623 MDNode *UniquedNode = uniquify();
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000624
Duncan P. N. Exon Smith86475292015-01-19 23:17:09 +0000625 if (UniquedNode == this) {
626 makeUniqued();
627 return this;
628 }
629
630 // Collision, so RAUW instead.
631 replaceAllUsesWith(UniquedNode);
632 deleteAsSubclass();
633 return UniquedNode;
634}
635
636MDNode *MDNode::replaceWithDistinctImpl() {
637 makeDistinct();
638 return this;
639}
640
Duncan P. N. Exon Smith118632d2015-01-12 20:09:34 +0000641void MDTuple::recalculateHash() {
Duncan P. N. Exon Smith93e983e2015-01-19 22:53:18 +0000642 setHash(MDTupleInfo::KeyTy::calculateHash(this));
Duncan P. N. Exon Smith967629e2015-01-12 19:16:34 +0000643}
644
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000645void MDNode::dropAllReferences() {
646 for (unsigned I = 0, E = NumOperands; I != E; ++I)
647 setOperand(I, nullptr);
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000648 if (Context.hasReplaceableUses()) {
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000649 Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
650 (void)Context.takeReplaceableUses();
651 }
Chris Lattner8cb6c342009-12-31 01:05:46 +0000652}
653
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000654void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000655 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
656 assert(Op < getNumOperands() && "Expected valid operand");
657
Duncan P. N. Exon Smith3d580562015-01-19 19:28:28 +0000658 if (!isUniqued()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000659 // This node is not uniqued. Just set the operand and be done with it.
660 setOperand(Op, New);
661 return;
Duncan Sandsc2928c62010-05-04 12:43:36 +0000662 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000663
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000664 // This node is uniqued.
665 eraseFromStore();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000666
667 Metadata *Old = getOperand(Op);
668 setOperand(Op, New);
669
Duncan P. N. Exon Smithbcd960a2015-01-05 23:31:54 +0000670 // Drop uniquing for self-reference cycles.
671 if (New == this) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000672 if (!isResolved())
673 resolve();
Duncan P. N. Exon Smithf08b8b42015-01-19 19:25:33 +0000674 storeDistinctInContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000675 return;
676 }
677
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000678 // Re-unique the node.
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000679 auto *Uniqued = uniquify();
680 if (Uniqued == this) {
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000681 if (!isResolved())
682 resolveAfterOperandChange(Old, New);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000683 return;
684 }
685
686 // Collision.
687 if (!isResolved()) {
688 // Still unresolved, so RAUW.
Duncan P. N. Exon Smithd9e6eb72015-01-12 19:36:35 +0000689 //
690 // First, clear out all operands to prevent any recursion (similar to
691 // dropAllReferences(), but we still need the use-list).
692 for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
693 setOperand(O, nullptr);
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000694 if (Context.hasReplaceableUses())
695 Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000696 deleteAsSubclass();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000697 return;
698 }
699
Duncan P. N. Exon Smithd9e6eb72015-01-12 19:36:35 +0000700 // Store in non-uniqued form if RAUW isn't possible.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000701 storeDistinctInContext();
Victor Hernandeze5f2af72010-01-20 04:45:57 +0000702}
703
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000704void MDNode::deleteAsSubclass() {
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000705 switch (getMetadataID()) {
706 default:
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000707 llvm_unreachable("Invalid subclass of MDNode");
708#define HANDLE_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000709 case CLASS##Kind: \
710 delete cast<CLASS>(this); \
711 break;
712#include "llvm/IR/Metadata.def"
713 }
714}
715
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000716template <class T, class InfoT>
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000717static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
718 if (T *U = getUniqued(Store, N))
719 return U;
720
721 Store.insert(N);
722 return N;
723}
724
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000725template <class NodeTy> struct MDNode::HasCachedHash {
726 typedef char Yes[1];
727 typedef char No[2];
728 template <class U, U Val> struct SFINAE {};
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000729
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000730 template <class U>
731 static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
732 template <class U> static No &check(...);
733
734 static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
735};
736
737MDNode *MDNode::uniquify() {
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000738 assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
739
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000740 // Try to insert into uniquing store.
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000741 switch (getMetadataID()) {
742 default:
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000743 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
744#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000745 case CLASS##Kind: { \
746 CLASS *SubclassThis = cast<CLASS>(this); \
747 std::integral_constant<bool, HasCachedHash<CLASS>::value> \
748 ShouldRecalculateHash; \
749 dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
750 return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
751 }
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000752#include "llvm/IR/Metadata.def"
753 }
754}
755
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000756void MDNode::eraseFromStore() {
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000757 switch (getMetadataID()) {
758 default:
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000759 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
760#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000761 case CLASS##Kind: \
Duncan P. N. Exon Smith6cf10d22015-01-19 22:47:08 +0000762 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000763 break;
764#include "llvm/IR/Metadata.def"
765 }
766}
767
Duncan P. N. Exon Smithac3128d2015-01-12 20:13:56 +0000768MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000769 StorageType Storage, bool ShouldCreate) {
770 unsigned Hash = 0;
771 if (Storage == Uniqued) {
772 MDTupleInfo::KeyTy Key(MDs);
Duncan P. N. Exon Smithb57f9e92015-01-19 20:16:50 +0000773 if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
774 return N;
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000775 if (!ShouldCreate)
776 return nullptr;
Duncan P. N. Exon Smith93e983e2015-01-19 22:53:18 +0000777 Hash = Key.getHash();
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000778 } else {
779 assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
780 }
Duncan Sands26a80f32012-03-31 08:20:11 +0000781
Duncan P. N. Exon Smith5b8c4402015-01-19 20:18:13 +0000782 return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
783 Storage, Context.pImpl->MDTuples);
Duncan P. N. Exon Smith5e5b8502015-01-07 22:24:46 +0000784}
785
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000786void MDNode::deleteTemporary(MDNode *N) {
787 assert(N->isTemporary() && "Expected temporary node");
Duncan P. N. Exon Smith8d536972015-01-22 21:36:45 +0000788 N->replaceAllUsesWith(nullptr);
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000789 N->deleteAsSubclass();
Dan Gohman16a5d982010-08-20 22:02:26 +0000790}
791
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000792void MDNode::storeDistinctInContext() {
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000793 assert(!Context.hasReplaceableUses() && "Unexpected replaceable uses");
794 assert(!NumUnresolved && "Unexpected unresolved nodes");
Duncan P. N. Exon Smithf1340452015-01-19 18:36:18 +0000795 Storage = Distinct;
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000796 assert(isResolved() && "Expected this to be resolved");
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000797
798 // Reset the hash.
799 switch (getMetadataID()) {
800 default:
801 llvm_unreachable("Invalid subclass of MDNode");
802#define HANDLE_MDNODE_LEAF(CLASS) \
803 case CLASS##Kind: { \
804 std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
805 dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
806 break; \
807 }
808#include "llvm/IR/Metadata.def"
809 }
810
Duncan P. N. Exon Smithde03ff52015-01-13 20:44:56 +0000811 getContext().pImpl->DistinctMDNodes.insert(this);
Devang Patel82ab3f82010-02-18 20:53:16 +0000812}
Chris Lattnerf543eff2009-12-28 09:12:35 +0000813
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000814void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
815 if (getOperand(I) == New)
Devang Patelf7188322009-09-03 01:39:20 +0000816 return;
Devang Patelf7188322009-09-03 01:39:20 +0000817
Duncan P. N. Exon Smithde03a8b2015-01-19 18:45:35 +0000818 if (!isUniqued()) {
Duncan P. N. Exon Smithdaa335a2015-01-12 18:01:45 +0000819 setOperand(I, New);
Duncan P. N. Exon Smithf39c3b82014-11-17 23:28:21 +0000820 return;
821 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +0000822
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000823 handleChangedOperand(mutable_begin() + I, New);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000824}
Chris Lattnerc6d17e22009-12-28 09:24:53 +0000825
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000826void MDNode::setOperand(unsigned I, Metadata *New) {
827 assert(I < NumOperands);
Duncan P. N. Exon Smithefdf2852015-01-19 19:29:25 +0000828 mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
Devang Patelf7188322009-09-03 01:39:20 +0000829}
830
Sanjay Patel9da9c762016-03-12 20:44:58 +0000831/// Get a node or a self-reference that looks like it.
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000832///
833/// Special handling for finding self-references, for use by \a
834/// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
835/// when self-referencing nodes were still uniqued. If the first operand has
836/// the same operands as \c Ops, return the first operand instead.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000837static MDNode *getOrSelfReference(LLVMContext &Context,
838 ArrayRef<Metadata *> Ops) {
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000839 if (!Ops.empty())
840 if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
841 if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
842 for (unsigned I = 1, E = Ops.size(); I != E; ++I)
843 if (Ops[I] != N->getOperand(I))
844 return MDNode::get(Context, Ops);
845 return N;
846 }
847
848 return MDNode::get(Context, Ops);
849}
850
Hal Finkel94146652014-07-24 14:25:39 +0000851MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
852 if (!A)
853 return B;
854 if (!B)
855 return A;
856
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000857 SmallVector<Metadata *, 4> MDs;
858 MDs.reserve(A->getNumOperands() + B->getNumOperands());
859 MDs.append(A->op_begin(), A->op_end());
860 MDs.append(B->op_begin(), B->op_end());
Hal Finkel94146652014-07-24 14:25:39 +0000861
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000862 // FIXME: This preserves long-standing behaviour, but is it really the right
863 // behaviour? Or was that an unintended side-effect of node uniquing?
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000864 return getOrSelfReference(A->getContext(), MDs);
Hal Finkel94146652014-07-24 14:25:39 +0000865}
866
867MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
868 if (!A || !B)
869 return nullptr;
870
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000871 SmallVector<Metadata *, 4> MDs;
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000872 for (Metadata *MD : A->operands())
873 if (std::find(B->op_begin(), B->op_end(), MD) != B->op_end())
874 MDs.push_back(MD);
Hal Finkel94146652014-07-24 14:25:39 +0000875
Duncan P. N. Exon Smithac8ee282014-12-07 19:52:06 +0000876 // FIXME: This preserves long-standing behaviour, but is it really the right
877 // behaviour? Or was that an unintended side-effect of node uniquing?
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000878 return getOrSelfReference(A->getContext(), MDs);
Hal Finkel94146652014-07-24 14:25:39 +0000879}
880
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +0000881MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
882 if (!A || !B)
883 return nullptr;
884
885 SmallVector<Metadata *, 4> MDs(B->op_begin(), B->op_end());
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000886 for (Metadata *MD : A->operands())
887 if (std::find(B->op_begin(), B->op_end(), MD) == B->op_end())
888 MDs.push_back(MD);
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +0000889
890 // FIXME: This preserves long-standing behaviour, but is it really the right
891 // behaviour? Or was that an unintended side-effect of node uniquing?
892 return getOrSelfReference(A->getContext(), MDs);
893}
894
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000895MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
896 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000897 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000898
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000899 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
900 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000901 if (AVal.compare(BVal) == APFloat::cmpLessThan)
902 return A;
903 return B;
904}
905
906static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
907 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
908}
909
910static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
911 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
912}
913
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000914static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
915 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000916 ConstantRange NewRange(Low->getValue(), High->getValue());
917 unsigned Size = EndPoints.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000918 APInt LB = EndPoints[Size - 2]->getValue();
919 APInt LE = EndPoints[Size - 1]->getValue();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000920 ConstantRange LastRange(LB, LE);
921 if (canBeMerged(NewRange, LastRange)) {
922 ConstantRange Union = LastRange.unionWith(NewRange);
923 Type *Ty = High->getType();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000924 EndPoints[Size - 2] =
925 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
926 EndPoints[Size - 1] =
927 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000928 return true;
929 }
930 return false;
931}
932
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000933static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
934 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000935 if (!EndPoints.empty())
936 if (tryMergeRange(EndPoints, Low, High))
937 return;
938
939 EndPoints.push_back(Low);
940 EndPoints.push_back(High);
941}
942
943MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
944 // Given two ranges, we want to compute the union of the ranges. This
945 // is slightly complitade by having to combine the intervals and merge
946 // the ones that overlap.
947
948 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000949 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000950
951 if (A == B)
952 return A;
953
954 // First, walk both lists in older of the lower boundary of each interval.
955 // 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 +0000956 SmallVector<ConstantInt *, 4> EndPoints;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000957 int AI = 0;
958 int BI = 0;
959 int AN = A->getNumOperands() / 2;
960 int BN = B->getNumOperands() / 2;
961 while (AI < AN && BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000962 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
963 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000964
965 if (ALow->getValue().slt(BLow->getValue())) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000966 addRange(EndPoints, ALow,
967 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000968 ++AI;
969 } else {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000970 addRange(EndPoints, BLow,
971 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000972 ++BI;
973 }
974 }
975 while (AI < AN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000976 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
977 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000978 ++AI;
979 }
980 while (BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000981 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
982 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000983 ++BI;
984 }
985
986 // If we have more than 2 ranges (4 endpoints) we have to try to merge
987 // the last and first ones.
988 unsigned Size = EndPoints.size();
989 if (Size > 4) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000990 ConstantInt *FB = EndPoints[0];
991 ConstantInt *FE = EndPoints[1];
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000992 if (tryMergeRange(EndPoints, FB, FE)) {
993 for (unsigned i = 0; i < Size - 2; ++i) {
994 EndPoints[i] = EndPoints[i + 2];
995 }
996 EndPoints.resize(Size - 2);
997 }
998 }
999
1000 // If in the end we have a single range, it is possible that it is now the
1001 // full range. Just drop the metadata in that case.
1002 if (EndPoints.size() == 2) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001003 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001004 if (Range.isFullSet())
Craig Topperc6207612014-04-09 06:08:46 +00001005 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001006 }
1007
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001008 SmallVector<Metadata *, 4> MDs;
1009 MDs.reserve(EndPoints.size());
1010 for (auto *I : EndPoints)
1011 MDs.push_back(ConstantAsMetadata::get(I));
1012 return MDNode::get(A->getContext(), MDs);
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001013}
1014
Artur Pilipenko5c5011d2015-11-02 17:53:51 +00001015MDNode *MDNode::getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B) {
1016 if (!A || !B)
1017 return nullptr;
1018
1019 ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
1020 ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
1021 if (AVal->getZExtValue() < BVal->getZExtValue())
1022 return A;
1023 return B;
1024}
1025
Devang Patel05a26fb2009-07-29 00:33:07 +00001026//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +00001027// NamedMDNode implementation.
Devang Patel05a26fb2009-07-29 00:33:07 +00001028//
Devang Patel943ddf62010-01-12 18:34:06 +00001029
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001030static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
1031 return *(SmallVector<TrackingMDRef, 4> *)Operands;
Chris Lattner1bc810b2009-12-28 08:07:14 +00001032}
1033
Dan Gohman2637cc12010-07-21 23:38:33 +00001034NamedMDNode::NamedMDNode(const Twine &N)
Duncan P. N. Exon Smithc5754a62014-11-05 18:16:03 +00001035 : Name(N.str()), Parent(nullptr),
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001036 Operands(new SmallVector<TrackingMDRef, 4>()) {}
Devang Patel5c310be2009-08-11 18:01:24 +00001037
Chris Lattner1bc810b2009-12-28 08:07:14 +00001038NamedMDNode::~NamedMDNode() {
1039 dropAllReferences();
1040 delete &getNMDOps(Operands);
1041}
1042
Chris Lattner9b493022009-12-31 01:22:29 +00001043unsigned NamedMDNode::getNumOperands() const {
Chris Lattner1bc810b2009-12-28 08:07:14 +00001044 return (unsigned)getNMDOps(Operands).size();
1045}
1046
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001047MDNode *NamedMDNode::getOperand(unsigned i) const {
Chris Lattner9b493022009-12-31 01:22:29 +00001048 assert(i < getNumOperands() && "Invalid Operand number!");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001049 auto *N = getNMDOps(Operands)[i].get();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001050 return cast_or_null<MDNode>(N);
Chris Lattner1bc810b2009-12-28 08:07:14 +00001051}
1052
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001053void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
Chris Lattner1bc810b2009-12-28 08:07:14 +00001054
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001055void NamedMDNode::setOperand(unsigned I, MDNode *New) {
1056 assert(I < getNumOperands() && "Invalid operand number");
1057 getNMDOps(Operands)[I].reset(New);
1058}
1059
Devang Patel79238d72009-08-03 06:19:01 +00001060void NamedMDNode::eraseFromParent() {
Dan Gohman2637cc12010-07-21 23:38:33 +00001061 getParent()->eraseNamedMetadata(this);
Devang Patel79238d72009-08-03 06:19:01 +00001062}
1063
Devang Patel79238d72009-08-03 06:19:01 +00001064void NamedMDNode::dropAllReferences() {
Chris Lattner1bc810b2009-12-28 08:07:14 +00001065 getNMDOps(Operands).clear();
Devang Patel79238d72009-08-03 06:19:01 +00001066}
1067
Devang Patelfcfee0f2010-01-07 19:39:36 +00001068StringRef NamedMDNode::getName() const {
1069 return StringRef(Name);
1070}
Devang Pateld5497a4b2009-09-16 18:09:00 +00001071
1072//===----------------------------------------------------------------------===//
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001073// Instruction Metadata method implementations.
1074//
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001075void MDAttachmentMap::set(unsigned ID, MDNode &MD) {
1076 for (auto &I : Attachments)
1077 if (I.first == ID) {
1078 I.second.reset(&MD);
1079 return;
1080 }
1081 Attachments.emplace_back(std::piecewise_construct, std::make_tuple(ID),
1082 std::make_tuple(&MD));
1083}
1084
1085void MDAttachmentMap::erase(unsigned ID) {
1086 if (empty())
1087 return;
1088
1089 // Common case is one/last value.
1090 if (Attachments.back().first == ID) {
1091 Attachments.pop_back();
1092 return;
1093 }
1094
1095 for (auto I = Attachments.begin(), E = std::prev(Attachments.end()); I != E;
1096 ++I)
1097 if (I->first == ID) {
1098 *I = std::move(Attachments.back());
1099 Attachments.pop_back();
1100 return;
1101 }
1102}
1103
1104MDNode *MDAttachmentMap::lookup(unsigned ID) const {
1105 for (const auto &I : Attachments)
1106 if (I.first == ID)
1107 return I.second;
1108 return nullptr;
1109}
1110
1111void MDAttachmentMap::getAll(
1112 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1113 Result.append(Attachments.begin(), Attachments.end());
1114
1115 // Sort the resulting array so it is stable.
1116 if (Result.size() > 1)
1117 array_pod_sort(Result.begin(), Result.end());
1118}
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001119
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001120void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
1121 if (!Node && !hasMetadata())
1122 return;
1123 setMetadata(getContext().getMDKindID(Kind), Node);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001124}
1125
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001126MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
Chris Lattnera0566972009-12-29 09:01:33 +00001127 return getMetadataImpl(getContext().getMDKindID(Kind));
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001128}
1129
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00001130void Instruction::dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs) {
Rafael Espindolaab73c492014-01-28 16:56:46 +00001131 SmallSet<unsigned, 5> KnownSet;
1132 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1133
Rafael Espindolaab73c492014-01-28 16:56:46 +00001134 if (!hasMetadataHashEntry())
1135 return; // Nothing to remove!
1136
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001137 auto &InstructionMetadata = getContext().pImpl->InstructionMetadata;
Rafael Espindolaab73c492014-01-28 16:56:46 +00001138
1139 if (KnownSet.empty()) {
1140 // Just drop our entry at the store.
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001141 InstructionMetadata.erase(this);
Rafael Espindolaab73c492014-01-28 16:56:46 +00001142 setHasMetadataHashEntry(false);
1143 return;
1144 }
1145
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001146 auto &Info = InstructionMetadata[this];
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001147 Info.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1148 return !KnownSet.count(I.first);
1149 });
Rafael Espindolaab73c492014-01-28 16:56:46 +00001150
Duncan P. N. Exon Smith75ef0c02015-04-24 20:23:44 +00001151 if (Info.empty()) {
Rafael Espindolaab73c492014-01-28 16:56:46 +00001152 // Drop our entry at the store.
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001153 InstructionMetadata.erase(this);
Rafael Espindolaab73c492014-01-28 16:56:46 +00001154 setHasMetadataHashEntry(false);
1155 }
1156}
1157
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001158void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1159 if (!Node && !hasMetadata())
1160 return;
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001161
Chris Lattnerc263b422010-03-30 23:03:27 +00001162 // Handle 'dbg' as a special case since it is not stored in the hash table.
1163 if (KindID == LLVMContext::MD_dbg) {
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00001164 DbgLoc = DebugLoc(Node);
Chris Lattnerc263b422010-03-30 23:03:27 +00001165 return;
1166 }
1167
Chris Lattnera0566972009-12-29 09:01:33 +00001168 // Handle the case when we're adding/updating metadata on an instruction.
1169 if (Node) {
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001170 auto &Info = getContext().pImpl->InstructionMetadata[this];
Chris Lattnerc263b422010-03-30 23:03:27 +00001171 assert(!Info.empty() == hasMetadataHashEntry() &&
1172 "HasMetadata bit is wonked");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001173 if (Info.empty())
Chris Lattnerc263b422010-03-30 23:03:27 +00001174 setHasMetadataHashEntry(true);
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001175 Info.set(KindID, *Node);
Chris Lattnera0566972009-12-29 09:01:33 +00001176 return;
1177 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001178
Chris Lattnera0566972009-12-29 09:01:33 +00001179 // Otherwise, we're removing metadata from an instruction.
Nick Lewycky4c131382011-12-27 01:17:40 +00001180 assert((hasMetadataHashEntry() ==
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001181 (getContext().pImpl->InstructionMetadata.count(this) > 0)) &&
Chris Lattnera0566972009-12-29 09:01:33 +00001182 "HasMetadata bit out of date!");
Nick Lewycky4c131382011-12-27 01:17:40 +00001183 if (!hasMetadataHashEntry())
1184 return; // Nothing to remove!
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001185 auto &Info = getContext().pImpl->InstructionMetadata[this];
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001186
Chris Lattnerc263b422010-03-30 23:03:27 +00001187 // Handle removal of an existing value.
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001188 Info.erase(KindID);
1189
1190 if (!Info.empty())
1191 return;
1192
1193 getContext().pImpl->InstructionMetadata.erase(this);
1194 setHasMetadataHashEntry(false);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001195}
1196
Hal Finkelcc39b672014-07-24 12:16:19 +00001197void Instruction::setAAMetadata(const AAMDNodes &N) {
1198 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
Hal Finkel94146652014-07-24 14:25:39 +00001199 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1200 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
Hal Finkelcc39b672014-07-24 12:16:19 +00001201}
1202
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001203MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
Chris Lattnerc263b422010-03-30 23:03:27 +00001204 // Handle 'dbg' as a special case since it is not stored in the hash table.
1205 if (KindID == LLVMContext::MD_dbg)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001206 return DbgLoc.getAsMDNode();
1207
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001208 if (!hasMetadataHashEntry())
1209 return nullptr;
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001210 auto &Info = getContext().pImpl->InstructionMetadata[this];
Chris Lattnerc263b422010-03-30 23:03:27 +00001211 assert(!Info.empty() && "bit out of sync with hash table");
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001212
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001213 return Info.lookup(KindID);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001214}
1215
Duncan P. N. Exon Smith4abd1a02014-11-01 00:26:42 +00001216void Instruction::getAllMetadataImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001217 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc263b422010-03-30 23:03:27 +00001218 Result.clear();
1219
1220 // 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 +00001221 if (DbgLoc) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001222 Result.push_back(
1223 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
Chris Lattnerc263b422010-03-30 23:03:27 +00001224 if (!hasMetadataHashEntry()) return;
1225 }
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001226
Chris Lattnerc263b422010-03-30 23:03:27 +00001227 assert(hasMetadataHashEntry() &&
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001228 getContext().pImpl->InstructionMetadata.count(this) &&
Chris Lattnera0566972009-12-29 09:01:33 +00001229 "Shouldn't have called this");
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001230 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
Chris Lattnera0566972009-12-29 09:01:33 +00001231 assert(!Info.empty() && "Shouldn't have called this");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001232 Info.getAll(Result);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001233}
1234
Duncan P. N. Exon Smith3d5a02f2014-11-03 18:13:57 +00001235void Instruction::getAllMetadataOtherThanDebugLocImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001236 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001237 Result.clear();
1238 assert(hasMetadataHashEntry() &&
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001239 getContext().pImpl->InstructionMetadata.count(this) &&
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001240 "Shouldn't have called this");
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001241 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001242 assert(!Info.empty() && "Shouldn't have called this");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001243 Info.getAll(Result);
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001244}
1245
Dan Gohman48a995f2010-07-20 22:25:04 +00001246void Instruction::clearMetadataHashEntries() {
1247 assert(hasMetadataHashEntry() && "Caller should check");
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001248 getContext().pImpl->InstructionMetadata.erase(this);
Dan Gohman48a995f2010-07-20 22:25:04 +00001249 setHasMetadataHashEntry(false);
Chris Lattner68017802009-12-29 07:44:16 +00001250}
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001251
1252MDNode *Function::getMetadata(unsigned KindID) const {
1253 if (!hasMetadata())
1254 return nullptr;
1255 return getContext().pImpl->FunctionMetadata[this].lookup(KindID);
1256}
1257
1258MDNode *Function::getMetadata(StringRef Kind) const {
1259 if (!hasMetadata())
1260 return nullptr;
1261 return getMetadata(getContext().getMDKindID(Kind));
1262}
1263
1264void Function::setMetadata(unsigned KindID, MDNode *MD) {
1265 if (MD) {
1266 if (!hasMetadata())
1267 setHasMetadataHashEntry(true);
1268
1269 getContext().pImpl->FunctionMetadata[this].set(KindID, *MD);
1270 return;
1271 }
1272
1273 // Nothing to unset.
1274 if (!hasMetadata())
1275 return;
1276
1277 auto &Store = getContext().pImpl->FunctionMetadata[this];
1278 Store.erase(KindID);
1279 if (Store.empty())
1280 clearMetadata();
1281}
1282
1283void Function::setMetadata(StringRef Kind, MDNode *MD) {
1284 if (!MD && !hasMetadata())
1285 return;
1286 setMetadata(getContext().getMDKindID(Kind), MD);
1287}
1288
1289void Function::getAllMetadata(
1290 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
1291 MDs.clear();
1292
1293 if (!hasMetadata())
1294 return;
1295
1296 getContext().pImpl->FunctionMetadata[this].getAll(MDs);
1297}
1298
1299void Function::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
1300 if (!hasMetadata())
1301 return;
1302 if (KnownIDs.empty()) {
1303 clearMetadata();
1304 return;
1305 }
1306
1307 SmallSet<unsigned, 5> KnownSet;
1308 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
1309
1310 auto &Store = getContext().pImpl->FunctionMetadata[this];
1311 assert(!Store.empty());
1312
1313 Store.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1314 return !KnownSet.count(I.first);
1315 });
1316
1317 if (Store.empty())
1318 clearMetadata();
1319}
1320
1321void Function::clearMetadata() {
1322 if (!hasMetadata())
1323 return;
1324 getContext().pImpl->FunctionMetadata.erase(this);
1325 setHasMetadataHashEntry(false);
1326}
Duncan P. N. Exon Smithb56b5af2015-08-28 21:55:35 +00001327
1328void Function::setSubprogram(DISubprogram *SP) {
1329 setMetadata(LLVMContext::MD_dbg, SP);
1330}
1331
1332DISubprogram *Function::getSubprogram() const {
1333 return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));
1334}