blob: 7228de3d23702d140e2254f86a24f25937fd1caf [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
Chris Lattner1300f452009-12-28 08:24:16 +000014#include "LLVMContextImpl.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000015#include "MetadataImpl.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "SymbolTableListTraitsImpl.h"
Eugene Zelenkodeaf6952017-02-17 00:00:09 +000017#include "llvm/ADT/APFloat.h"
18#include "llvm/ADT/APInt.h"
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/DenseSet.h"
21#include "llvm/ADT/None.h"
David Majnemerfa0f1e62016-08-16 18:48:34 +000022#include "llvm/ADT/SetVector.h"
Eugene Zelenkodeaf6952017-02-17 00:00:09 +000023#include "llvm/ADT/SmallPtrSet.h"
Rafael Espindolaab73c492014-01-28 16:56:46 +000024#include "llvm/ADT/SmallSet.h"
Eugene Zelenkodeaf6952017-02-17 00:00:09 +000025#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/ADT/StringMap.h"
Eugene Zelenkodeaf6952017-02-17 00:00:09 +000028#include "llvm/ADT/StringRef.h"
29#include "llvm/IR/Argument.h"
30#include "llvm/IR/BasicBlock.h"
31#include "llvm/IR/Constant.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000032#include "llvm/IR/ConstantRange.h"
Eugene Zelenkodeaf6952017-02-17 00:00:09 +000033#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000034#include "llvm/IR/DebugInfoMetadata.h"
Eugene Zelenkodeaf6952017-02-17 00:00:09 +000035#include "llvm/IR/DebugLoc.h"
36#include "llvm/IR/Function.h"
37#include "llvm/IR/GlobalObject.h"
38#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Instruction.h"
40#include "llvm/IR/LLVMContext.h"
Eugene Zelenkodeaf6952017-02-17 00:00:09 +000041#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/Module.h"
Eugene Zelenkodeaf6952017-02-17 00:00:09 +000043#include "llvm/IR/TrackingMDRef.h"
44#include "llvm/IR/Type.h"
45#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000046#include "llvm/IR/ValueHandle.h"
Eugene Zelenkodeaf6952017-02-17 00:00:09 +000047#include "llvm/Support/Casting.h"
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/Support/MathExtras.h"
50#include <algorithm>
51#include <cassert>
52#include <cstddef>
53#include <cstdint>
54#include <iterator>
55#include <tuple>
56#include <utility>
57#include <vector>
Duncan P. N. Exon Smith46d91ad2014-11-14 18:42:06 +000058
Devang Patela4f43fb2009-07-28 21:49:47 +000059using namespace llvm;
60
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +000061MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
62 : Value(Ty, MetadataAsValueVal), MD(MD) {
63 track();
64}
65
66MetadataAsValue::~MetadataAsValue() {
67 getType()->getContext().pImpl->MetadataAsValues.erase(MD);
68 untrack();
69}
70
Sanjay Patel9da9c762016-03-12 20:44:58 +000071/// Canonicalize metadata arguments to intrinsics.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +000072///
73/// To support bitcode upgrades (and assembly semantic sugar) for \a
74/// MetadataAsValue, we need to canonicalize certain metadata.
75///
76/// - nullptr is replaced by an empty MDNode.
77/// - An MDNode with a single null operand is replaced by an empty MDNode.
78/// - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
79///
80/// This maintains readability of bitcode from when metadata was a type of
81/// value, and these bridges were unnecessary.
82static Metadata *canonicalizeMetadataForValue(LLVMContext &Context,
83 Metadata *MD) {
84 if (!MD)
85 // !{}
86 return MDNode::get(Context, None);
87
88 // Return early if this isn't a single-operand MDNode.
89 auto *N = dyn_cast<MDNode>(MD);
90 if (!N || N->getNumOperands() != 1)
91 return MD;
92
93 if (!N->getOperand(0))
94 // !{}
95 return MDNode::get(Context, None);
96
97 if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
98 // Look through the MDNode.
99 return C;
100
101 return MD;
102}
103
104MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
105 MD = canonicalizeMetadataForValue(Context, MD);
106 auto *&Entry = Context.pImpl->MetadataAsValues[MD];
107 if (!Entry)
108 Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
109 return Entry;
110}
111
112MetadataAsValue *MetadataAsValue::getIfExists(LLVMContext &Context,
113 Metadata *MD) {
114 MD = canonicalizeMetadataForValue(Context, MD);
115 auto &Store = Context.pImpl->MetadataAsValues;
Benjamin Kramer4c1f0972015-02-08 21:56:09 +0000116 return Store.lookup(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000117}
118
119void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
120 LLVMContext &Context = getContext();
121 MD = canonicalizeMetadataForValue(Context, MD);
122 auto &Store = Context.pImpl->MetadataAsValues;
123
124 // Stop tracking the old metadata.
125 Store.erase(this->MD);
126 untrack();
127 this->MD = nullptr;
128
129 // Start tracking MD, or RAUW if necessary.
130 auto *&Entry = Store[MD];
131 if (Entry) {
132 replaceAllUsesWith(Entry);
133 delete this;
134 return;
135 }
136
137 this->MD = MD;
138 track();
139 Entry = this;
140}
141
142void MetadataAsValue::track() {
143 if (MD)
144 MetadataTracking::track(&MD, *MD, *this);
145}
146
147void MetadataAsValue::untrack() {
148 if (MD)
149 MetadataTracking::untrack(MD);
150}
151
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000152bool MetadataTracking::track(void *Ref, Metadata &MD, OwnerTy Owner) {
153 assert(Ref && "Expected live reference");
154 assert((Owner || *static_cast<Metadata **>(Ref) == &MD) &&
155 "Reference without owner must be direct");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000156 if (auto *R = ReplaceableMetadataImpl::getOrCreate(MD)) {
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000157 R->addRef(Ref, Owner);
158 return true;
159 }
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000160 if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD)) {
161 assert(!PH->Use && "Placeholders can only be used once");
162 assert(!Owner && "Unexpected callback to owner");
163 PH->Use = static_cast<Metadata **>(Ref);
164 return true;
165 }
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000166 return false;
167}
168
169void MetadataTracking::untrack(void *Ref, Metadata &MD) {
170 assert(Ref && "Expected live reference");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000171 if (auto *R = ReplaceableMetadataImpl::getIfExists(MD))
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000172 R->dropRef(Ref);
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000173 else if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD))
174 PH->Use = nullptr;
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000175}
176
177bool MetadataTracking::retrack(void *Ref, Metadata &MD, void *New) {
178 assert(Ref && "Expected live reference");
179 assert(New && "Expected live reference");
180 assert(Ref != New && "Expected change");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000181 if (auto *R = ReplaceableMetadataImpl::getIfExists(MD)) {
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000182 R->moveRef(Ref, New, MD);
183 return true;
184 }
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000185 assert(!isa<DistinctMDOperandPlaceholder>(MD) &&
186 "Unexpected move of an MDOperand");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000187 assert(!isReplaceable(MD) &&
188 "Expected un-replaceable metadata, since we didn't move a reference");
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000189 return false;
190}
191
192bool MetadataTracking::isReplaceable(const Metadata &MD) {
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000193 return ReplaceableMetadataImpl::isReplaceable(MD);
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000194}
195
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000196void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000197 bool WasInserted =
198 UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
199 .second;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000200 (void)WasInserted;
201 assert(WasInserted && "Expected to add a reference");
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000202
203 ++NextIndex;
204 assert(NextIndex != 0 && "Unexpected overflow");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000205}
206
207void ReplaceableMetadataImpl::dropRef(void *Ref) {
208 bool WasErased = UseMap.erase(Ref);
209 (void)WasErased;
210 assert(WasErased && "Expected to drop a reference");
211}
212
213void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
214 const Metadata &MD) {
215 auto I = UseMap.find(Ref);
216 assert(I != UseMap.end() && "Expected to move a reference");
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000217 auto OwnerAndIndex = I->second;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000218 UseMap.erase(I);
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000219 bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
220 (void)WasInserted;
221 assert(WasInserted && "Expected to add a reference");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000222
223 // Check that the references are direct if there's no owner.
224 (void)MD;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000225 assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000226 "Reference without owner must be direct");
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000227 assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000228 "Reference without owner must be direct");
229}
230
231void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000232 if (UseMap.empty())
233 return;
234
235 // Copy out uses since UseMap will get touched below.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000236 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
237 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
238 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
239 return L.second.second < R.second.second;
240 });
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000241 for (const auto &Pair : Uses) {
Duncan P. N. Exon Smith4a4f7852015-01-14 19:56:10 +0000242 // Check that this Ref hasn't disappeared after RAUW (when updating a
243 // previous Ref).
244 if (!UseMap.count(Pair.first))
245 continue;
246
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000247 OwnerTy Owner = Pair.second.first;
248 if (!Owner) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000249 // Update unowned tracking references directly.
250 Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
251 Ref = MD;
Duncan P. N. Exon Smith121eeff2014-12-12 19:24:33 +0000252 if (MD)
253 MetadataTracking::track(Ref);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000254 UseMap.erase(Pair.first);
255 continue;
256 }
257
258 // Check for MetadataAsValue.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000259 if (Owner.is<MetadataAsValue *>()) {
260 Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000261 continue;
262 }
263
264 // There's a Metadata owner -- dispatch.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000265 Metadata *OwnerMD = Owner.get<Metadata *>();
266 switch (OwnerMD->getMetadataID()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000267#define HANDLE_METADATA_LEAF(CLASS) \
268 case Metadata::CLASS##Kind: \
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000269 cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000270 continue;
271#include "llvm/IR/Metadata.def"
272 default:
273 llvm_unreachable("Invalid metadata subclass");
274 }
275 }
276 assert(UseMap.empty() && "Expected all uses to be replaced");
277}
278
279void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
280 if (UseMap.empty())
281 return;
282
283 if (!ResolveUsers) {
284 UseMap.clear();
285 return;
286 }
287
288 // Copy out uses since UseMap could get touched below.
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000289 typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
290 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
291 std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
292 return L.second.second < R.second.second;
293 });
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000294 UseMap.clear();
295 for (const auto &Pair : Uses) {
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000296 auto Owner = Pair.second.first;
297 if (!Owner)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000298 continue;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000299 if (Owner.is<MetadataAsValue *>())
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000300 continue;
301
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000302 // Resolve MDNodes that point at this.
303 auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000304 if (!OwnerMD)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000305 continue;
Duncan P. N. Exon Smith21909e32014-12-09 21:12:56 +0000306 if (OwnerMD->isResolved())
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000307 continue;
Duncan P. N. Exon Smith34c3d102015-01-12 19:43:15 +0000308 OwnerMD->decrementUnresolvedOperandCount();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000309 }
310}
311
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000312ReplaceableMetadataImpl *ReplaceableMetadataImpl::getOrCreate(Metadata &MD) {
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000313 if (auto *N = dyn_cast<MDNode>(&MD))
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000314 return N->isResolved() ? nullptr : N->Context.getOrCreateReplaceableUses();
315 return dyn_cast<ValueAsMetadata>(&MD);
316}
317
318ReplaceableMetadataImpl *ReplaceableMetadataImpl::getIfExists(Metadata &MD) {
319 if (auto *N = dyn_cast<MDNode>(&MD))
320 return N->isResolved() ? nullptr : N->Context.getReplaceableUses();
321 return dyn_cast<ValueAsMetadata>(&MD);
322}
323
324bool ReplaceableMetadataImpl::isReplaceable(const Metadata &MD) {
325 if (auto *N = dyn_cast<MDNode>(&MD))
326 return !N->isResolved();
Chandler Carrutha7dc0872015-12-29 02:14:50 +0000327 return dyn_cast<ValueAsMetadata>(&MD);
328}
329
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000330static Function *getLocalFunction(Value *V) {
331 assert(V && "Expected value");
332 if (auto *A = dyn_cast<Argument>(V))
333 return A->getParent();
334 if (BasicBlock *BB = cast<Instruction>(V)->getParent())
335 return BB->getParent();
336 return nullptr;
337}
338
339ValueAsMetadata *ValueAsMetadata::get(Value *V) {
340 assert(V && "Unexpected null Value");
341
342 auto &Context = V->getContext();
343 auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
344 if (!Entry) {
345 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
346 "Expected constant or function-local value");
Dehao Chene0e0ed12016-09-16 18:27:20 +0000347 assert(!V->IsUsedByMD && "Expected this to be the only metadata use");
Owen Anderson7349ab92015-06-01 22:24:01 +0000348 V->IsUsedByMD = true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000349 if (auto *C = dyn_cast<Constant>(V))
Duncan P. N. Exon Smith1c00c9f2015-01-05 20:41:25 +0000350 Entry = new ConstantAsMetadata(C);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000351 else
Duncan P. N. Exon Smith1c00c9f2015-01-05 20:41:25 +0000352 Entry = new LocalAsMetadata(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000353 }
354
355 return Entry;
356}
357
358ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
359 assert(V && "Unexpected null Value");
360 return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
361}
362
363void ValueAsMetadata::handleDeletion(Value *V) {
364 assert(V && "Expected valid value");
365
366 auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
367 auto I = Store.find(V);
368 if (I == Store.end())
369 return;
370
371 // Remove old entry from the map.
372 ValueAsMetadata *MD = I->second;
373 assert(MD && "Expected valid metadata");
374 assert(MD->getValue() == V && "Expected valid mapping");
375 Store.erase(I);
376
377 // Delete the metadata.
378 MD->replaceAllUsesWith(nullptr);
379 delete MD;
380}
381
382void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
383 assert(From && "Expected valid value");
384 assert(To && "Expected valid value");
385 assert(From != To && "Expected changed value");
386 assert(From->getType() == To->getType() && "Unexpected type change");
387
388 LLVMContext &Context = From->getType()->getContext();
389 auto &Store = Context.pImpl->ValuesAsMetadata;
390 auto I = Store.find(From);
391 if (I == Store.end()) {
Dehao Chene0e0ed12016-09-16 18:27:20 +0000392 assert(!From->IsUsedByMD && "Expected From not to be used by metadata");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000393 return;
394 }
395
396 // Remove old entry from the map.
Dehao Chene0e0ed12016-09-16 18:27:20 +0000397 assert(From->IsUsedByMD && "Expected From to be used by metadata");
Owen Anderson7349ab92015-06-01 22:24:01 +0000398 From->IsUsedByMD = false;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000399 ValueAsMetadata *MD = I->second;
400 assert(MD && "Expected valid metadata");
401 assert(MD->getValue() == From && "Expected valid mapping");
402 Store.erase(I);
403
404 if (isa<LocalAsMetadata>(MD)) {
405 if (auto *C = dyn_cast<Constant>(To)) {
406 // Local became a constant.
407 MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
408 delete MD;
409 return;
410 }
411 if (getLocalFunction(From) && getLocalFunction(To) &&
412 getLocalFunction(From) != getLocalFunction(To)) {
413 // Function changed.
414 MD->replaceAllUsesWith(nullptr);
415 delete MD;
416 return;
417 }
418 } else if (!isa<Constant>(To)) {
419 // Changed to function-local value.
420 MD->replaceAllUsesWith(nullptr);
421 delete MD;
422 return;
423 }
424
425 auto *&Entry = Store[To];
426 if (Entry) {
427 // The target already exists.
428 MD->replaceAllUsesWith(Entry);
429 delete MD;
430 return;
431 }
432
433 // Update MD in place (and update the map entry).
Dehao Chene0e0ed12016-09-16 18:27:20 +0000434 assert(!To->IsUsedByMD && "Expected this to be the only metadata use");
Owen Anderson7349ab92015-06-01 22:24:01 +0000435 To->IsUsedByMD = true;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000436 MD->V = To;
437 Entry = MD;
438}
Duncan P. N. Exon Smitha69934f2014-11-14 18:42:09 +0000439
Devang Patela4f43fb2009-07-28 21:49:47 +0000440//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000441// MDString implementation.
Owen Anderson0087fe62009-07-31 21:35:40 +0000442//
Chris Lattner5a409bd2009-12-28 08:30:43 +0000443
Devang Pateldcb99d32009-10-22 00:10:15 +0000444MDString *MDString::get(LLVMContext &Context, StringRef Str) {
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000445 auto &Store = Context.pImpl->MDStringCache;
Benjamin Kramereab3d362016-07-21 13:37:48 +0000446 auto I = Store.try_emplace(Str);
Mehdi Aminicb708b22016-03-25 05:58:04 +0000447 auto &MapEntry = I.first->getValue();
448 if (!I.second)
449 return &MapEntry;
450 MapEntry.Entry = &*I.first;
451 return &MapEntry;
Duncan P. N. Exon Smithf17e7402014-11-14 01:17:09 +0000452}
453
454StringRef MDString::getString() const {
Duncan P. N. Exon Smithc1a664f2014-12-05 01:41:34 +0000455 assert(Entry && "Expected to find string map entry");
456 return Entry->first();
Owen Anderson0087fe62009-07-31 21:35:40 +0000457}
458
459//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +0000460// MDNode implementation.
Devang Patela4f43fb2009-07-28 21:49:47 +0000461//
Chris Lattner74a6ad62009-12-28 07:41:54 +0000462
James Y Knight8096d342015-06-17 01:21:20 +0000463// Assert that the MDNode types will not be unaligned by the objects
464// prepended to them.
465#define HANDLE_MDNODE_LEAF(CLASS) \
James Y Knightf27e4412015-06-17 13:53:12 +0000466 static_assert( \
Benjamin Kramerb2505002016-10-20 15:02:18 +0000467 alignof(uint64_t) >= alignof(CLASS), \
James Y Knightf27e4412015-06-17 13:53:12 +0000468 "Alignment is insufficient after objects prepended to " #CLASS);
James Y Knight8096d342015-06-17 01:21:20 +0000469#include "llvm/IR/Metadata.def"
470
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000471void *MDNode::operator new(size_t Size, unsigned NumOps) {
James Y Knight8096d342015-06-17 01:21:20 +0000472 size_t OpSize = NumOps * sizeof(MDOperand);
473 // uint64_t is the most aligned type we need support (ensured by static_assert
474 // above)
Benjamin Kramerb2505002016-10-20 15:02:18 +0000475 OpSize = alignTo(OpSize, alignof(uint64_t));
James Y Knight8096d342015-06-17 01:21:20 +0000476 void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
Duncan P. N. Exon Smith22600ff2014-12-09 23:56:39 +0000477 MDOperand *O = static_cast<MDOperand *>(Ptr);
James Y Knight8096d342015-06-17 01:21:20 +0000478 for (MDOperand *E = O - NumOps; O != E; --O)
479 (void)new (O - 1) MDOperand;
480 return Ptr;
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000481}
482
Naomi Musgrave21c1bc42015-08-31 21:06:08 +0000483void MDNode::operator delete(void *Mem) {
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000484 MDNode *N = static_cast<MDNode *>(Mem);
James Y Knight8096d342015-06-17 01:21:20 +0000485 size_t OpSize = N->NumOperands * sizeof(MDOperand);
Benjamin Kramerb2505002016-10-20 15:02:18 +0000486 OpSize = alignTo(OpSize, alignof(uint64_t));
James Y Knight8096d342015-06-17 01:21:20 +0000487
Duncan P. N. Exon Smith22600ff2014-12-09 23:56:39 +0000488 MDOperand *O = static_cast<MDOperand *>(Mem);
489 for (MDOperand *E = O - N->NumOperands; O != E; --O)
490 (O - 1)->~MDOperand();
James Y Knight8096d342015-06-17 01:21:20 +0000491 ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
Duncan P. N. Exon Smithc23610b2014-11-18 01:56:14 +0000492}
493
Duncan P. N. Exon Smithf1340452015-01-19 18:36:18 +0000494MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
Duncan P. N. Exon Smithfed199a2015-01-20 00:01:43 +0000495 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
496 : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
497 NumUnresolved(0), Context(Context) {
498 unsigned Op = 0;
499 for (Metadata *MD : Ops1)
500 setOperand(Op++, MD);
501 for (Metadata *MD : Ops2)
502 setOperand(Op++, MD);
Duncan P. N. Exon Smith2711ca72015-01-19 19:02:06 +0000503
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000504 if (!isUniqued())
Duncan P. N. Exon Smith5e5b8502015-01-07 22:24:46 +0000505 return;
506
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000507 // Count the unresolved operands. If there are any, RAUW support will be
508 // added lazily on first reference.
509 countUnresolvedOperands();
Devang Patela4f43fb2009-07-28 21:49:47 +0000510}
511
Duncan P. N. Exon Smith03e05832015-01-20 02:56:57 +0000512TempMDNode MDNode::clone() const {
513 switch (getMetadataID()) {
514 default:
515 llvm_unreachable("Invalid MDNode subclass");
516#define HANDLE_MDNODE_LEAF(CLASS) \
517 case CLASS##Kind: \
518 return cast<CLASS>(this)->cloneImpl();
519#include "llvm/IR/Metadata.def"
520 }
521}
522
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000523static bool isOperandUnresolved(Metadata *Op) {
524 if (auto *N = dyn_cast_or_null<MDNode>(Op))
525 return !N->isResolved();
526 return false;
527}
528
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000529void MDNode::countUnresolvedOperands() {
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000530 assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000531 assert(isUniqued() && "Expected this to be uniqued");
Sanjoy Das39c226f2016-06-10 21:18:39 +0000532 NumUnresolved = count_if(operands(), isOperandUnresolved);
Duncan P. N. Exon Smithc5a0e2e2015-01-19 22:18:29 +0000533}
534
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000535void MDNode::makeUniqued() {
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000536 assert(isTemporary() && "Expected this to be temporary");
537 assert(!isResolved() && "Expected this to be unresolved");
538
Duncan P. N. Exon Smithcb33d6f2015-03-31 20:50:50 +0000539 // Enable uniquing callbacks.
540 for (auto &Op : mutable_operands())
541 Op.reset(Op.get(), this);
542
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000543 // Make this 'uniqued'.
544 Storage = Uniqued;
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000545 countUnresolvedOperands();
546 if (!NumUnresolved) {
547 dropReplaceableUses();
548 assert(isResolved() && "Expected this to be resolved");
549 }
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000550
551 assert(isUniqued() && "Expected this to be uniqued");
552}
553
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000554void MDNode::makeDistinct() {
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000555 assert(isTemporary() && "Expected this to be temporary");
556 assert(!isResolved() && "Expected this to be unresolved");
557
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000558 // Drop RAUW support and store as a distinct node.
559 dropReplaceableUses();
Duncan P. N. Exon Smithe3353092015-01-19 22:24:52 +0000560 storeDistinctInContext();
561
562 assert(isDistinct() && "Expected this to be distinct");
563 assert(isResolved() && "Expected this to be resolved");
564}
565
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000566void MDNode::resolve() {
Duncan P. N. Exon Smithb8f79602015-01-19 19:26:24 +0000567 assert(isUniqued() && "Expected this to be uniqued");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000568 assert(!isResolved() && "Expected this to be unresolved");
569
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000570 NumUnresolved = 0;
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000571 dropReplaceableUses();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000572
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000573 assert(isResolved() && "Expected this to be resolved");
574}
575
576void MDNode::dropReplaceableUses() {
577 assert(!NumUnresolved && "Unexpected unresolved operand");
578
579 // Drop any RAUW support.
580 if (Context.hasReplaceableUses())
581 Context.takeReplaceableUses()->resolveAllUses();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000582}
583
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000584void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000585 assert(isUniqued() && "Expected this to be uniqued");
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000586 assert(NumUnresolved != 0 && "Expected unresolved operands");
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000587
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000588 // Check if an operand was resolved.
Duncan P. N. Exon Smith845755c42015-01-13 00:46:34 +0000589 if (!isOperandUnresolved(Old)) {
590 if (isOperandUnresolved(New))
591 // An operand was un-resolved!
Duncan P. N. Exon Smith909131b2015-01-19 23:18:34 +0000592 ++NumUnresolved;
Duncan P. N. Exon Smith845755c42015-01-13 00:46:34 +0000593 } else if (!isOperandUnresolved(New))
Duncan P. N. Exon Smith0c87d772015-01-12 19:45:44 +0000594 decrementUnresolvedOperandCount();
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000595}
596
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000597void MDNode::decrementUnresolvedOperandCount() {
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000598 assert(!isResolved() && "Expected this to be unresolved");
599 if (isTemporary())
600 return;
601
602 assert(isUniqued() && "Expected this to be uniqued");
603 if (--NumUnresolved)
604 return;
605
606 // Last unresolved operand has just been resolved.
607 dropReplaceableUses();
608 assert(isResolved() && "Expected this to become resolved");
Duncan P. N. Exon Smith34c3d102015-01-12 19:43:15 +0000609}
610
Teresa Johnsonb703c772016-03-29 18:24:19 +0000611void MDNode::resolveCycles() {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000612 if (isResolved())
613 return;
614
615 // Resolve this node immediately.
616 resolve();
617
618 // Resolve all operands.
619 for (const auto &Op : operands()) {
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000620 auto *N = dyn_cast_or_null<MDNode>(Op);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000621 if (!N)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000622 continue;
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000623
624 assert(!N->isTemporary() &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000625 "Expected all forward declarations to be resolved");
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000626 if (!N->isResolved())
627 N->resolveCycles();
Chris Lattner8cb6c342009-12-31 01:05:46 +0000628 }
Duncan P. N. Exon Smith50846f82014-11-18 00:37:17 +0000629}
630
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000631static bool hasSelfReference(MDNode *N) {
632 for (Metadata *MD : N->operands())
633 if (MD == N)
634 return true;
635 return false;
636}
637
638MDNode *MDNode::replaceWithPermanentImpl() {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000639 switch (getMetadataID()) {
640 default:
641 // If this type isn't uniquable, replace with a distinct node.
642 return replaceWithDistinctImpl();
643
644#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
645 case CLASS##Kind: \
646 break;
647#include "llvm/IR/Metadata.def"
648 }
649
650 // Even if this type is uniquable, self-references have to be distinct.
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000651 if (hasSelfReference(this))
652 return replaceWithDistinctImpl();
653 return replaceWithUniquedImpl();
654}
655
Duncan P. N. Exon Smith86475292015-01-19 23:17:09 +0000656MDNode *MDNode::replaceWithUniquedImpl() {
657 // Try to uniquify in place.
658 MDNode *UniquedNode = uniquify();
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000659
Duncan P. N. Exon Smith86475292015-01-19 23:17:09 +0000660 if (UniquedNode == this) {
661 makeUniqued();
662 return this;
663 }
664
665 // Collision, so RAUW instead.
666 replaceAllUsesWith(UniquedNode);
667 deleteAsSubclass();
668 return UniquedNode;
669}
670
671MDNode *MDNode::replaceWithDistinctImpl() {
672 makeDistinct();
673 return this;
674}
675
Duncan P. N. Exon Smith118632d2015-01-12 20:09:34 +0000676void MDTuple::recalculateHash() {
Duncan P. N. Exon Smith93e983e2015-01-19 22:53:18 +0000677 setHash(MDTupleInfo::KeyTy::calculateHash(this));
Duncan P. N. Exon Smith967629e2015-01-12 19:16:34 +0000678}
679
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000680void MDNode::dropAllReferences() {
681 for (unsigned I = 0, E = NumOperands; I != E; ++I)
682 setOperand(I, nullptr);
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000683 if (Context.hasReplaceableUses()) {
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000684 Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
685 (void)Context.takeReplaceableUses();
686 }
Chris Lattner8cb6c342009-12-31 01:05:46 +0000687}
688
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000689void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000690 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
691 assert(Op < getNumOperands() && "Expected valid operand");
692
Duncan P. N. Exon Smith3d580562015-01-19 19:28:28 +0000693 if (!isUniqued()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000694 // This node is not uniqued. Just set the operand and be done with it.
695 setOperand(Op, New);
696 return;
Duncan Sandsc2928c62010-05-04 12:43:36 +0000697 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000698
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000699 // This node is uniqued.
700 eraseFromStore();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000701
702 Metadata *Old = getOperand(Op);
703 setOperand(Op, New);
704
Duncan P. N. Exon Smith9cbc69d2016-08-03 18:19:43 +0000705 // Drop uniquing for self-reference cycles and deleted constants.
706 if (New == this || (!New && Old && isa<ConstantAsMetadata>(Old))) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000707 if (!isResolved())
708 resolve();
Duncan P. N. Exon Smithf08b8b42015-01-19 19:25:33 +0000709 storeDistinctInContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000710 return;
711 }
712
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000713 // Re-unique the node.
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000714 auto *Uniqued = uniquify();
715 if (Uniqued == this) {
Duncan P. N. Exon Smith3a16d802015-01-12 19:14:15 +0000716 if (!isResolved())
717 resolveAfterOperandChange(Old, New);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000718 return;
719 }
720
721 // Collision.
722 if (!isResolved()) {
723 // Still unresolved, so RAUW.
Duncan P. N. Exon Smithd9e6eb72015-01-12 19:36:35 +0000724 //
725 // First, clear out all operands to prevent any recursion (similar to
726 // dropAllReferences(), but we still need the use-list).
727 for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
728 setOperand(O, nullptr);
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000729 if (Context.hasReplaceableUses())
730 Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000731 deleteAsSubclass();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000732 return;
733 }
734
Duncan P. N. Exon Smithd9e6eb72015-01-12 19:36:35 +0000735 // Store in non-uniqued form if RAUW isn't possible.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000736 storeDistinctInContext();
Victor Hernandeze5f2af72010-01-20 04:45:57 +0000737}
738
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000739void MDNode::deleteAsSubclass() {
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000740 switch (getMetadataID()) {
741 default:
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000742 llvm_unreachable("Invalid subclass of MDNode");
743#define HANDLE_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000744 case CLASS##Kind: \
745 delete cast<CLASS>(this); \
746 break;
747#include "llvm/IR/Metadata.def"
748 }
749}
750
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000751template <class T, class InfoT>
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000752static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
753 if (T *U = getUniqued(Store, N))
754 return U;
755
756 Store.insert(N);
757 return N;
758}
759
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000760template <class NodeTy> struct MDNode::HasCachedHash {
761 typedef char Yes[1];
762 typedef char No[2];
763 template <class U, U Val> struct SFINAE {};
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000764
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000765 template <class U>
766 static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
767 template <class U> static No &check(...);
768
769 static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
770};
771
772MDNode *MDNode::uniquify() {
Duncan P. N. Exon Smith4ee4a982015-02-10 19:13:46 +0000773 assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
774
Duncan P. N. Exon Smithf9d1bc92015-01-19 22:52:07 +0000775 // Try to insert into uniquing store.
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000776 switch (getMetadataID()) {
777 default:
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000778 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
779#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000780 case CLASS##Kind: { \
781 CLASS *SubclassThis = cast<CLASS>(this); \
782 std::integral_constant<bool, HasCachedHash<CLASS>::value> \
783 ShouldRecalculateHash; \
784 dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
785 return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
786 }
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000787#include "llvm/IR/Metadata.def"
788 }
789}
790
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000791void MDNode::eraseFromStore() {
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000792 switch (getMetadataID()) {
793 default:
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +0000794 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
795#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000796 case CLASS##Kind: \
Duncan P. N. Exon Smith6cf10d22015-01-19 22:47:08 +0000797 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
Duncan P. N. Exon Smithbf68e802015-01-12 20:56:33 +0000798 break;
799#include "llvm/IR/Metadata.def"
800 }
801}
802
Duncan P. N. Exon Smithac3128d2015-01-12 20:13:56 +0000803MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000804 StorageType Storage, bool ShouldCreate) {
805 unsigned Hash = 0;
806 if (Storage == Uniqued) {
807 MDTupleInfo::KeyTy Key(MDs);
Duncan P. N. Exon Smithb57f9e92015-01-19 20:16:50 +0000808 if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
809 return N;
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000810 if (!ShouldCreate)
811 return nullptr;
Duncan P. N. Exon Smith93e983e2015-01-19 22:53:18 +0000812 Hash = Key.getHash();
Duncan P. N. Exon Smith1b0064d2015-01-19 20:14:15 +0000813 } else {
814 assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
815 }
Duncan Sands26a80f32012-03-31 08:20:11 +0000816
Duncan P. N. Exon Smith5b8c4402015-01-19 20:18:13 +0000817 return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
818 Storage, Context.pImpl->MDTuples);
Duncan P. N. Exon Smith5e5b8502015-01-07 22:24:46 +0000819}
820
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000821void MDNode::deleteTemporary(MDNode *N) {
822 assert(N->isTemporary() && "Expected temporary node");
Duncan P. N. Exon Smith8d536972015-01-22 21:36:45 +0000823 N->replaceAllUsesWith(nullptr);
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000824 N->deleteAsSubclass();
Dan Gohman16a5d982010-08-20 22:02:26 +0000825}
826
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000827void MDNode::storeDistinctInContext() {
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000828 assert(!Context.hasReplaceableUses() && "Unexpected replaceable uses");
829 assert(!NumUnresolved && "Unexpected unresolved nodes");
Duncan P. N. Exon Smithf1340452015-01-19 18:36:18 +0000830 Storage = Distinct;
Duncan P. N. Exon Smithfef609f2016-04-03 21:23:52 +0000831 assert(isResolved() && "Expected this to be resolved");
Duncan P. N. Exon Smith0f529992015-01-20 00:57:33 +0000832
833 // Reset the hash.
834 switch (getMetadataID()) {
835 default:
836 llvm_unreachable("Invalid subclass of MDNode");
837#define HANDLE_MDNODE_LEAF(CLASS) \
838 case CLASS##Kind: { \
839 std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
840 dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
841 break; \
842 }
843#include "llvm/IR/Metadata.def"
844 }
845
Duncan P. N. Exon Smith3eef9d12016-04-19 23:59:13 +0000846 getContext().pImpl->DistinctMDNodes.push_back(this);
Devang Patel82ab3f82010-02-18 20:53:16 +0000847}
Chris Lattnerf543eff2009-12-28 09:12:35 +0000848
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000849void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
850 if (getOperand(I) == New)
Devang Patelf7188322009-09-03 01:39:20 +0000851 return;
Devang Patelf7188322009-09-03 01:39:20 +0000852
Duncan P. N. Exon Smithde03a8b2015-01-19 18:45:35 +0000853 if (!isUniqued()) {
Duncan P. N. Exon Smithdaa335a2015-01-12 18:01:45 +0000854 setOperand(I, New);
Duncan P. N. Exon Smithf39c3b82014-11-17 23:28:21 +0000855 return;
856 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +0000857
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000858 handleChangedOperand(mutable_begin() + I, New);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000859}
Chris Lattnerc6d17e22009-12-28 09:24:53 +0000860
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000861void MDNode::setOperand(unsigned I, Metadata *New) {
862 assert(I < NumOperands);
Duncan P. N. Exon Smithefdf2852015-01-19 19:29:25 +0000863 mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
Devang Patelf7188322009-09-03 01:39:20 +0000864}
865
Sanjay Patel9da9c762016-03-12 20:44:58 +0000866/// Get a node or a self-reference that looks like it.
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000867///
868/// Special handling for finding self-references, for use by \a
869/// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
870/// when self-referencing nodes were still uniqued. If the first operand has
871/// the same operands as \c Ops, return the first operand instead.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000872static MDNode *getOrSelfReference(LLVMContext &Context,
873 ArrayRef<Metadata *> Ops) {
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000874 if (!Ops.empty())
875 if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
876 if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
877 for (unsigned I = 1, E = Ops.size(); I != E; ++I)
878 if (Ops[I] != N->getOperand(I))
879 return MDNode::get(Context, Ops);
880 return N;
881 }
882
883 return MDNode::get(Context, Ops);
884}
885
Hal Finkel94146652014-07-24 14:25:39 +0000886MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
887 if (!A)
888 return B;
889 if (!B)
890 return A;
891
David Majnemerfa0f1e62016-08-16 18:48:34 +0000892 SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
893 MDs.insert(B->op_begin(), B->op_end());
Hal Finkel94146652014-07-24 14:25:39 +0000894
Duncan P. N. Exon Smith9c51b502014-12-07 20:32:11 +0000895 // FIXME: This preserves long-standing behaviour, but is it really the right
896 // behaviour? Or was that an unintended side-effect of node uniquing?
David Majnemerfa0f1e62016-08-16 18:48:34 +0000897 return getOrSelfReference(A->getContext(), MDs.getArrayRef());
Hal Finkel94146652014-07-24 14:25:39 +0000898}
899
900MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
901 if (!A || !B)
902 return nullptr;
903
David Majnemer00940fb2016-08-16 18:48:37 +0000904 SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
905 SmallPtrSet<Metadata *, 4> BSet(B->op_begin(), B->op_end());
906 MDs.remove_if([&](Metadata *MD) { return !is_contained(BSet, MD); });
Hal Finkel94146652014-07-24 14:25:39 +0000907
Duncan P. N. Exon Smithac8ee282014-12-07 19:52:06 +0000908 // FIXME: This preserves long-standing behaviour, but is it really the right
909 // behaviour? Or was that an unintended side-effect of node uniquing?
David Majnemer00940fb2016-08-16 18:48:37 +0000910 return getOrSelfReference(A->getContext(), MDs.getArrayRef());
Hal Finkel94146652014-07-24 14:25:39 +0000911}
912
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +0000913MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
914 if (!A || !B)
915 return nullptr;
916
David Majnemerfa0f1e62016-08-16 18:48:34 +0000917 return concatenate(A, B);
Bjorn Steinbrink5ec75222015-02-08 17:07:14 +0000918}
919
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000920MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
921 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000922 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000923
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000924 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
925 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000926 if (AVal.compare(BVal) == APFloat::cmpLessThan)
927 return A;
928 return B;
929}
930
931static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
932 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
933}
934
935static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
936 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
937}
938
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000939static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
940 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000941 ConstantRange NewRange(Low->getValue(), High->getValue());
942 unsigned Size = EndPoints.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000943 APInt LB = EndPoints[Size - 2]->getValue();
944 APInt LE = EndPoints[Size - 1]->getValue();
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000945 ConstantRange LastRange(LB, LE);
946 if (canBeMerged(NewRange, LastRange)) {
947 ConstantRange Union = LastRange.unionWith(NewRange);
948 Type *Ty = High->getType();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000949 EndPoints[Size - 2] =
950 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
951 EndPoints[Size - 1] =
952 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000953 return true;
954 }
955 return false;
956}
957
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000958static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
959 ConstantInt *Low, ConstantInt *High) {
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000960 if (!EndPoints.empty())
961 if (tryMergeRange(EndPoints, Low, High))
962 return;
963
964 EndPoints.push_back(Low);
965 EndPoints.push_back(High);
966}
967
968MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
969 // Given two ranges, we want to compute the union of the ranges. This
970 // is slightly complitade by having to combine the intervals and merge
971 // the ones that overlap.
972
973 if (!A || !B)
Craig Topperc6207612014-04-09 06:08:46 +0000974 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000975
976 if (A == B)
977 return A;
978
979 // First, walk both lists in older of the lower boundary of each interval.
980 // 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 +0000981 SmallVector<ConstantInt *, 4> EndPoints;
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000982 int AI = 0;
983 int BI = 0;
984 int AN = A->getNumOperands() / 2;
985 int BN = B->getNumOperands() / 2;
986 while (AI < AN && BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000987 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
988 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000989
990 if (ALow->getValue().slt(BLow->getValue())) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000991 addRange(EndPoints, ALow,
992 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000993 ++AI;
994 } else {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000995 addRange(EndPoints, BLow,
996 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +0000997 ++BI;
998 }
999 }
1000 while (AI < AN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001001 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
1002 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001003 ++AI;
1004 }
1005 while (BI < BN) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001006 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
1007 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001008 ++BI;
1009 }
1010
1011 // If we have more than 2 ranges (4 endpoints) we have to try to merge
1012 // the last and first ones.
1013 unsigned Size = EndPoints.size();
1014 if (Size > 4) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001015 ConstantInt *FB = EndPoints[0];
1016 ConstantInt *FE = EndPoints[1];
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001017 if (tryMergeRange(EndPoints, FB, FE)) {
1018 for (unsigned i = 0; i < Size - 2; ++i) {
1019 EndPoints[i] = EndPoints[i + 2];
1020 }
1021 EndPoints.resize(Size - 2);
1022 }
1023 }
1024
1025 // If in the end we have a single range, it is possible that it is now the
1026 // full range. Just drop the metadata in that case.
1027 if (EndPoints.size() == 2) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001028 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001029 if (Range.isFullSet())
Craig Topperc6207612014-04-09 06:08:46 +00001030 return nullptr;
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001031 }
1032
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001033 SmallVector<Metadata *, 4> MDs;
1034 MDs.reserve(EndPoints.size());
1035 for (auto *I : EndPoints)
1036 MDs.push_back(ConstantAsMetadata::get(I));
1037 return MDNode::get(A->getContext(), MDs);
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001038}
1039
Artur Pilipenko5c5011d2015-11-02 17:53:51 +00001040MDNode *MDNode::getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B) {
1041 if (!A || !B)
1042 return nullptr;
1043
1044 ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
1045 ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
1046 if (AVal->getZExtValue() < BVal->getZExtValue())
1047 return A;
1048 return B;
1049}
1050
Devang Patel05a26fb2009-07-29 00:33:07 +00001051//===----------------------------------------------------------------------===//
Chris Lattnerb0c23e82009-10-19 07:10:59 +00001052// NamedMDNode implementation.
Devang Patel05a26fb2009-07-29 00:33:07 +00001053//
Devang Patel943ddf62010-01-12 18:34:06 +00001054
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001055static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
1056 return *(SmallVector<TrackingMDRef, 4> *)Operands;
Chris Lattner1bc810b2009-12-28 08:07:14 +00001057}
1058
Dan Gohman2637cc12010-07-21 23:38:33 +00001059NamedMDNode::NamedMDNode(const Twine &N)
Eugene Zelenkodeaf6952017-02-17 00:00:09 +00001060 : Name(N.str()), Operands(new SmallVector<TrackingMDRef, 4>()) {}
Devang Patel5c310be2009-08-11 18:01:24 +00001061
Chris Lattner1bc810b2009-12-28 08:07:14 +00001062NamedMDNode::~NamedMDNode() {
1063 dropAllReferences();
1064 delete &getNMDOps(Operands);
1065}
1066
Chris Lattner9b493022009-12-31 01:22:29 +00001067unsigned NamedMDNode::getNumOperands() const {
Chris Lattner1bc810b2009-12-28 08:07:14 +00001068 return (unsigned)getNMDOps(Operands).size();
1069}
1070
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001071MDNode *NamedMDNode::getOperand(unsigned i) const {
Chris Lattner9b493022009-12-31 01:22:29 +00001072 assert(i < getNumOperands() && "Invalid Operand number!");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001073 auto *N = getNMDOps(Operands)[i].get();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001074 return cast_or_null<MDNode>(N);
Chris Lattner1bc810b2009-12-28 08:07:14 +00001075}
1076
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001077void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
Chris Lattner1bc810b2009-12-28 08:07:14 +00001078
Duncan P. N. Exon Smithdf55d8b2015-01-07 21:32:27 +00001079void NamedMDNode::setOperand(unsigned I, MDNode *New) {
1080 assert(I < getNumOperands() && "Invalid operand number");
1081 getNMDOps(Operands)[I].reset(New);
1082}
1083
Dehao Chene0e0ed12016-09-16 18:27:20 +00001084void NamedMDNode::eraseFromParent() { getParent()->eraseNamedMetadata(this); }
Devang Patel79238d72009-08-03 06:19:01 +00001085
Michael Ilsemane5428042016-10-25 18:44:13 +00001086void NamedMDNode::clearOperands() { getNMDOps(Operands).clear(); }
Devang Patel79238d72009-08-03 06:19:01 +00001087
Dehao Chene0e0ed12016-09-16 18:27:20 +00001088StringRef NamedMDNode::getName() const { return StringRef(Name); }
Devang Pateld5497a4b2009-09-16 18:09:00 +00001089
1090//===----------------------------------------------------------------------===//
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001091// Instruction Metadata method implementations.
1092//
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001093void MDAttachmentMap::set(unsigned ID, MDNode &MD) {
1094 for (auto &I : Attachments)
1095 if (I.first == ID) {
1096 I.second.reset(&MD);
1097 return;
1098 }
1099 Attachments.emplace_back(std::piecewise_construct, std::make_tuple(ID),
1100 std::make_tuple(&MD));
1101}
1102
1103void MDAttachmentMap::erase(unsigned ID) {
1104 if (empty())
1105 return;
1106
1107 // Common case is one/last value.
1108 if (Attachments.back().first == ID) {
1109 Attachments.pop_back();
1110 return;
1111 }
1112
1113 for (auto I = Attachments.begin(), E = std::prev(Attachments.end()); I != E;
1114 ++I)
1115 if (I->first == ID) {
1116 *I = std::move(Attachments.back());
1117 Attachments.pop_back();
1118 return;
1119 }
1120}
1121
1122MDNode *MDAttachmentMap::lookup(unsigned ID) const {
1123 for (const auto &I : Attachments)
1124 if (I.first == ID)
1125 return I.second;
1126 return nullptr;
1127}
1128
1129void MDAttachmentMap::getAll(
1130 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1131 Result.append(Attachments.begin(), Attachments.end());
1132
1133 // Sort the resulting array so it is stable.
1134 if (Result.size() > 1)
1135 array_pod_sort(Result.begin(), Result.end());
1136}
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001137
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001138void MDGlobalAttachmentMap::insert(unsigned ID, MDNode &MD) {
1139 Attachments.push_back({ID, TrackingMDNodeRef(&MD)});
1140}
1141
1142void MDGlobalAttachmentMap::get(unsigned ID,
1143 SmallVectorImpl<MDNode *> &Result) {
1144 for (auto A : Attachments)
1145 if (A.MDKind == ID)
1146 Result.push_back(A.Node);
1147}
1148
1149void MDGlobalAttachmentMap::erase(unsigned ID) {
1150 auto Follower = Attachments.begin();
1151 for (auto Leader = Attachments.begin(), E = Attachments.end(); Leader != E;
1152 ++Leader) {
1153 if (Leader->MDKind != ID) {
1154 if (Follower != Leader)
1155 *Follower = std::move(*Leader);
1156 ++Follower;
1157 }
1158 }
1159 Attachments.resize(Follower - Attachments.begin());
1160}
1161
1162void MDGlobalAttachmentMap::getAll(
1163 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1164 for (auto &A : Attachments)
1165 Result.emplace_back(A.MDKind, A.Node);
1166
1167 // Sort the resulting array so it is stable with respect to metadata IDs. We
1168 // need to preserve the original insertion order though.
1169 std::stable_sort(
1170 Result.begin(), Result.end(),
1171 [](const std::pair<unsigned, MDNode *> &A,
1172 const std::pair<unsigned, MDNode *> &B) { return A.first < B.first; });
1173}
1174
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001175void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
1176 if (!Node && !hasMetadata())
1177 return;
1178 setMetadata(getContext().getMDKindID(Kind), Node);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001179}
1180
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001181MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
Chris Lattnera0566972009-12-29 09:01:33 +00001182 return getMetadataImpl(getContext().getMDKindID(Kind));
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001183}
1184
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00001185void Instruction::dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs) {
Rafael Espindolaab73c492014-01-28 16:56:46 +00001186 if (!hasMetadataHashEntry())
1187 return; // Nothing to remove!
1188
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001189 auto &InstructionMetadata = getContext().pImpl->InstructionMetadata;
Rafael Espindolaab73c492014-01-28 16:56:46 +00001190
Aditya Kumar0a48b372016-09-26 21:01:13 +00001191 SmallSet<unsigned, 4> KnownSet;
1192 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
Rafael Espindolaab73c492014-01-28 16:56:46 +00001193 if (KnownSet.empty()) {
1194 // Just drop our entry at the store.
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001195 InstructionMetadata.erase(this);
Rafael Espindolaab73c492014-01-28 16:56:46 +00001196 setHasMetadataHashEntry(false);
1197 return;
1198 }
1199
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001200 auto &Info = InstructionMetadata[this];
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001201 Info.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1202 return !KnownSet.count(I.first);
1203 });
Rafael Espindolaab73c492014-01-28 16:56:46 +00001204
Duncan P. N. Exon Smith75ef0c02015-04-24 20:23:44 +00001205 if (Info.empty()) {
Rafael Espindolaab73c492014-01-28 16:56:46 +00001206 // Drop our entry at the store.
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001207 InstructionMetadata.erase(this);
Rafael Espindolaab73c492014-01-28 16:56:46 +00001208 setHasMetadataHashEntry(false);
1209 }
1210}
1211
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001212void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1213 if (!Node && !hasMetadata())
1214 return;
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001215
Chris Lattnerc263b422010-03-30 23:03:27 +00001216 // Handle 'dbg' as a special case since it is not stored in the hash table.
1217 if (KindID == LLVMContext::MD_dbg) {
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00001218 DbgLoc = DebugLoc(Node);
Chris Lattnerc263b422010-03-30 23:03:27 +00001219 return;
1220 }
Dehao Chene0e0ed12016-09-16 18:27:20 +00001221
Chris Lattnera0566972009-12-29 09:01:33 +00001222 // Handle the case when we're adding/updating metadata on an instruction.
1223 if (Node) {
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001224 auto &Info = getContext().pImpl->InstructionMetadata[this];
Chris Lattnerc263b422010-03-30 23:03:27 +00001225 assert(!Info.empty() == hasMetadataHashEntry() &&
1226 "HasMetadata bit is wonked");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001227 if (Info.empty())
Chris Lattnerc263b422010-03-30 23:03:27 +00001228 setHasMetadataHashEntry(true);
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001229 Info.set(KindID, *Node);
Chris Lattnera0566972009-12-29 09:01:33 +00001230 return;
1231 }
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001232
Chris Lattnera0566972009-12-29 09:01:33 +00001233 // Otherwise, we're removing metadata from an instruction.
Nick Lewycky4c131382011-12-27 01:17:40 +00001234 assert((hasMetadataHashEntry() ==
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001235 (getContext().pImpl->InstructionMetadata.count(this) > 0)) &&
Chris Lattnera0566972009-12-29 09:01:33 +00001236 "HasMetadata bit out of date!");
Nick Lewycky4c131382011-12-27 01:17:40 +00001237 if (!hasMetadataHashEntry())
Dehao Chene0e0ed12016-09-16 18:27:20 +00001238 return; // Nothing to remove!
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001239 auto &Info = getContext().pImpl->InstructionMetadata[this];
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001240
Chris Lattnerc263b422010-03-30 23:03:27 +00001241 // Handle removal of an existing value.
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001242 Info.erase(KindID);
1243
1244 if (!Info.empty())
1245 return;
1246
1247 getContext().pImpl->InstructionMetadata.erase(this);
1248 setHasMetadataHashEntry(false);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001249}
1250
Hal Finkelcc39b672014-07-24 12:16:19 +00001251void Instruction::setAAMetadata(const AAMDNodes &N) {
1252 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
Hal Finkel94146652014-07-24 14:25:39 +00001253 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1254 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
Hal Finkelcc39b672014-07-24 12:16:19 +00001255}
1256
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001257MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
Chris Lattnerc263b422010-03-30 23:03:27 +00001258 // Handle 'dbg' as a special case since it is not stored in the hash table.
1259 if (KindID == LLVMContext::MD_dbg)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001260 return DbgLoc.getAsMDNode();
1261
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001262 if (!hasMetadataHashEntry())
1263 return nullptr;
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001264 auto &Info = getContext().pImpl->InstructionMetadata[this];
Chris Lattnerc263b422010-03-30 23:03:27 +00001265 assert(!Info.empty() && "bit out of sync with hash table");
Mikhail Glushenkoved3bd132010-01-10 18:48:49 +00001266
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001267 return Info.lookup(KindID);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001268}
1269
Duncan P. N. Exon Smith4abd1a02014-11-01 00:26:42 +00001270void Instruction::getAllMetadataImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001271 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc263b422010-03-30 23:03:27 +00001272 Result.clear();
Dehao Chene0e0ed12016-09-16 18:27:20 +00001273
Chris Lattnerc263b422010-03-30 23:03:27 +00001274 // 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 +00001275 if (DbgLoc) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001276 Result.push_back(
1277 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
Dehao Chene0e0ed12016-09-16 18:27:20 +00001278 if (!hasMetadataHashEntry())
1279 return;
Chris Lattnerc263b422010-03-30 23:03:27 +00001280 }
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001281
Chris Lattnerc263b422010-03-30 23:03:27 +00001282 assert(hasMetadataHashEntry() &&
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001283 getContext().pImpl->InstructionMetadata.count(this) &&
Chris Lattnera0566972009-12-29 09:01:33 +00001284 "Shouldn't have called this");
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001285 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
Chris Lattnera0566972009-12-29 09:01:33 +00001286 assert(!Info.empty() && "Shouldn't have called this");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001287 Info.getAll(Result);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001288}
1289
Duncan P. N. Exon Smith3d5a02f2014-11-03 18:13:57 +00001290void Instruction::getAllMetadataOtherThanDebugLocImpl(
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001291 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001292 Result.clear();
1293 assert(hasMetadataHashEntry() &&
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001294 getContext().pImpl->InstructionMetadata.count(this) &&
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001295 "Shouldn't have called this");
Duncan P. N. Exon Smith14a384b2015-04-24 20:19:13 +00001296 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001297 assert(!Info.empty() && "Shouldn't have called this");
Duncan P. N. Exon Smithcbc28dc2015-04-24 20:36:25 +00001298 Info.getAll(Result);
Chris Lattnerc0f5ce32010-04-01 05:23:13 +00001299}
1300
Dehao Chene0e0ed12016-09-16 18:27:20 +00001301bool Instruction::extractProfMetadata(uint64_t &TrueVal,
1302 uint64_t &FalseVal) const {
1303 assert(
1304 (getOpcode() == Instruction::Br || getOpcode() == Instruction::Select) &&
1305 "Looking for branch weights on something besides branch or select");
Sanjay Pateld66607b2016-04-26 17:11:17 +00001306
1307 auto *ProfileData = getMetadata(LLVMContext::MD_prof);
1308 if (!ProfileData || ProfileData->getNumOperands() != 3)
1309 return false;
1310
1311 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
1312 if (!ProfDataName || !ProfDataName->getString().equals("branch_weights"))
1313 return false;
1314
1315 auto *CITrue = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
1316 auto *CIFalse = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
1317 if (!CITrue || !CIFalse)
1318 return false;
1319
1320 TrueVal = CITrue->getValue().getZExtValue();
1321 FalseVal = CIFalse->getValue().getZExtValue();
1322
1323 return true;
1324}
1325
Dehao Chene0e0ed12016-09-16 18:27:20 +00001326bool Instruction::extractProfTotalWeight(uint64_t &TotalVal) const {
Dehao Chen9232f982016-07-11 16:48:54 +00001327 assert((getOpcode() == Instruction::Br ||
1328 getOpcode() == Instruction::Select ||
Dehao Chen71021cd2016-07-11 17:36:02 +00001329 getOpcode() == Instruction::Call ||
Dehao Chene9d07522016-10-11 18:53:00 +00001330 getOpcode() == Instruction::Invoke ||
1331 getOpcode() == Instruction::Switch) &&
Dehao Chen9232f982016-07-11 16:48:54 +00001332 "Looking for branch weights on something besides branch");
1333
1334 TotalVal = 0;
1335 auto *ProfileData = getMetadata(LLVMContext::MD_prof);
1336 if (!ProfileData)
1337 return false;
1338
1339 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
Dehao Chenfed890e2017-03-31 15:59:52 +00001340 if (!ProfDataName)
Dehao Chen9232f982016-07-11 16:48:54 +00001341 return false;
1342
Dehao Chenfed890e2017-03-31 15:59:52 +00001343 if (ProfDataName->getString().equals("branch_weights")) {
1344 TotalVal = 0;
1345 for (unsigned i = 1; i < ProfileData->getNumOperands(); i++) {
1346 auto *V = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i));
1347 if (!V)
1348 return false;
1349 TotalVal += V->getValue().getZExtValue();
1350 }
1351 return true;
1352 } else if (ProfDataName->getString().equals("VP") &&
1353 ProfileData->getNumOperands() > 3) {
1354 TotalVal = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2))
1355 ->getValue()
1356 .getZExtValue();
1357 return true;
Dehao Chen9232f982016-07-11 16:48:54 +00001358 }
Dehao Chenfed890e2017-03-31 15:59:52 +00001359 return false;
Dehao Chen9232f982016-07-11 16:48:54 +00001360}
1361
Dan Gohman48a995f2010-07-20 22:25:04 +00001362void Instruction::clearMetadataHashEntries() {
1363 assert(hasMetadataHashEntry() && "Caller should check");
Duncan P. N. Exon Smith391fc562015-04-24 20:16:42 +00001364 getContext().pImpl->InstructionMetadata.erase(this);
Dan Gohman48a995f2010-07-20 22:25:04 +00001365 setHasMetadataHashEntry(false);
Chris Lattner68017802009-12-29 07:44:16 +00001366}
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001367
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001368void GlobalObject::getMetadata(unsigned KindID,
1369 SmallVectorImpl<MDNode *> &MDs) const {
1370 if (hasMetadata())
1371 getContext().pImpl->GlobalObjectMetadata[this].get(KindID, MDs);
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001372}
1373
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001374void GlobalObject::getMetadata(StringRef Kind,
1375 SmallVectorImpl<MDNode *> &MDs) const {
1376 if (hasMetadata())
1377 getMetadata(getContext().getMDKindID(Kind), MDs);
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001378}
1379
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001380void GlobalObject::addMetadata(unsigned KindID, MDNode &MD) {
1381 if (!hasMetadata())
1382 setHasMetadataHashEntry(true);
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001383
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001384 getContext().pImpl->GlobalObjectMetadata[this].insert(KindID, MD);
1385}
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001386
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001387void GlobalObject::addMetadata(StringRef Kind, MDNode &MD) {
1388 addMetadata(getContext().getMDKindID(Kind), MD);
1389}
1390
1391void GlobalObject::eraseMetadata(unsigned KindID) {
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001392 // Nothing to unset.
1393 if (!hasMetadata())
1394 return;
1395
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001396 auto &Store = getContext().pImpl->GlobalObjectMetadata[this];
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001397 Store.erase(KindID);
1398 if (Store.empty())
1399 clearMetadata();
1400}
1401
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001402void GlobalObject::getAllMetadata(
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001403 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
1404 MDs.clear();
1405
1406 if (!hasMetadata())
1407 return;
1408
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001409 getContext().pImpl->GlobalObjectMetadata[this].getAll(MDs);
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001410}
1411
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001412void GlobalObject::clearMetadata() {
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001413 if (!hasMetadata())
1414 return;
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001415 getContext().pImpl->GlobalObjectMetadata.erase(this);
Duncan P. N. Exon Smithe2510cd2015-04-24 21:51:02 +00001416 setHasMetadataHashEntry(false);
1417}
Duncan P. N. Exon Smithb56b5af2015-08-28 21:55:35 +00001418
Peter Collingbourne382d81c2016-06-01 01:17:57 +00001419void GlobalObject::setMetadata(unsigned KindID, MDNode *N) {
1420 eraseMetadata(KindID);
1421 if (N)
1422 addMetadata(KindID, *N);
1423}
1424
1425void GlobalObject::setMetadata(StringRef Kind, MDNode *N) {
1426 setMetadata(getContext().getMDKindID(Kind), N);
1427}
1428
1429MDNode *GlobalObject::getMetadata(unsigned KindID) const {
1430 SmallVector<MDNode *, 1> MDs;
1431 getMetadata(KindID, MDs);
1432 assert(MDs.size() <= 1 && "Expected at most one metadata attachment");
1433 if (MDs.empty())
1434 return nullptr;
1435 return MDs[0];
1436}
1437
1438MDNode *GlobalObject::getMetadata(StringRef Kind) const {
1439 return getMetadata(getContext().getMDKindID(Kind));
1440}
1441
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001442void GlobalObject::copyMetadata(const GlobalObject *Other, unsigned Offset) {
Peter Collingbourne4f7c16d2016-06-24 17:42:21 +00001443 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1444 Other->getAllMetadata(MDs);
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001445 for (auto &MD : MDs) {
1446 // We need to adjust the type metadata offset.
1447 if (Offset != 0 && MD.first == LLVMContext::MD_type) {
1448 auto *OffsetConst = cast<ConstantInt>(
1449 cast<ConstantAsMetadata>(MD.second->getOperand(0))->getValue());
1450 Metadata *TypeId = MD.second->getOperand(1);
1451 auto *NewOffsetMD = ConstantAsMetadata::get(ConstantInt::get(
1452 OffsetConst->getType(), OffsetConst->getValue() + Offset));
1453 addMetadata(LLVMContext::MD_type,
1454 *MDNode::get(getContext(), {NewOffsetMD, TypeId}));
1455 continue;
1456 }
Peter Collingbourned4135bb2016-09-13 01:12:59 +00001457 // If an offset adjustment was specified we need to modify the DIExpression
1458 // to prepend the adjustment:
1459 // !DIExpression(DW_OP_plus, Offset, [original expr])
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001460 auto *Attachment = MD.second;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00001461 if (Offset != 0 && MD.first == LLVMContext::MD_dbg) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001462 DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(Attachment);
1463 DIExpression *E = nullptr;
1464 if (!GV) {
1465 auto *GVE = cast<DIGlobalVariableExpression>(Attachment);
1466 GV = GVE->getVariable();
1467 E = GVE->getExpression();
1468 }
Peter Collingbourned4135bb2016-09-13 01:12:59 +00001469 ArrayRef<uint64_t> OrigElements;
1470 if (E)
1471 OrigElements = E->getElements();
1472 std::vector<uint64_t> Elements(OrigElements.size() + 2);
1473 Elements[0] = dwarf::DW_OP_plus;
1474 Elements[1] = Offset;
1475 std::copy(OrigElements.begin(), OrigElements.end(), Elements.begin() + 2);
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001476 E = DIExpression::get(getContext(), Elements);
1477 Attachment = DIGlobalVariableExpression::get(getContext(), GV, E);
Peter Collingbourned4135bb2016-09-13 01:12:59 +00001478 }
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001479 addMetadata(MD.first, *Attachment);
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001480 }
1481}
1482
1483void GlobalObject::addTypeMetadata(unsigned Offset, Metadata *TypeID) {
1484 addMetadata(
1485 LLVMContext::MD_type,
1486 *MDTuple::get(getContext(),
Eugene Zelenkodeaf6952017-02-17 00:00:09 +00001487 {ConstantAsMetadata::get(llvm::ConstantInt::get(
Peter Collingbourne7efd7502016-06-24 21:21:32 +00001488 Type::getInt64Ty(getContext()), Offset)),
1489 TypeID}));
Peter Collingbourne4f7c16d2016-06-24 17:42:21 +00001490}
1491
Duncan P. N. Exon Smithb56b5af2015-08-28 21:55:35 +00001492void Function::setSubprogram(DISubprogram *SP) {
1493 setMetadata(LLVMContext::MD_dbg, SP);
1494}
1495
1496DISubprogram *Function::getSubprogram() const {
1497 return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));
1498}
Peter Collingbourned4135bb2016-09-13 01:12:59 +00001499
Dehao Chenfb02f712017-02-10 21:09:07 +00001500bool Function::isDebugInfoForProfiling() const {
1501 if (DISubprogram *SP = getSubprogram()) {
1502 if (DICompileUnit *CU = SP->getUnit()) {
1503 return CU->getDebugInfoForProfiling();
1504 }
1505 }
1506 return false;
1507}
1508
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001509void GlobalVariable::addDebugInfo(DIGlobalVariableExpression *GV) {
Peter Collingbourned4135bb2016-09-13 01:12:59 +00001510 addMetadata(LLVMContext::MD_dbg, *GV);
1511}
1512
1513void GlobalVariable::getDebugInfo(
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001514 SmallVectorImpl<DIGlobalVariableExpression *> &GVs) const {
Peter Collingbourned4135bb2016-09-13 01:12:59 +00001515 SmallVector<MDNode *, 1> MDs;
1516 getMetadata(LLVMContext::MD_dbg, MDs);
1517 for (MDNode *MD : MDs)
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001518 GVs.push_back(cast<DIGlobalVariableExpression>(MD));
Peter Collingbourned4135bb2016-09-13 01:12:59 +00001519}