blob: 0ad3c5c04bae97a886c8167341a0273aa5b85dd9 [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");
259 assert(!V->NameAndIsUsedByMD.getInt() &&
260 "Expected this to be the only metadata use");
261 V->NameAndIsUsedByMD.setInt(true);
262 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()) {
305 assert(!From->NameAndIsUsedByMD.getInt() &&
306 "Expected From not to be used by metadata");
307 return;
308 }
309
310 // Remove old entry from the map.
311 assert(From->NameAndIsUsedByMD.getInt() &&
312 "Expected From to be used by metadata");
313 From->NameAndIsUsedByMD.setInt(false);
314 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).
349 assert(!To->NameAndIsUsedByMD.getInt() &&
350 "Expected this to be the only metadata use");
351 To->NameAndIsUsedByMD.setInt(true);
352 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
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000384void *MDNode::operator new(size_t Size, unsigned NumOps) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000385 void *Ptr = ::operator new(Size + NumOps * sizeof(MDOperand));
Duncan P. N. Exon Smith22600ff2014-12-09 23:56:39 +0000386 MDOperand *O = static_cast<MDOperand *>(Ptr);
387 for (MDOperand *E = O + NumOps; O != E; ++O)
388 (void)new (O) MDOperand;
389 return O;
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000390}
391
392void MDNode::operator delete(void *Mem) {
393 MDNode *N = static_cast<MDNode *>(Mem);
Duncan P. N. Exon Smith22600ff2014-12-09 23:56:39 +0000394 MDOperand *O = static_cast<MDOperand *>(Mem);
395 for (MDOperand *E = O - N->NumOperands; O != E; --O)
396 (O - 1)->~MDOperand();
397 ::operator delete(O);
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000398}
399
Duncan P. N. Exon Smithf1340452015-01-19 18:36:18 +0000400MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
Duncan P. N. Exon Smithfed199a2015-01-20 00:01:43 +0000401 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
402 : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
403 NumUnresolved(0), Context(Context) {
404 unsigned Op = 0;
405 for (Metadata *MD : Ops1)
406 setOperand(Op++, MD);
407 for (Metadata *MD : Ops2)
408 setOperand(Op++, MD);
Duncan P. N. Exon Smith2711ca72015-01-19 19:02:06 +0000409
Duncan P. N. Exon Smitha1ae4f62015-01-19 23:15:21 +0000410 if (isDistinct())
Duncan P. N. Exon Smith5e5b8502015-01-07 22:24:46 +0000411 return;
412
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000413 if (isUniqued())
414 // Check whether any operands are unresolved, requiring re-uniquing. If
415 // not, don't support RAUW.
416 if (!countUnresolvedOperands())
Duncan P. N. Exon Smitha1ae4f62015-01-19 23:15:21 +0000417 return;
418
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000419 this->Context.makeReplaceable(make_unique<ReplaceableMetadataImpl>(Context));
Devang Patela4f43fb2009-07-28 21:49:47 +0000420}
421
Duncan P. N. Exon Smith03e05832015-01-20 02:56:57 +0000422TempMDNode MDNode::clone() const {
423 switch (getMetadataID()) {
424 default:
425 llvm_unreachable("Invalid MDNode subclass");
426#define HANDLE_MDNODE_LEAF(CLASS) \
427 case CLASS##Kind: \
428 return cast<CLASS>(this)->cloneImpl();
429#include "llvm/IR/Metadata.def"
430 }
431}
432
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000433static bool isOperandUnresolved(Metadata *Op) {
434 if (auto *N = dyn_cast_or_null<MDNode>(Op))
435 return !N->isResolved();
436 return false;
437}
438
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000439unsigned MDNode::countUnresolvedOperands() {
440 assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000441 NumUnresolved = std::count_if(op_begin(), op_end(), isOperandUnresolved);
Duncan P. N. Exon Smithc5a0e2e2015-01-19 22:18:29 +0000442 return NumUnresolved;
443}
444
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000445void MDNode::makeUniqued() {
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000446 assert(isTemporary() && "Expected this to be temporary");
447 assert(!isResolved() && "Expected this to be unresolved");
448
449 // Make this 'uniqued'.
450 Storage = Uniqued;
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000451 if (!countUnresolvedOperands())
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000452 resolve();
453
454 assert(isUniqued() && "Expected this to be uniqued");
455}
456
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000457void MDNode::makeDistinct() {
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000458 assert(isTemporary() && "Expected this to be temporary");
459 assert(!isResolved() && "Expected this to be unresolved");
460
461 // Pretend to be uniqued, resolve the node, and then store in distinct table.
462 Storage = Uniqued;
463 resolve();
464 storeDistinctInContext();
465
466 assert(isDistinct() && "Expected this to be distinct");
467 assert(isResolved() && "Expected this to be resolved");
468}
469
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000470void MDNode::resolve() {
Duncan P. N. Exon Smithb8f79602015-01-19 19:26:24 +0000471 assert(isUniqued() && "Expected this to be uniqued");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000472 assert(!isResolved() && "Expected this to be unresolved");
473
474 // Move the map, so that this immediately looks resolved.
Duncan P. N. Exon Smith2711ca72015-01-19 19:02:06 +0000475 auto Uses = Context.takeReplaceableUses();
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000476 NumUnresolved = 0;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000477 assert(isResolved() && "Expected this to be resolved");
478
479 // Drop RAUW support.
480 Uses->resolveAllUses();
481}
482
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000483void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000484 assert(NumUnresolved != 0 && "Expected unresolved operands");
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000485
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000486 // Check if an operand was resolved.
Duncan P. N. Exon Smith845755c42015-01-13 00:46:34 +0000487 if (!isOperandUnresolved(Old)) {
488 if (isOperandUnresolved(New))
489 // An operand was un-resolved!
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000490 ++NumUnresolved;
Duncan P. N. Exon Smith845755c42015-01-13 00:46:34 +0000491 } else if (!isOperandUnresolved(New))
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000492 decrementUnresolvedOperandCount();
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000493}
494
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000495void MDNode::decrementUnresolvedOperandCount() {
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000496 if (!--NumUnresolved)
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000497 // Last unresolved operand has just been resolved.
Duncan P. N. Exon Smith34c3d102015-01-12 19:43:15 +0000498 resolve();
499}
500
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000501void MDNode::resolveCycles() {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000502 if (isResolved())
503 return;
504
505 // Resolve this node immediately.
506 resolve();
507
508 // Resolve all operands.
509 for (const auto &Op : operands()) {
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000510 auto *N = dyn_cast_or_null<MDNode>(Op);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000511 if (!N)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000512 continue;
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000513
514 assert(!N->isTemporary() &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000515 "Expected all forward declarations to be resolved");
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000516 if (!N->isResolved())
517 N->resolveCycles();
Chris Lattner8cb6c342009-12-31 01:05:46 +0000518 }
Duncan P. N. Exon Smith50846f82014-11-18 00:37:17 +0000519}
520
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000521static bool hasSelfReference(MDNode *N) {
522 for (Metadata *MD : N->operands())
523 if (MD == N)
524 return true;
525 return false;
526}
527
528MDNode *MDNode::replaceWithPermanentImpl() {
529 if (hasSelfReference(this))
530 return replaceWithDistinctImpl();
531 return replaceWithUniquedImpl();
532}
533
Duncan P. N. Exon Smith86475292015-01-19 23:17:09 +0000534MDNode *MDNode::replaceWithUniquedImpl() {
535 // Try to uniquify in place.
536 MDNode *UniquedNode = uniquify();
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000537
Duncan P. N. Exon Smith86475292015-01-19 23:17:09 +0000538 if (UniquedNode == this) {
539 makeUniqued();
540 return this;
541 }
542
543 // Collision, so RAUW instead.
544 replaceAllUsesWith(UniquedNode);
545 deleteAsSubclass();
546 return UniquedNode;
547}
548
549MDNode *MDNode::replaceWithDistinctImpl() {
550 makeDistinct();
551 return this;
552}
553
Duncan P. N. Exon Smith118632d2015-01-12 20:09:34 +0000554void MDTuple::recalculateHash() {
Duncan P. N. Exon Smith93e983e2015-01-19 22:53:18 +0000555 setHash(MDTupleInfo::KeyTy::calculateHash(this));
Duncan P. N. Exon Smith967629e2015-01-12 19:16:34 +0000556}
557
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000558void MDNode::dropAllReferences() {
559 for (unsigned I = 0, E = NumOperands; I != E; ++I)
560 setOperand(I, nullptr);
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000561 if (!isResolved()) {
562 Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
563 (void)Context.takeReplaceableUses();
564 }
Chris Lattner8cb6c342009-12-31 01:05:46 +0000565}
566
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000567void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000568 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
569 assert(Op < getNumOperands() && "Expected valid operand");
570
Duncan P. N. Exon Smith3d580562015-01-19 19:28:28 +0000571 if (!isUniqued()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000572 // This node is not uniqued. Just set the operand and be done with it.
573 setOperand(Op, New);
574 return;
Duncan Sandsc2928c62010-05-04 12:43:36 +0000575 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000576
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000577 // This node is uniqued.
578 eraseFromStore();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000579
580 Metadata *Old = getOperand(Op);
581 setOperand(Op, New);
582
Duncan P. N. Exon Smithbcd960a2015-01-05 23:31:54 +0000583 // Drop uniquing for self-reference cycles.
584 if (New == this) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000585 if (!isResolved())
586 resolve();
Duncan P. N. Exon Smithf08b8b42015-01-19 19:25:33 +0000587 storeDistinctInContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000588 return;
589 }
590
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000591 // Re-unique the node.
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000592 auto *Uniqued = uniquify();
593 if (Uniqued == this) {
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000594 if (!isResolved())
595 resolveAfterOperandChange(Old, New);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000596 return;
597 }
598
599 // Collision.
600 if (!isResolved()) {
601 // Still unresolved, so RAUW.
Duncan P. N. Exon Smithd9e6eb72015-01-12 19:36:35 +0000602 //
603 // First, clear out all operands to prevent any recursion (similar to
604 // dropAllReferences(), but we still need the use-list).
605 for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
606 setOperand(O, nullptr);
Duncan P. N. Exon Smith2711ca72015-01-19 19:02:06 +0000607 Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000608 deleteAsSubclass();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000609 return;
610 }
611
Duncan P. N. Exon Smithd9e6eb72015-01-12 19:36:35 +0000612 // Store in non-uniqued form if RAUW isn't possible.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000613 storeDistinctInContext();
Victor Hernandeze5f2af72010-01-20 04:45:57 +0000614}
615
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000616void MDNode::deleteAsSubclass() {
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000617 switch (getMetadataID()) {
618 default:
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000619 llvm_unreachable("Invalid subclass of MDNode");
620#define HANDLE_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000621 case CLASS##Kind: \
622 delete cast<CLASS>(this); \
623 break;
624#include "llvm/IR/Metadata.def"
625 }
626}
627
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000628template <class T, class InfoT>
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000629static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
630 if (T *U = getUniqued(Store, N))
631 return U;
632
633 Store.insert(N);
634 return N;
635}
636
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000637template <class NodeTy> struct MDNode::HasCachedHash {
638 typedef char Yes[1];
639 typedef char No[2];
640 template <class U, U Val> struct SFINAE {};
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000641
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000642 template <class U>
643 static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
644 template <class U> static No &check(...);
645
646 static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
647};
648
649MDNode *MDNode::uniquify() {
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000650 assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
651
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000652 // Try to insert into uniquing store.
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000653 switch (getMetadataID()) {
654 default:
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000655 llvm_unreachable("Invalid subclass of MDNode");
656#define HANDLE_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000657 case CLASS##Kind: { \
658 CLASS *SubclassThis = cast<CLASS>(this); \
659 std::integral_constant<bool, HasCachedHash<CLASS>::value> \
660 ShouldRecalculateHash; \
661 dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
662 return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
663 }
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000664#include "llvm/IR/Metadata.def"
665 }
666}
667
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000668void MDNode::eraseFromStore() {
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000669 switch (getMetadataID()) {
670 default:
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000671 llvm_unreachable("Invalid subclass of MDNode");
672#define HANDLE_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000673 case CLASS##Kind: \
Duncan P. N. Exon Smith6cf10d22015-01-19 22:47:08 +0000674 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000675 break;
676#include "llvm/IR/Metadata.def"
677 }
678}
679
Duncan P. N. Exon Smithac3128d2015-01-12 20:13:56 +0000680MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000681 StorageType Storage, bool ShouldCreate) {
682 unsigned Hash = 0;
683 if (Storage == Uniqued) {
684 MDTupleInfo::KeyTy Key(MDs);
Duncan P. N. Exon Smithb57f9e92015-01-19 20:16:50 +0000685 if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
686 return N;
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000687 if (!ShouldCreate)
688 return nullptr;
Duncan P. N. Exon Smith93e983e2015-01-19 22:53:18 +0000689 Hash = Key.getHash();
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000690 } else {
691 assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
692 }
Duncan Sands26a80f32012-03-31 08:20:11 +0000693
Duncan P. N. Exon Smith5b8c4402015-01-19 20:18:13 +0000694 return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
695 Storage, Context.pImpl->MDTuples);
Duncan P. N. Exon Smith5e5b8502015-01-07 22:24:46 +0000696}
697
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000698void MDNode::deleteTemporary(MDNode *N) {
699 assert(N->isTemporary() && "Expected temporary node");
Duncan P. N. Exon Smith8d536972015-01-22 21:36:45 +0000700 N->replaceAllUsesWith(nullptr);
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000701 N->deleteAsSubclass();
Dan Gohman16a5d982010-08-20 22:02:26 +0000702}
703
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000704void MDNode::storeDistinctInContext() {
Duncan P. N. Exon Smithf08b8b42015-01-19 19:25:33 +0000705 assert(isResolved() && "Expected resolved nodes");
Duncan P. N. Exon Smithf1340452015-01-19 18:36:18 +0000706 Storage = Distinct;
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000707
708 // Reset the hash.
709 switch (getMetadataID()) {
710 default:
711 llvm_unreachable("Invalid subclass of MDNode");
712#define HANDLE_MDNODE_LEAF(CLASS) \
713 case CLASS##Kind: { \
714 std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
715 dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
716 break; \
717 }
718#include "llvm/IR/Metadata.def"
719 }
720
Duncan P. N. Exon Smithde03ff52015-01-13 20:44:56 +0000721 getContext().pImpl->DistinctMDNodes.insert(this);
Devang Patel82ab3f82010-02-18 20:53:16 +0000722}
Chris Lattnerf543eff2009-12-28 09:12:35 +0000723
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000724void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
725 if (getOperand(I) == New)
Devang Patelf7188322009-09-03 01:39:20 +0000726 return;
Devang Patelf7188322009-09-03 01:39:20 +0000727
Duncan P. N. Exon Smithde03a8b2015-01-19 18:45:35 +0000728 if (!isUniqued()) {
Duncan P. N. Exon Smithdaa335a2015-01-12 18:01:45 +0000729 setOperand(I, New);
Duncan P. N. Exon Smithf39c3b82014-11-17 23:28:21 +0000730 return;
731 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +0000732
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000733 handleChangedOperand(mutable_begin() + I, New);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000734}
Chris Lattnerc6d17e22009-12-28 09:24:53 +0000735
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000736void MDNode::setOperand(unsigned I, Metadata *New) {
737 assert(I < NumOperands);
Duncan P. N. Exon Smithefdf2852015-01-19 19:29:25 +0000738 mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
Devang Patelf7188322009-09-03 01:39:20 +0000739}
740
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000741/// \brief Get a node, or a self-reference that looks like it.
742///
743/// Special handling for finding self-references, for use by \a
744/// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
745/// when self-referencing nodes were still uniqued. If the first operand has
746/// the same operands as \c Ops, return the first operand instead.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000747static MDNode *getOrSelfReference(LLVMContext &Context,
748 ArrayRef<Metadata *> Ops) {
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000749 if (!Ops.empty())
750 if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
751 if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
752 for (unsigned I = 1, E = Ops.size(); I != E; ++I)
753 if (Ops[I] != N->getOperand(I))
754 return MDNode::get(Context, Ops);
755 return N;
756 }
757
758 return MDNode::get(Context, Ops);
759}
760
Hal Finkel94146652014-07-24 14:25:39 +0000761MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
762 if (!A)
763 return B;
764 if (!B)
765 return A;
766
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000767 SmallVector<Metadata *, 4> MDs;
768 MDs.reserve(A->getNumOperands() + B->getNumOperands());
769 MDs.append(A->op_begin(), A->op_end());
770 MDs.append(B->op_begin(), B->op_end());
Hal Finkel94146652014-07-24 14:25:39 +0000771
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000772 // FIXME: This preserves long-standing behaviour, but is it really the right
773 // behaviour? Or was that an unintended side-effect of node uniquing?
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000774 return getOrSelfReference(A->getContext(), MDs);
Hal Finkel94146652014-07-24 14:25:39 +0000775}
776
777MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
778 if (!A || !B)
779 return nullptr;
780
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000781 SmallVector<Metadata *, 4> MDs;
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000782 for (Metadata *MD : A->operands())
783 if (std::find(B->op_begin(), B->op_end(), MD) != B->op_end())
784 MDs.push_back(MD);
Hal Finkel94146652014-07-24 14:25:39 +0000785
Duncan P. N. Exon Smithac8ee282014-12-07 19:52:06 +0000786 // FIXME: This preserves long-standing behaviour, but is it really the right
787 // behaviour? Or was that an unintended side-effect of node uniquing?
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000788 return getOrSelfReference(A->getContext(), MDs);
Hal Finkel94146652014-07-24 14:25:39 +0000789}
790
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +0000791MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
792 if (!A || !B)
793 return nullptr;
794
795 SmallVector<Metadata *, 4> MDs(B->op_begin(), B->op_end());
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000796 for (Metadata *MD : A->operands())
797 if (std::find(B->op_begin(), B->op_end(), MD) == B->op_end())
798 MDs.push_back(MD);
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +0000799
800 // FIXME: This preserves long-standing behaviour, but is it really the right
801 // behaviour? Or was that an unintended side-effect of node uniquing?
802 return getOrSelfReference(A->getContext(), MDs);
803}
804
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000805MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
806 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000807 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000808
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000809 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
810 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000811 if (AVal.compare(BVal) == APFloat::cmpLessThan)
812 return A;
813 return B;
814}
815
816static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
817 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
818}
819
820static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
821 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
822}
823
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000824static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
825 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000826 ConstantRange NewRange(Low->getValue(), High->getValue());
827 unsigned Size = EndPoints.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000828 APInt LB = EndPoints[Size - 2]->getValue();
829 APInt LE = EndPoints[Size - 1]->getValue();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000830 ConstantRange LastRange(LB, LE);
831 if (canBeMerged(NewRange, LastRange)) {
832 ConstantRange Union = LastRange.unionWith(NewRange);
833 Type *Ty = High->getType();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000834 EndPoints[Size - 2] =
835 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
836 EndPoints[Size - 1] =
837 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000838 return true;
839 }
840 return false;
841}
842
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000843static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
844 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000845 if (!EndPoints.empty())
846 if (tryMergeRange(EndPoints, Low, High))
847 return;
848
849 EndPoints.push_back(Low);
850 EndPoints.push_back(High);
851}
852
853MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
854 // Given two ranges, we want to compute the union of the ranges. This
855 // is slightly complitade by having to combine the intervals and merge
856 // the ones that overlap.
857
858 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000859 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000860
861 if (A == B)
862 return A;
863
864 // First, walk both lists in older of the lower boundary of each interval.
865 // 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 +0000866 SmallVector<ConstantInt *, 4> EndPoints;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000867 int AI = 0;
868 int BI = 0;
869 int AN = A->getNumOperands() / 2;
870 int BN = B->getNumOperands() / 2;
871 while (AI < AN && BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000872 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
873 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000874
875 if (ALow->getValue().slt(BLow->getValue())) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000876 addRange(EndPoints, ALow,
877 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000878 ++AI;
879 } else {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000880 addRange(EndPoints, BLow,
881 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000882 ++BI;
883 }
884 }
885 while (AI < AN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000886 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
887 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000888 ++AI;
889 }
890 while (BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000891 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
892 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000893 ++BI;
894 }
895
896 // If we have more than 2 ranges (4 endpoints) we have to try to merge
897 // the last and first ones.
898 unsigned Size = EndPoints.size();
899 if (Size > 4) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000900 ConstantInt *FB = EndPoints[0];
901 ConstantInt *FE = EndPoints[1];
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000902 if (tryMergeRange(EndPoints, FB, FE)) {
903 for (unsigned i = 0; i < Size - 2; ++i) {
904 EndPoints[i] = EndPoints[i + 2];
905 }
906 EndPoints.resize(Size - 2);
907 }
908 }
909
910 // If in the end we have a single range, it is possible that it is now the
911 // full range. Just drop the metadata in that case.
912 if (EndPoints.size() == 2) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000913 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000914 if (Range.isFullSet())
Craig Topperc6207612014-04-09 06:08:46 +0000915 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000916 }
917
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000918 SmallVector<Metadata *, 4> MDs;
919 MDs.reserve(EndPoints.size());
920 for (auto *I : EndPoints)
921 MDs.push_back(ConstantAsMetadata::get(I));
922 return MDNode::get(A->getContext(), MDs);
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000923}
924
Devang Patel05a26fb2009-07-29 00:33:07 +0000925//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000926// NamedMDNode implementation.
Devang Patel05a26fb2009-07-29 00:33:07 +0000927//
Devang Patel943ddf62010-01-12 18:34:06 +0000928
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000929static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
930 return *(SmallVector<TrackingMDRef, 4> *)Operands;
Chris Lattner1bc810b2009-12-28 08:07:14 +0000931}
932
Dan Gohman2637cc12010-07-21 23:38:33 +0000933NamedMDNode::NamedMDNode(const Twine &N)
Duncan P. N. Exon Smithc5754a62014-11-05 18:16:03 +0000934 : Name(N.str()), Parent(nullptr),
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000935 Operands(new SmallVector<TrackingMDRef, 4>()) {}
Devang Patel5c310be2009-08-11 18:01:24 +0000936
Chris Lattner1bc810b2009-12-28 08:07:14 +0000937NamedMDNode::~NamedMDNode() {
938 dropAllReferences();
939 delete &getNMDOps(Operands);
940}
941
Chris Lattner9b493022009-12-31 01:22:29 +0000942unsigned NamedMDNode::getNumOperands() const {
Chris Lattner1bc810b2009-12-28 08:07:14 +0000943 return (unsigned)getNMDOps(Operands).size();
944}
945
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000946MDNode *NamedMDNode::getOperand(unsigned i) const {
Chris Lattner9b493022009-12-31 01:22:29 +0000947 assert(i < getNumOperands() && "Invalid Operand number!");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000948 auto *N = getNMDOps(Operands)[i].get();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000949 return cast_or_null<MDNode>(N);
Chris Lattner1bc810b2009-12-28 08:07:14 +0000950}
951
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000952void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
Chris Lattner1bc810b2009-12-28 08:07:14 +0000953
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +0000954void NamedMDNode::setOperand(unsigned I, MDNode *New) {
955 assert(I < getNumOperands() && "Invalid operand number");
956 getNMDOps(Operands)[I].reset(New);
957}
958
Devang Patel79238d72009-08-03 06:19:01 +0000959void NamedMDNode::eraseFromParent() {
Dan Gohman2637cc12010-07-21 23:38:33 +0000960 getParent()->eraseNamedMetadata(this);
Devang Patel79238d72009-08-03 06:19:01 +0000961}
962
Devang Patel79238d72009-08-03 06:19:01 +0000963void NamedMDNode::dropAllReferences() {
Chris Lattner1bc810b2009-12-28 08:07:14 +0000964 getNMDOps(Operands).clear();
Devang Patel79238d72009-08-03 06:19:01 +0000965}
966
Devang Patelfcfee0f2010-01-07 19:39:36 +0000967StringRef NamedMDNode::getName() const {
968 return StringRef(Name);
969}
Devang Pateld5497a4b2009-09-16 18:09:00 +0000970
971//===----------------------------------------------------------------------===//
Chris Lattner2f2aa2b2009-12-28 23:41:32 +0000972// Instruction Metadata method implementations.
973//
974
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000975void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
976 if (!Node && !hasMetadata())
977 return;
978 setMetadata(getContext().getMDKindID(Kind), Node);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +0000979}
980
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000981MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
Chris Lattnera0566972009-12-29 09:01:33 +0000982 return getMetadataImpl(getContext().getMDKindID(Kind));
Chris Lattner2f2aa2b2009-12-28 23:41:32 +0000983}
984
Rafael Espindolaab73c492014-01-28 16:56:46 +0000985void Instruction::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
986 SmallSet<unsigned, 5> KnownSet;
987 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
988
989 // Drop debug if needed
990 if (KnownSet.erase(LLVMContext::MD_dbg))
991 DbgLoc = DebugLoc();
992
993 if (!hasMetadataHashEntry())
994 return; // Nothing to remove!
995
996 DenseMap<const Instruction *, LLVMContextImpl::MDMapTy> &MetadataStore =
997 getContext().pImpl->MetadataStore;
998
999 if (KnownSet.empty()) {
1000 // Just drop our entry at the store.
1001 MetadataStore.erase(this);
1002 setHasMetadataHashEntry(false);
1003 return;
1004 }
1005
1006 LLVMContextImpl::MDMapTy &Info = MetadataStore[this];
1007 unsigned I;
1008 unsigned E;
1009 // Walk the array and drop any metadata we don't know.
1010 for (I = 0, E = Info.size(); I != E;) {
1011 if (KnownSet.count(Info[I].first)) {
1012 ++I;
1013 continue;
1014 }
1015
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001016 Info[I] = std::move(Info.back());
Rafael Espindolaab73c492014-01-28 16:56:46 +00001017 Info.pop_back();
1018 --E;
1019 }
1020 assert(E == Info.size());
1021
1022 if (E == 0) {
1023 // Drop our entry at the store.
1024 MetadataStore.erase(this);
1025 setHasMetadataHashEntry(false);
1026 }
1027}
1028
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001029/// setMetadata - Set the metadata of of the specified kind to the specified
1030/// node. This updates/replaces metadata if already present, or removes it if
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001031/// Node is null.
1032void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1033 if (!Node && !hasMetadata())
1034 return;
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001035
Chris Lattnerc263b422010-03-30 23:03:27 +00001036 // Handle 'dbg' as a special case since it is not stored in the hash table.
1037 if (KindID == LLVMContext::MD_dbg) {
Chris Lattner593916d2010-04-02 20:21:22 +00001038 DbgLoc = DebugLoc::getFromDILocation(Node);
Chris Lattnerc263b422010-03-30 23:03:27 +00001039 return;
1040 }
1041
Chris Lattnera0566972009-12-29 09:01:33 +00001042 // Handle the case when we're adding/updating metadata on an instruction.
1043 if (Node) {
1044 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
Chris Lattnerc263b422010-03-30 23:03:27 +00001045 assert(!Info.empty() == hasMetadataHashEntry() &&
1046 "HasMetadata bit is wonked");
Chris Lattnera0566972009-12-29 09:01:33 +00001047 if (Info.empty()) {
Chris Lattnerc263b422010-03-30 23:03:27 +00001048 setHasMetadataHashEntry(true);
Chris Lattnera0566972009-12-29 09:01:33 +00001049 } else {
1050 // Handle replacement of an existing value.
Benjamin Kramer3ad5c962014-03-10 15:03:06 +00001051 for (auto &P : Info)
1052 if (P.first == KindID) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001053 P.second.reset(Node);
Chris Lattnera0566972009-12-29 09:01:33 +00001054 return;
1055 }
1056 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001057
Chris Lattnera0566972009-12-29 09:01:33 +00001058 // No replacement, just add it to the list.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001059 Info.emplace_back(std::piecewise_construct, std::make_tuple(KindID),
1060 std::make_tuple(Node));
Chris Lattnera0566972009-12-29 09:01:33 +00001061 return;
1062 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001063
Chris Lattnera0566972009-12-29 09:01:33 +00001064 // Otherwise, we're removing metadata from an instruction.
Nick Lewycky4c131382011-12-27 01:17:40 +00001065 assert((hasMetadataHashEntry() ==
Yaron Keren6d3194f2014-06-20 10:26:56 +00001066 (getContext().pImpl->MetadataStore.count(this) > 0)) &&
Chris Lattnera0566972009-12-29 09:01:33 +00001067 "HasMetadata bit out of date!");
Nick Lewycky4c131382011-12-27 01:17:40 +00001068 if (!hasMetadataHashEntry())
1069 return; // Nothing to remove!
Chris Lattnera0566972009-12-29 09:01:33 +00001070 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001071
Chris Lattnera0566972009-12-29 09:01:33 +00001072 // Common case is removing the only entry.
1073 if (Info.size() == 1 && Info[0].first == KindID) {
1074 getContext().pImpl->MetadataStore.erase(this);
Chris Lattnerc263b422010-03-30 23:03:27 +00001075 setHasMetadataHashEntry(false);
Chris Lattnera0566972009-12-29 09:01:33 +00001076 return;
1077 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001078
Chris Lattnerc263b422010-03-30 23:03:27 +00001079 // Handle removal of an existing value.
Chris Lattnera0566972009-12-29 09:01:33 +00001080 for (unsigned i = 0, e = Info.size(); i != e; ++i)
1081 if (Info[i].first == KindID) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001082 Info[i] = std::move(Info.back());
Chris Lattnera0566972009-12-29 09:01:33 +00001083 Info.pop_back();
1084 assert(!Info.empty() && "Removing last entry should be handled above");
1085 return;
1086 }
1087 // Otherwise, removing an entry that doesn't exist on the instruction.
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001088}
1089
Hal Finkelcc39b672014-07-24 12:16:19 +00001090void Instruction::setAAMetadata(const AAMDNodes &N) {
1091 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
Hal Finkel94146652014-07-24 14:25:39 +00001092 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1093 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
Hal Finkelcc39b672014-07-24 12:16:19 +00001094}
1095
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001096MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
Chris Lattnerc263b422010-03-30 23:03:27 +00001097 // Handle 'dbg' as a special case since it is not stored in the hash table.
1098 if (KindID == LLVMContext::MD_dbg)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001099 return DbgLoc.getAsMDNode();
1100
Craig Topperc6207612014-04-09 06:08:46 +00001101 if (!hasMetadataHashEntry()) return nullptr;
Chris Lattnerc263b422010-03-30 23:03:27 +00001102
Chris Lattnera0566972009-12-29 09:01:33 +00001103 LLVMContextImpl::MDMapTy &Info = getContext().pImpl->MetadataStore[this];
Chris Lattnerc263b422010-03-30 23:03:27 +00001104 assert(!Info.empty() && "bit out of sync with hash table");
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001105
Benjamin Kramer3ad5c962014-03-10 15:03:06 +00001106 for (const auto &I : Info)
1107 if (I.first == KindID)
1108 return I.second;
Craig Topperc6207612014-04-09 06:08:46 +00001109 return nullptr;
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001110}
1111
Duncan P. N. Exon Smith4abd1a02014-11-01 00:26:42 +00001112void Instruction::getAllMetadataImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001113 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc263b422010-03-30 23:03:27 +00001114 Result.clear();
1115
1116 // Handle 'dbg' as a special case since it is not stored in the hash table.
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001117 if (!DbgLoc.isUnknown()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001118 Result.push_back(
1119 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
Chris Lattnerc263b422010-03-30 23:03:27 +00001120 if (!hasMetadataHashEntry()) return;
1121 }
1122
1123 assert(hasMetadataHashEntry() &&
1124 getContext().pImpl->MetadataStore.count(this) &&
Chris Lattnera0566972009-12-29 09:01:33 +00001125 "Shouldn't have called this");
1126 const LLVMContextImpl::MDMapTy &Info =
1127 getContext().pImpl->MetadataStore.find(this)->second;
1128 assert(!Info.empty() && "Shouldn't have called this");
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001129
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001130 Result.reserve(Result.size() + Info.size());
1131 for (auto &I : Info)
1132 Result.push_back(std::make_pair(I.first, cast<MDNode>(I.second.get())));
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001133
Chris Lattnera0566972009-12-29 09:01:33 +00001134 // Sort the resulting array so it is stable.
1135 if (Result.size() > 1)
1136 array_pod_sort(Result.begin(), Result.end());
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001137}
1138
Duncan P. N. Exon Smith3d5a02f2014-11-03 18:13:57 +00001139void Instruction::getAllMetadataOtherThanDebugLocImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001140 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001141 Result.clear();
1142 assert(hasMetadataHashEntry() &&
1143 getContext().pImpl->MetadataStore.count(this) &&
1144 "Shouldn't have called this");
1145 const LLVMContextImpl::MDMapTy &Info =
Bill Wendlingdd91e732012-04-03 10:50:09 +00001146 getContext().pImpl->MetadataStore.find(this)->second;
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001147 assert(!Info.empty() && "Shouldn't have called this");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001148 Result.reserve(Result.size() + Info.size());
1149 for (auto &I : Info)
1150 Result.push_back(std::make_pair(I.first, cast<MDNode>(I.second.get())));
Bill Wendlingdd91e732012-04-03 10:50:09 +00001151
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001152 // Sort the resulting array so it is stable.
1153 if (Result.size() > 1)
1154 array_pod_sort(Result.begin(), Result.end());
1155}
1156
Dan Gohman48a995f2010-07-20 22:25:04 +00001157/// clearMetadataHashEntries - Clear all hashtable-based metadata from
1158/// this instruction.
1159void Instruction::clearMetadataHashEntries() {
1160 assert(hasMetadataHashEntry() && "Caller should check");
1161 getContext().pImpl->MetadataStore.erase(this);
1162 setHasMetadataHashEntry(false);
Chris Lattner68017802009-12-29 07:44:16 +00001163}