blob: 5536c2497f1e986859933cf9fd5a90f5367d93a8 [file] [log] [blame]
Duncan P. N. Exon Smith0784a4d2015-02-02 18:20:15 +00001//===- Metadata.cpp - Implement Metadata classes --------------------------===//
Devang Patel0a9f7b92009-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 Lattner37da0ad2009-12-28 08:24:16 +000014#include "LLVMContextImpl.h"
Duncan P. N. Exon Smithca8d3bf2015-02-02 18:53:21 +000015#include "MetadataImpl.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "SymbolTableListTraitsImpl.h"
Eugene Zelenkob1df7872017-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"
Chandler Carruthe3e43d92017-06-06 11:49:48 +000022#include "llvm/ADT/STLExtras.h"
David Majnemer9c509582016-08-16 18:48:34 +000023#include "llvm/ADT/SetVector.h"
Eugene Zelenkob1df7872017-02-17 00:00:09 +000024#include "llvm/ADT/SmallPtrSet.h"
Rafael Espindolaf611ae42014-01-28 16:56:46 +000025#include "llvm/ADT/SmallSet.h"
Eugene Zelenkob1df7872017-02-17 00:00:09 +000026#include "llvm/ADT/SmallVector.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000027#include "llvm/ADT/StringMap.h"
Eugene Zelenkob1df7872017-02-17 00:00:09 +000028#include "llvm/ADT/StringRef.h"
Eugene Zelenkof1934002017-06-19 22:05:08 +000029#include "llvm/ADT/Twine.h"
Eugene Zelenkob1df7872017-02-17 00:00:09 +000030#include "llvm/IR/Argument.h"
31#include "llvm/IR/BasicBlock.h"
32#include "llvm/IR/Constant.h"
Chandler Carruth19d764f2014-03-04 12:24:34 +000033#include "llvm/IR/ConstantRange.h"
Eugene Zelenkob1df7872017-02-17 00:00:09 +000034#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithca8d3bf2015-02-02 18:53:21 +000035#include "llvm/IR/DebugInfoMetadata.h"
Eugene Zelenkob1df7872017-02-17 00:00:09 +000036#include "llvm/IR/DebugLoc.h"
37#include "llvm/IR/Function.h"
38#include "llvm/IR/GlobalObject.h"
39#include "llvm/IR/GlobalVariable.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000040#include "llvm/IR/Instruction.h"
41#include "llvm/IR/LLVMContext.h"
Eugene Zelenkof1934002017-06-19 22:05:08 +000042#include "llvm/IR/Metadata.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000043#include "llvm/IR/Module.h"
Eugene Zelenkob1df7872017-02-17 00:00:09 +000044#include "llvm/IR/TrackingMDRef.h"
45#include "llvm/IR/Type.h"
46#include "llvm/IR/Value.h"
Chandler Carrutheb3d76d2014-03-04 11:17:44 +000047#include "llvm/IR/ValueHandle.h"
Eugene Zelenkob1df7872017-02-17 00:00:09 +000048#include "llvm/Support/Casting.h"
49#include "llvm/Support/ErrorHandling.h"
50#include "llvm/Support/MathExtras.h"
51#include <algorithm>
52#include <cassert>
53#include <cstddef>
54#include <cstdint>
55#include <iterator>
56#include <tuple>
Eugene Zelenkof1934002017-06-19 22:05:08 +000057#include <type_traits>
Eugene Zelenkob1df7872017-02-17 00:00:09 +000058#include <utility>
59#include <vector>
Duncan P. N. Exon Smith24593ac2014-11-14 18:42:06 +000060
Devang Patel0a9f7b92009-07-28 21:49:47 +000061using namespace llvm;
62
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +000063MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
64 : Value(Ty, MetadataAsValueVal), MD(MD) {
65 track();
66}
67
68MetadataAsValue::~MetadataAsValue() {
69 getType()->getContext().pImpl->MetadataAsValues.erase(MD);
70 untrack();
71}
72
Sanjay Patel134f3302016-03-12 20:44:58 +000073/// Canonicalize metadata arguments to intrinsics.
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +000074///
75/// To support bitcode upgrades (and assembly semantic sugar) for \a
76/// MetadataAsValue, we need to canonicalize certain metadata.
77///
78/// - nullptr is replaced by an empty MDNode.
79/// - An MDNode with a single null operand is replaced by an empty MDNode.
80/// - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
81///
82/// This maintains readability of bitcode from when metadata was a type of
83/// value, and these bridges were unnecessary.
84static Metadata *canonicalizeMetadataForValue(LLVMContext &Context,
85 Metadata *MD) {
86 if (!MD)
87 // !{}
88 return MDNode::get(Context, None);
89
90 // Return early if this isn't a single-operand MDNode.
91 auto *N = dyn_cast<MDNode>(MD);
92 if (!N || N->getNumOperands() != 1)
93 return MD;
94
95 if (!N->getOperand(0))
96 // !{}
97 return MDNode::get(Context, None);
98
99 if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
100 // Look through the MDNode.
101 return C;
102
103 return MD;
104}
105
106MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
107 MD = canonicalizeMetadataForValue(Context, MD);
108 auto *&Entry = Context.pImpl->MetadataAsValues[MD];
109 if (!Entry)
110 Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
111 return Entry;
112}
113
114MetadataAsValue *MetadataAsValue::getIfExists(LLVMContext &Context,
115 Metadata *MD) {
116 MD = canonicalizeMetadataForValue(Context, MD);
117 auto &Store = Context.pImpl->MetadataAsValues;
Benjamin Kramer15307c32015-02-08 21:56:09 +0000118 return Store.lookup(MD);
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000119}
120
121void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
122 LLVMContext &Context = getContext();
123 MD = canonicalizeMetadataForValue(Context, MD);
124 auto &Store = Context.pImpl->MetadataAsValues;
125
126 // Stop tracking the old metadata.
127 Store.erase(this->MD);
128 untrack();
129 this->MD = nullptr;
130
131 // Start tracking MD, or RAUW if necessary.
132 auto *&Entry = Store[MD];
133 if (Entry) {
134 replaceAllUsesWith(Entry);
135 delete this;
136 return;
137 }
138
139 this->MD = MD;
140 track();
141 Entry = this;
142}
143
144void MetadataAsValue::track() {
145 if (MD)
146 MetadataTracking::track(&MD, *MD, *this);
147}
148
149void MetadataAsValue::untrack() {
150 if (MD)
151 MetadataTracking::untrack(MD);
152}
153
Chandler Carruth9bdbabc2015-12-29 02:14:50 +0000154bool MetadataTracking::track(void *Ref, Metadata &MD, OwnerTy Owner) {
155 assert(Ref && "Expected live reference");
156 assert((Owner || *static_cast<Metadata **>(Ref) == &MD) &&
157 "Reference without owner must be direct");
Duncan P. N. Exon Smith0568c3d2016-04-03 21:23:52 +0000158 if (auto *R = ReplaceableMetadataImpl::getOrCreate(MD)) {
Chandler Carruth9bdbabc2015-12-29 02:14:50 +0000159 R->addRef(Ref, Owner);
160 return true;
161 }
Duncan P. N. Exon Smith20c44662016-04-23 04:15:56 +0000162 if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD)) {
163 assert(!PH->Use && "Placeholders can only be used once");
164 assert(!Owner && "Unexpected callback to owner");
165 PH->Use = static_cast<Metadata **>(Ref);
166 return true;
167 }
Chandler Carruth9bdbabc2015-12-29 02:14:50 +0000168 return false;
169}
170
171void MetadataTracking::untrack(void *Ref, Metadata &MD) {
172 assert(Ref && "Expected live reference");
Duncan P. N. Exon Smith0568c3d2016-04-03 21:23:52 +0000173 if (auto *R = ReplaceableMetadataImpl::getIfExists(MD))
Chandler Carruth9bdbabc2015-12-29 02:14:50 +0000174 R->dropRef(Ref);
Duncan P. N. Exon Smith20c44662016-04-23 04:15:56 +0000175 else if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD))
176 PH->Use = nullptr;
Chandler Carruth9bdbabc2015-12-29 02:14:50 +0000177}
178
179bool MetadataTracking::retrack(void *Ref, Metadata &MD, void *New) {
180 assert(Ref && "Expected live reference");
181 assert(New && "Expected live reference");
182 assert(Ref != New && "Expected change");
Duncan P. N. Exon Smith0568c3d2016-04-03 21:23:52 +0000183 if (auto *R = ReplaceableMetadataImpl::getIfExists(MD)) {
Chandler Carruth9bdbabc2015-12-29 02:14:50 +0000184 R->moveRef(Ref, New, MD);
185 return true;
186 }
Duncan P. N. Exon Smith20c44662016-04-23 04:15:56 +0000187 assert(!isa<DistinctMDOperandPlaceholder>(MD) &&
188 "Unexpected move of an MDOperand");
Duncan P. N. Exon Smith0568c3d2016-04-03 21:23:52 +0000189 assert(!isReplaceable(MD) &&
190 "Expected un-replaceable metadata, since we didn't move a reference");
Chandler Carruth9bdbabc2015-12-29 02:14:50 +0000191 return false;
192}
193
194bool MetadataTracking::isReplaceable(const Metadata &MD) {
Duncan P. N. Exon Smith0568c3d2016-04-03 21:23:52 +0000195 return ReplaceableMetadataImpl::isReplaceable(MD);
Chandler Carruth9bdbabc2015-12-29 02:14:50 +0000196}
197
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000198void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
Duncan P. N. Exon Smith90cd6f12014-12-09 21:12:56 +0000199 bool WasInserted =
200 UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
201 .second;
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000202 (void)WasInserted;
203 assert(WasInserted && "Expected to add a reference");
Duncan P. N. Exon Smith90cd6f12014-12-09 21:12:56 +0000204
205 ++NextIndex;
206 assert(NextIndex != 0 && "Unexpected overflow");
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000207}
208
209void ReplaceableMetadataImpl::dropRef(void *Ref) {
210 bool WasErased = UseMap.erase(Ref);
211 (void)WasErased;
212 assert(WasErased && "Expected to drop a reference");
213}
214
215void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
216 const Metadata &MD) {
217 auto I = UseMap.find(Ref);
218 assert(I != UseMap.end() && "Expected to move a reference");
Duncan P. N. Exon Smith90cd6f12014-12-09 21:12:56 +0000219 auto OwnerAndIndex = I->second;
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000220 UseMap.erase(I);
Duncan P. N. Exon Smith90cd6f12014-12-09 21:12:56 +0000221 bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
222 (void)WasInserted;
223 assert(WasInserted && "Expected to add a reference");
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000224
225 // Check that the references are direct if there's no owner.
226 (void)MD;
Duncan P. N. Exon Smith90cd6f12014-12-09 21:12:56 +0000227 assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000228 "Reference without owner must be direct");
Duncan P. N. Exon Smith90cd6f12014-12-09 21:12:56 +0000229 assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000230 "Reference without owner must be direct");
231}
232
233void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000234 if (UseMap.empty())
235 return;
236
237 // Copy out uses since UseMap will get touched below.
Eugene Zelenkof1934002017-06-19 22:05:08 +0000238 using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
Duncan P. N. Exon Smith90cd6f12014-12-09 21:12:56 +0000239 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
Fangrui Song3b35e172018-09-27 02:13:45 +0000240 llvm::sort(Uses, [](const UseTy &L, const UseTy &R) {
Duncan P. N. Exon Smith90cd6f12014-12-09 21:12:56 +0000241 return L.second.second < R.second.second;
242 });
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000243 for (const auto &Pair : Uses) {
Duncan P. N. Exon Smith9e4a11f2015-01-14 19:56:10 +0000244 // Check that this Ref hasn't disappeared after RAUW (when updating a
245 // previous Ref).
246 if (!UseMap.count(Pair.first))
247 continue;
248
Duncan P. N. Exon Smith90cd6f12014-12-09 21:12:56 +0000249 OwnerTy Owner = Pair.second.first;
250 if (!Owner) {
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000251 // Update unowned tracking references directly.
252 Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
253 Ref = MD;
Duncan P. N. Exon Smith85cbe572014-12-12 19:24:33 +0000254 if (MD)
255 MetadataTracking::track(Ref);
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000256 UseMap.erase(Pair.first);
257 continue;
258 }
259
260 // Check for MetadataAsValue.
Duncan P. N. Exon Smith90cd6f12014-12-09 21:12:56 +0000261 if (Owner.is<MetadataAsValue *>()) {
262 Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000263 continue;
264 }
265
266 // There's a Metadata owner -- dispatch.
Duncan P. N. Exon Smith90cd6f12014-12-09 21:12:56 +0000267 Metadata *OwnerMD = Owner.get<Metadata *>();
268 switch (OwnerMD->getMetadataID()) {
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000269#define HANDLE_METADATA_LEAF(CLASS) \
270 case Metadata::CLASS##Kind: \
Duncan P. N. Exon Smith90cd6f12014-12-09 21:12:56 +0000271 cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000272 continue;
273#include "llvm/IR/Metadata.def"
274 default:
275 llvm_unreachable("Invalid metadata subclass");
276 }
277 }
278 assert(UseMap.empty() && "Expected all uses to be replaced");
279}
280
281void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
282 if (UseMap.empty())
283 return;
284
285 if (!ResolveUsers) {
286 UseMap.clear();
287 return;
288 }
289
290 // Copy out uses since UseMap could get touched below.
Eugene Zelenkof1934002017-06-19 22:05:08 +0000291 using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
Duncan P. N. Exon Smith90cd6f12014-12-09 21:12:56 +0000292 SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
Fangrui Song3b35e172018-09-27 02:13:45 +0000293 llvm::sort(Uses, [](const UseTy &L, const UseTy &R) {
Duncan P. N. Exon Smith90cd6f12014-12-09 21:12:56 +0000294 return L.second.second < R.second.second;
295 });
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000296 UseMap.clear();
297 for (const auto &Pair : Uses) {
Duncan P. N. Exon Smith90cd6f12014-12-09 21:12:56 +0000298 auto Owner = Pair.second.first;
299 if (!Owner)
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000300 continue;
Duncan P. N. Exon Smith90cd6f12014-12-09 21:12:56 +0000301 if (Owner.is<MetadataAsValue *>())
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000302 continue;
303
Duncan P. N. Exon Smithb0617862015-01-19 23:13:14 +0000304 // Resolve MDNodes that point at this.
305 auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
Duncan P. N. Exon Smith90cd6f12014-12-09 21:12:56 +0000306 if (!OwnerMD)
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000307 continue;
Duncan P. N. Exon Smith90cd6f12014-12-09 21:12:56 +0000308 if (OwnerMD->isResolved())
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000309 continue;
Duncan P. N. Exon Smith29129902015-01-12 19:43:15 +0000310 OwnerMD->decrementUnresolvedOperandCount();
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000311 }
312}
313
Duncan P. N. Exon Smith0568c3d2016-04-03 21:23:52 +0000314ReplaceableMetadataImpl *ReplaceableMetadataImpl::getOrCreate(Metadata &MD) {
Chandler Carruth9bdbabc2015-12-29 02:14:50 +0000315 if (auto *N = dyn_cast<MDNode>(&MD))
Duncan P. N. Exon Smith0568c3d2016-04-03 21:23:52 +0000316 return N->isResolved() ? nullptr : N->Context.getOrCreateReplaceableUses();
317 return dyn_cast<ValueAsMetadata>(&MD);
318}
319
320ReplaceableMetadataImpl *ReplaceableMetadataImpl::getIfExists(Metadata &MD) {
321 if (auto *N = dyn_cast<MDNode>(&MD))
322 return N->isResolved() ? nullptr : N->Context.getReplaceableUses();
323 return dyn_cast<ValueAsMetadata>(&MD);
324}
325
326bool ReplaceableMetadataImpl::isReplaceable(const Metadata &MD) {
327 if (auto *N = dyn_cast<MDNode>(&MD))
328 return !N->isResolved();
Chandler Carruth9bdbabc2015-12-29 02:14:50 +0000329 return dyn_cast<ValueAsMetadata>(&MD);
330}
331
Petar Jovanovicc2255792018-01-30 16:42:04 +0000332static DISubprogram *getLocalFunctionMetadata(Value *V) {
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000333 assert(V && "Expected value");
Petar Jovanovicc2255792018-01-30 16:42:04 +0000334 if (auto *A = dyn_cast<Argument>(V)) {
335 if (auto *Fn = A->getParent())
336 return Fn->getSubprogram();
337 return nullptr;
338 }
339
340 if (BasicBlock *BB = cast<Instruction>(V)->getParent()) {
341 if (auto *Fn = BB->getParent())
342 return Fn->getSubprogram();
343 return nullptr;
344 }
345
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000346 return nullptr;
347}
348
349ValueAsMetadata *ValueAsMetadata::get(Value *V) {
350 assert(V && "Unexpected null Value");
351
352 auto &Context = V->getContext();
353 auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
354 if (!Entry) {
355 assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
356 "Expected constant or function-local value");
Dehao Chen47462142016-09-16 18:27:20 +0000357 assert(!V->IsUsedByMD && "Expected this to be the only metadata use");
Owen Andersonbd84bdb2015-06-01 22:24:01 +0000358 V->IsUsedByMD = true;
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000359 if (auto *C = dyn_cast<Constant>(V))
Duncan P. N. Exon Smithd43539c2015-01-05 20:41:25 +0000360 Entry = new ConstantAsMetadata(C);
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000361 else
Duncan P. N. Exon Smithd43539c2015-01-05 20:41:25 +0000362 Entry = new LocalAsMetadata(V);
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000363 }
364
365 return Entry;
366}
367
368ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
369 assert(V && "Unexpected null Value");
370 return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
371}
372
373void ValueAsMetadata::handleDeletion(Value *V) {
374 assert(V && "Expected valid value");
375
376 auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
377 auto I = Store.find(V);
378 if (I == Store.end())
379 return;
380
381 // Remove old entry from the map.
382 ValueAsMetadata *MD = I->second;
383 assert(MD && "Expected valid metadata");
384 assert(MD->getValue() == V && "Expected valid mapping");
385 Store.erase(I);
386
387 // Delete the metadata.
388 MD->replaceAllUsesWith(nullptr);
389 delete MD;
390}
391
392void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
393 assert(From && "Expected valid value");
394 assert(To && "Expected valid value");
395 assert(From != To && "Expected changed value");
396 assert(From->getType() == To->getType() && "Unexpected type change");
397
398 LLVMContext &Context = From->getType()->getContext();
399 auto &Store = Context.pImpl->ValuesAsMetadata;
400 auto I = Store.find(From);
401 if (I == Store.end()) {
Dehao Chen47462142016-09-16 18:27:20 +0000402 assert(!From->IsUsedByMD && "Expected From not to be used by metadata");
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000403 return;
404 }
405
406 // Remove old entry from the map.
Dehao Chen47462142016-09-16 18:27:20 +0000407 assert(From->IsUsedByMD && "Expected From to be used by metadata");
Owen Andersonbd84bdb2015-06-01 22:24:01 +0000408 From->IsUsedByMD = false;
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000409 ValueAsMetadata *MD = I->second;
410 assert(MD && "Expected valid metadata");
411 assert(MD->getValue() == From && "Expected valid mapping");
412 Store.erase(I);
413
414 if (isa<LocalAsMetadata>(MD)) {
415 if (auto *C = dyn_cast<Constant>(To)) {
416 // Local became a constant.
417 MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
418 delete MD;
419 return;
420 }
Petar Jovanovicc2255792018-01-30 16:42:04 +0000421 if (getLocalFunctionMetadata(From) && getLocalFunctionMetadata(To) &&
422 getLocalFunctionMetadata(From) != getLocalFunctionMetadata(To)) {
423 // DISubprogram changed.
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000424 MD->replaceAllUsesWith(nullptr);
425 delete MD;
426 return;
427 }
428 } else if (!isa<Constant>(To)) {
429 // Changed to function-local value.
430 MD->replaceAllUsesWith(nullptr);
431 delete MD;
432 return;
433 }
434
435 auto *&Entry = Store[To];
436 if (Entry) {
437 // The target already exists.
438 MD->replaceAllUsesWith(Entry);
439 delete MD;
440 return;
441 }
442
443 // Update MD in place (and update the map entry).
Dehao Chen47462142016-09-16 18:27:20 +0000444 assert(!To->IsUsedByMD && "Expected this to be the only metadata use");
Owen Andersonbd84bdb2015-06-01 22:24:01 +0000445 To->IsUsedByMD = true;
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000446 MD->V = To;
447 Entry = MD;
448}
Duncan P. N. Exon Smithe9b30c72014-11-14 18:42:09 +0000449
Devang Patel0a9f7b92009-07-28 21:49:47 +0000450//===----------------------------------------------------------------------===//
Chris Lattnerb2a33b462009-10-19 07:10:59 +0000451// MDString implementation.
Owen Anderson647e3012009-07-31 21:35:40 +0000452//
Chris Lattner5e9cd432009-12-28 08:30:43 +0000453
Devang Patel49b63a12009-10-22 00:10:15 +0000454MDString *MDString::get(LLVMContext &Context, StringRef Str) {
Duncan P. N. Exon Smithed7bdca2014-11-14 01:17:09 +0000455 auto &Store = Context.pImpl->MDStringCache;
Benjamin Kramerb11b3522016-07-21 13:37:48 +0000456 auto I = Store.try_emplace(Str);
Mehdi Amini25656752016-03-25 05:58:04 +0000457 auto &MapEntry = I.first->getValue();
458 if (!I.second)
459 return &MapEntry;
460 MapEntry.Entry = &*I.first;
461 return &MapEntry;
Duncan P. N. Exon Smithed7bdca2014-11-14 01:17:09 +0000462}
463
464StringRef MDString::getString() const {
Duncan P. N. Exon Smith397b5752014-12-05 01:41:34 +0000465 assert(Entry && "Expected to find string map entry");
466 return Entry->first();
Owen Anderson647e3012009-07-31 21:35:40 +0000467}
468
469//===----------------------------------------------------------------------===//
Chris Lattnerb2a33b462009-10-19 07:10:59 +0000470// MDNode implementation.
Devang Patel0a9f7b92009-07-28 21:49:47 +0000471//
Chris Lattnerc5e08a92009-12-28 07:41:54 +0000472
James Y Knight4a80b4b2015-06-17 01:21:20 +0000473// Assert that the MDNode types will not be unaligned by the objects
474// prepended to them.
475#define HANDLE_MDNODE_LEAF(CLASS) \
James Y Knight4dd3b872015-06-17 13:53:12 +0000476 static_assert( \
Benjamin Kramercb58e1e2016-10-20 15:02:18 +0000477 alignof(uint64_t) >= alignof(CLASS), \
James Y Knight4dd3b872015-06-17 13:53:12 +0000478 "Alignment is insufficient after objects prepended to " #CLASS);
James Y Knight4a80b4b2015-06-17 01:21:20 +0000479#include "llvm/IR/Metadata.def"
480
Duncan P. N. Exon Smith023c72e2014-11-18 01:56:14 +0000481void *MDNode::operator new(size_t Size, unsigned NumOps) {
James Y Knight4a80b4b2015-06-17 01:21:20 +0000482 size_t OpSize = NumOps * sizeof(MDOperand);
483 // uint64_t is the most aligned type we need support (ensured by static_assert
484 // above)
Benjamin Kramercb58e1e2016-10-20 15:02:18 +0000485 OpSize = alignTo(OpSize, alignof(uint64_t));
James Y Knight4a80b4b2015-06-17 01:21:20 +0000486 void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
Duncan P. N. Exon Smithea614a52014-12-09 23:56:39 +0000487 MDOperand *O = static_cast<MDOperand *>(Ptr);
James Y Knight4a80b4b2015-06-17 01:21:20 +0000488 for (MDOperand *E = O - NumOps; O != E; --O)
489 (void)new (O - 1) MDOperand;
490 return Ptr;
Duncan P. N. Exon Smith023c72e2014-11-18 01:56:14 +0000491}
492
Naomi Musgrave950c0092015-08-31 21:06:08 +0000493void MDNode::operator delete(void *Mem) {
Duncan P. N. Exon Smith023c72e2014-11-18 01:56:14 +0000494 MDNode *N = static_cast<MDNode *>(Mem);
James Y Knight4a80b4b2015-06-17 01:21:20 +0000495 size_t OpSize = N->NumOperands * sizeof(MDOperand);
Benjamin Kramercb58e1e2016-10-20 15:02:18 +0000496 OpSize = alignTo(OpSize, alignof(uint64_t));
James Y Knight4a80b4b2015-06-17 01:21:20 +0000497
Duncan P. N. Exon Smithea614a52014-12-09 23:56:39 +0000498 MDOperand *O = static_cast<MDOperand *>(Mem);
499 for (MDOperand *E = O - N->NumOperands; O != E; --O)
500 (O - 1)->~MDOperand();
James Y Knight4a80b4b2015-06-17 01:21:20 +0000501 ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
Duncan P. N. Exon Smith023c72e2014-11-18 01:56:14 +0000502}
503
Duncan P. N. Exon Smith5f508742015-01-19 18:36:18 +0000504MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
Duncan P. N. Exon Smith0a9f9212015-01-20 00:01:43 +0000505 ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
506 : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
507 NumUnresolved(0), Context(Context) {
508 unsigned Op = 0;
509 for (Metadata *MD : Ops1)
510 setOperand(Op++, MD);
511 for (Metadata *MD : Ops2)
512 setOperand(Op++, MD);
Duncan P. N. Exon Smith641414a2015-01-19 19:02:06 +0000513
Duncan P. N. Exon Smith0568c3d2016-04-03 21:23:52 +0000514 if (!isUniqued())
Duncan P. N. Exon Smith727176d2015-01-07 22:24:46 +0000515 return;
516
Duncan P. N. Exon Smith0568c3d2016-04-03 21:23:52 +0000517 // Count the unresolved operands. If there are any, RAUW support will be
518 // added lazily on first reference.
519 countUnresolvedOperands();
Devang Patel0a9f7b92009-07-28 21:49:47 +0000520}
521
Duncan P. N. Exon Smith749d6fb2015-01-20 02:56:57 +0000522TempMDNode MDNode::clone() const {
523 switch (getMetadataID()) {
524 default:
525 llvm_unreachable("Invalid MDNode subclass");
526#define HANDLE_MDNODE_LEAF(CLASS) \
527 case CLASS##Kind: \
528 return cast<CLASS>(this)->cloneImpl();
529#include "llvm/IR/Metadata.def"
530 }
531}
532
Duncan P. N. Exon Smithb0617862015-01-19 23:13:14 +0000533static bool isOperandUnresolved(Metadata *Op) {
534 if (auto *N = dyn_cast_or_null<MDNode>(Op))
535 return !N->isResolved();
536 return false;
537}
538
Duncan P. N. Exon Smith0568c3d2016-04-03 21:23:52 +0000539void MDNode::countUnresolvedOperands() {
Duncan P. N. Exon Smith0d7ab292015-01-19 23:18:34 +0000540 assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
Duncan P. N. Exon Smith0568c3d2016-04-03 21:23:52 +0000541 assert(isUniqued() && "Expected this to be uniqued");
Sanjoy Das285b85b2016-06-10 21:18:39 +0000542 NumUnresolved = count_if(operands(), isOperandUnresolved);
Duncan P. N. Exon Smith09279972015-01-19 22:18:29 +0000543}
544
Duncan P. N. Exon Smithb0617862015-01-19 23:13:14 +0000545void MDNode::makeUniqued() {
Duncan P. N. Exon Smith37c7ccc2015-01-19 22:24:52 +0000546 assert(isTemporary() && "Expected this to be temporary");
547 assert(!isResolved() && "Expected this to be unresolved");
548
Duncan P. N. Exon Smithf067a682015-03-31 20:50:50 +0000549 // Enable uniquing callbacks.
550 for (auto &Op : mutable_operands())
551 Op.reset(Op.get(), this);
552
Duncan P. N. Exon Smith37c7ccc2015-01-19 22:24:52 +0000553 // Make this 'uniqued'.
554 Storage = Uniqued;
Duncan P. N. Exon Smith0568c3d2016-04-03 21:23:52 +0000555 countUnresolvedOperands();
556 if (!NumUnresolved) {
557 dropReplaceableUses();
558 assert(isResolved() && "Expected this to be resolved");
559 }
Duncan P. N. Exon Smith37c7ccc2015-01-19 22:24:52 +0000560
561 assert(isUniqued() && "Expected this to be uniqued");
562}
563
Duncan P. N. Exon Smithb0617862015-01-19 23:13:14 +0000564void MDNode::makeDistinct() {
Duncan P. N. Exon Smith37c7ccc2015-01-19 22:24:52 +0000565 assert(isTemporary() && "Expected this to be temporary");
566 assert(!isResolved() && "Expected this to be unresolved");
567
Duncan P. N. Exon Smith0568c3d2016-04-03 21:23:52 +0000568 // Drop RAUW support and store as a distinct node.
569 dropReplaceableUses();
Duncan P. N. Exon Smith37c7ccc2015-01-19 22:24:52 +0000570 storeDistinctInContext();
571
572 assert(isDistinct() && "Expected this to be distinct");
573 assert(isResolved() && "Expected this to be resolved");
574}
575
Duncan P. N. Exon Smithb0617862015-01-19 23:13:14 +0000576void MDNode::resolve() {
Duncan P. N. Exon Smith5cc26e02015-01-19 19:26:24 +0000577 assert(isUniqued() && "Expected this to be uniqued");
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000578 assert(!isResolved() && "Expected this to be unresolved");
579
Duncan P. N. Exon Smith0d7ab292015-01-19 23:18:34 +0000580 NumUnresolved = 0;
Duncan P. N. Exon Smith0568c3d2016-04-03 21:23:52 +0000581 dropReplaceableUses();
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000582
Duncan P. N. Exon Smith0568c3d2016-04-03 21:23:52 +0000583 assert(isResolved() && "Expected this to be resolved");
584}
585
586void MDNode::dropReplaceableUses() {
587 assert(!NumUnresolved && "Unexpected unresolved operand");
588
589 // Drop any RAUW support.
590 if (Context.hasReplaceableUses())
591 Context.takeReplaceableUses()->resolveAllUses();
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000592}
593
Duncan P. N. Exon Smithb0617862015-01-19 23:13:14 +0000594void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
Duncan P. N. Exon Smith0568c3d2016-04-03 21:23:52 +0000595 assert(isUniqued() && "Expected this to be uniqued");
Duncan P. N. Exon Smith0d7ab292015-01-19 23:18:34 +0000596 assert(NumUnresolved != 0 && "Expected unresolved operands");
Duncan P. N. Exon Smith78268072015-01-12 19:14:15 +0000597
Duncan P. N. Exon Smith6fc29012015-01-12 19:45:44 +0000598 // Check if an operand was resolved.
Duncan P. N. Exon Smith698be082015-01-13 00:46:34 +0000599 if (!isOperandUnresolved(Old)) {
600 if (isOperandUnresolved(New))
601 // An operand was un-resolved!
Duncan P. N. Exon Smith0d7ab292015-01-19 23:18:34 +0000602 ++NumUnresolved;
Duncan P. N. Exon Smith698be082015-01-13 00:46:34 +0000603 } else if (!isOperandUnresolved(New))
Duncan P. N. Exon Smith6fc29012015-01-12 19:45:44 +0000604 decrementUnresolvedOperandCount();
Duncan P. N. Exon Smith78268072015-01-12 19:14:15 +0000605}
606
Duncan P. N. Exon Smithb0617862015-01-19 23:13:14 +0000607void MDNode::decrementUnresolvedOperandCount() {
Duncan P. N. Exon Smith0568c3d2016-04-03 21:23:52 +0000608 assert(!isResolved() && "Expected this to be unresolved");
609 if (isTemporary())
610 return;
611
612 assert(isUniqued() && "Expected this to be uniqued");
613 if (--NumUnresolved)
614 return;
615
616 // Last unresolved operand has just been resolved.
617 dropReplaceableUses();
618 assert(isResolved() && "Expected this to become resolved");
Duncan P. N. Exon Smith29129902015-01-12 19:43:15 +0000619}
620
Teresa Johnson40275202016-03-29 18:24:19 +0000621void MDNode::resolveCycles() {
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000622 if (isResolved())
623 return;
624
625 // Resolve this node immediately.
626 resolve();
627
628 // Resolve all operands.
629 for (const auto &Op : operands()) {
Duncan P. N. Exon Smithb0617862015-01-19 23:13:14 +0000630 auto *N = dyn_cast_or_null<MDNode>(Op);
Duncan P. N. Exon Smith8ec0aee2015-01-19 20:36:39 +0000631 if (!N)
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000632 continue;
Duncan P. N. Exon Smith8ec0aee2015-01-19 20:36:39 +0000633
634 assert(!N->isTemporary() &&
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000635 "Expected all forward declarations to be resolved");
Duncan P. N. Exon Smith8ec0aee2015-01-19 20:36:39 +0000636 if (!N->isResolved())
637 N->resolveCycles();
Chris Lattnerb76359e2009-12-31 01:05:46 +0000638 }
Duncan P. N. Exon Smith2c38b002014-11-18 00:37:17 +0000639}
640
Duncan P. N. Exon Smith027898a2015-02-10 19:13:46 +0000641static bool hasSelfReference(MDNode *N) {
642 for (Metadata *MD : N->operands())
643 if (MD == N)
644 return true;
645 return false;
646}
647
648MDNode *MDNode::replaceWithPermanentImpl() {
Duncan P. N. Exon Smithc61bc482015-08-03 17:26:41 +0000649 switch (getMetadataID()) {
650 default:
651 // If this type isn't uniquable, replace with a distinct node.
652 return replaceWithDistinctImpl();
653
654#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
655 case CLASS##Kind: \
656 break;
657#include "llvm/IR/Metadata.def"
658 }
659
660 // Even if this type is uniquable, self-references have to be distinct.
Duncan P. N. Exon Smith027898a2015-02-10 19:13:46 +0000661 if (hasSelfReference(this))
662 return replaceWithDistinctImpl();
663 return replaceWithUniquedImpl();
664}
665
Duncan P. N. Exon Smithc062fbe2015-01-19 23:17:09 +0000666MDNode *MDNode::replaceWithUniquedImpl() {
667 // Try to uniquify in place.
668 MDNode *UniquedNode = uniquify();
Duncan P. N. Exon Smith027898a2015-02-10 19:13:46 +0000669
Duncan P. N. Exon Smithc062fbe2015-01-19 23:17:09 +0000670 if (UniquedNode == this) {
671 makeUniqued();
672 return this;
673 }
674
675 // Collision, so RAUW instead.
676 replaceAllUsesWith(UniquedNode);
677 deleteAsSubclass();
678 return UniquedNode;
679}
680
681MDNode *MDNode::replaceWithDistinctImpl() {
682 makeDistinct();
683 return this;
684}
685
Duncan P. N. Exon Smithae9e15f2015-01-12 20:09:34 +0000686void MDTuple::recalculateHash() {
Duncan P. N. Exon Smithfce53dd2015-01-19 22:53:18 +0000687 setHash(MDTupleInfo::KeyTy::calculateHash(this));
Duncan P. N. Exon Smith6205b212015-01-12 19:16:34 +0000688}
689
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000690void MDNode::dropAllReferences() {
691 for (unsigned I = 0, E = NumOperands; I != E; ++I)
692 setOperand(I, nullptr);
Duncan P. N. Exon Smith0568c3d2016-04-03 21:23:52 +0000693 if (Context.hasReplaceableUses()) {
Duncan P. N. Exon Smithb0617862015-01-19 23:13:14 +0000694 Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
695 (void)Context.takeReplaceableUses();
696 }
Chris Lattnerb76359e2009-12-31 01:05:46 +0000697}
698
Duncan P. N. Exon Smithb0617862015-01-19 23:13:14 +0000699void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000700 unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
701 assert(Op < getNumOperands() && "Expected valid operand");
702
Duncan P. N. Exon Smithe2644b62015-01-19 19:28:28 +0000703 if (!isUniqued()) {
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000704 // This node is not uniqued. Just set the operand and be done with it.
705 setOperand(Op, New);
706 return;
Duncan Sands203f7cb2010-05-04 12:43:36 +0000707 }
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000708
Duncan P. N. Exon Smith343bb3e2015-01-12 20:56:33 +0000709 // This node is uniqued.
710 eraseFromStore();
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000711
712 Metadata *Old = getOperand(Op);
713 setOperand(Op, New);
714
Duncan P. N. Exon Smith8fa25a12016-08-03 18:19:43 +0000715 // Drop uniquing for self-reference cycles and deleted constants.
716 if (New == this || (!New && Old && isa<ConstantAsMetadata>(Old))) {
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000717 if (!isResolved())
718 resolve();
Duncan P. N. Exon Smith2c22f8d2015-01-19 19:25:33 +0000719 storeDistinctInContext();
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000720 return;
721 }
722
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000723 // Re-unique the node.
Duncan P. N. Exon Smith343bb3e2015-01-12 20:56:33 +0000724 auto *Uniqued = uniquify();
725 if (Uniqued == this) {
Duncan P. N. Exon Smith78268072015-01-12 19:14:15 +0000726 if (!isResolved())
727 resolveAfterOperandChange(Old, New);
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000728 return;
729 }
730
731 // Collision.
732 if (!isResolved()) {
733 // Still unresolved, so RAUW.
Duncan P. N. Exon Smithaea8ab82015-01-12 19:36:35 +0000734 //
735 // First, clear out all operands to prevent any recursion (similar to
736 // dropAllReferences(), but we still need the use-list).
737 for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
738 setOperand(O, nullptr);
Duncan P. N. Exon Smith0568c3d2016-04-03 21:23:52 +0000739 if (Context.hasReplaceableUses())
740 Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
Duncan P. N. Exon Smith343bb3e2015-01-12 20:56:33 +0000741 deleteAsSubclass();
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000742 return;
743 }
744
Duncan P. N. Exon Smithaea8ab82015-01-12 19:36:35 +0000745 // Store in non-uniqued form if RAUW isn't possible.
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000746 storeDistinctInContext();
Victor Hernandez8fffff52010-01-20 04:45:57 +0000747}
748
Duncan P. N. Exon Smithb0617862015-01-19 23:13:14 +0000749void MDNode::deleteAsSubclass() {
Duncan P. N. Exon Smith343bb3e2015-01-12 20:56:33 +0000750 switch (getMetadataID()) {
751 default:
Duncan P. N. Exon Smithb0617862015-01-19 23:13:14 +0000752 llvm_unreachable("Invalid subclass of MDNode");
753#define HANDLE_MDNODE_LEAF(CLASS) \
Duncan P. N. Exon Smith343bb3e2015-01-12 20:56:33 +0000754 case CLASS##Kind: \
755 delete cast<CLASS>(this); \
756 break;
757#include "llvm/IR/Metadata.def"
758 }
759}
760
Duncan P. N. Exon Smithce8f1442015-01-19 22:52:07 +0000761template <class T, class InfoT>
Duncan P. N. Exon Smithce8f1442015-01-19 22:52:07 +0000762static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
763 if (T *U = getUniqued(Store, N))
764 return U;
765
766 Store.insert(N);
767 return N;
768}
769
Duncan P. N. Exon Smithc10ef2d2015-01-20 00:57:33 +0000770template <class NodeTy> struct MDNode::HasCachedHash {
Eugene Zelenkof1934002017-06-19 22:05:08 +0000771 using Yes = char[1];
772 using No = char[2];
Duncan P. N. Exon Smithc10ef2d2015-01-20 00:57:33 +0000773 template <class U, U Val> struct SFINAE {};
Duncan P. N. Exon Smithce8f1442015-01-19 22:52:07 +0000774
Duncan P. N. Exon Smithc10ef2d2015-01-20 00:57:33 +0000775 template <class U>
776 static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
777 template <class U> static No &check(...);
778
779 static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
780};
781
782MDNode *MDNode::uniquify() {
Duncan P. N. Exon Smith027898a2015-02-10 19:13:46 +0000783 assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
784
Duncan P. N. Exon Smithce8f1442015-01-19 22:52:07 +0000785 // Try to insert into uniquing store.
Duncan P. N. Exon Smith343bb3e2015-01-12 20:56:33 +0000786 switch (getMetadataID()) {
787 default:
Duncan P. N. Exon Smithc61bc482015-08-03 17:26:41 +0000788 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
789#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
Duncan P. N. Exon Smithc10ef2d2015-01-20 00:57:33 +0000790 case CLASS##Kind: { \
791 CLASS *SubclassThis = cast<CLASS>(this); \
792 std::integral_constant<bool, HasCachedHash<CLASS>::value> \
793 ShouldRecalculateHash; \
794 dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
795 return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
796 }
Duncan P. N. Exon Smith343bb3e2015-01-12 20:56:33 +0000797#include "llvm/IR/Metadata.def"
798 }
799}
800
Duncan P. N. Exon Smithb0617862015-01-19 23:13:14 +0000801void MDNode::eraseFromStore() {
Duncan P. N. Exon Smith343bb3e2015-01-12 20:56:33 +0000802 switch (getMetadataID()) {
803 default:
Duncan P. N. Exon Smithc61bc482015-08-03 17:26:41 +0000804 llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
805#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
Duncan P. N. Exon Smith343bb3e2015-01-12 20:56:33 +0000806 case CLASS##Kind: \
Duncan P. N. Exon Smith668bd8c2015-01-19 22:47:08 +0000807 getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
Duncan P. N. Exon Smith343bb3e2015-01-12 20:56:33 +0000808 break;
809#include "llvm/IR/Metadata.def"
810 }
811}
812
Duncan P. N. Exon Smithdc6a3352015-01-12 20:13:56 +0000813MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
Duncan P. N. Exon Smith518025f2015-01-19 20:14:15 +0000814 StorageType Storage, bool ShouldCreate) {
815 unsigned Hash = 0;
816 if (Storage == Uniqued) {
817 MDTupleInfo::KeyTy Key(MDs);
Duncan P. N. Exon Smith1c588db2015-01-19 20:16:50 +0000818 if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
819 return N;
Duncan P. N. Exon Smith518025f2015-01-19 20:14:15 +0000820 if (!ShouldCreate)
821 return nullptr;
Duncan P. N. Exon Smithfce53dd2015-01-19 22:53:18 +0000822 Hash = Key.getHash();
Duncan P. N. Exon Smith518025f2015-01-19 20:14:15 +0000823 } else {
824 assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
825 }
Duncan Sands4000afe2012-03-31 08:20:11 +0000826
Duncan P. N. Exon Smithe5afc652015-01-19 20:18:13 +0000827 return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
828 Storage, Context.pImpl->MDTuples);
Duncan P. N. Exon Smith727176d2015-01-07 22:24:46 +0000829}
830
Duncan P. N. Exon Smith8ec0aee2015-01-19 20:36:39 +0000831void MDNode::deleteTemporary(MDNode *N) {
832 assert(N->isTemporary() && "Expected temporary node");
Duncan P. N. Exon Smith00334612015-01-22 21:36:45 +0000833 N->replaceAllUsesWith(nullptr);
Duncan P. N. Exon Smithb0617862015-01-19 23:13:14 +0000834 N->deleteAsSubclass();
Dan Gohman489b29b2010-08-20 22:02:26 +0000835}
836
Duncan P. N. Exon Smithb0617862015-01-19 23:13:14 +0000837void MDNode::storeDistinctInContext() {
Duncan P. N. Exon Smith0568c3d2016-04-03 21:23:52 +0000838 assert(!Context.hasReplaceableUses() && "Unexpected replaceable uses");
839 assert(!NumUnresolved && "Unexpected unresolved nodes");
Duncan P. N. Exon Smith5f508742015-01-19 18:36:18 +0000840 Storage = Distinct;
Duncan P. N. Exon Smith0568c3d2016-04-03 21:23:52 +0000841 assert(isResolved() && "Expected this to be resolved");
Duncan P. N. Exon Smithc10ef2d2015-01-20 00:57:33 +0000842
843 // Reset the hash.
844 switch (getMetadataID()) {
845 default:
846 llvm_unreachable("Invalid subclass of MDNode");
847#define HANDLE_MDNODE_LEAF(CLASS) \
848 case CLASS##Kind: { \
849 std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
850 dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
851 break; \
852 }
853#include "llvm/IR/Metadata.def"
854 }
855
Duncan P. N. Exon Smith995d8632016-04-19 23:59:13 +0000856 getContext().pImpl->DistinctMDNodes.push_back(this);
Devang Patel06fdacc2010-02-18 20:53:16 +0000857}
Chris Lattnerf2410182009-12-28 09:12:35 +0000858
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000859void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
860 if (getOperand(I) == New)
Devang Patel5f4ac842009-09-03 01:39:20 +0000861 return;
Devang Patel5f4ac842009-09-03 01:39:20 +0000862
Duncan P. N. Exon Smith1d72e182015-01-19 18:45:35 +0000863 if (!isUniqued()) {
Duncan P. N. Exon Smithe5e4a9a2015-01-12 18:01:45 +0000864 setOperand(I, New);
Duncan P. N. Exon Smith66a2b052014-11-17 23:28:21 +0000865 return;
866 }
Mikhail Glushenkov0d75d872010-01-10 18:48:49 +0000867
Duncan P. N. Exon Smithb0617862015-01-19 23:13:14 +0000868 handleChangedOperand(mutable_begin() + I, New);
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000869}
Chris Lattner49642572009-12-28 09:24:53 +0000870
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000871void MDNode::setOperand(unsigned I, Metadata *New) {
872 assert(I < NumOperands);
Duncan P. N. Exon Smithe85df9e2015-01-19 19:29:25 +0000873 mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
Devang Patel5f4ac842009-09-03 01:39:20 +0000874}
875
Sanjay Patel134f3302016-03-12 20:44:58 +0000876/// Get a node or a self-reference that looks like it.
Duncan P. N. Exon Smith8ecb7e22014-12-07 20:32:11 +0000877///
878/// Special handling for finding self-references, for use by \a
879/// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
880/// when self-referencing nodes were still uniqued. If the first operand has
881/// the same operands as \c Ops, return the first operand instead.
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000882static MDNode *getOrSelfReference(LLVMContext &Context,
883 ArrayRef<Metadata *> Ops) {
Duncan P. N. Exon Smith8ecb7e22014-12-07 20:32:11 +0000884 if (!Ops.empty())
885 if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
886 if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
887 for (unsigned I = 1, E = Ops.size(); I != E; ++I)
888 if (Ops[I] != N->getOperand(I))
889 return MDNode::get(Context, Ops);
890 return N;
891 }
892
893 return MDNode::get(Context, Ops);
894}
895
Hal Finkel16fd27b2014-07-24 14:25:39 +0000896MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
897 if (!A)
898 return B;
899 if (!B)
900 return A;
901
David Majnemer9c509582016-08-16 18:48:34 +0000902 SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
903 MDs.insert(B->op_begin(), B->op_end());
Hal Finkel16fd27b2014-07-24 14:25:39 +0000904
Duncan P. N. Exon Smith8ecb7e22014-12-07 20:32:11 +0000905 // FIXME: This preserves long-standing behaviour, but is it really the right
906 // behaviour? Or was that an unintended side-effect of node uniquing?
David Majnemer9c509582016-08-16 18:48:34 +0000907 return getOrSelfReference(A->getContext(), MDs.getArrayRef());
Hal Finkel16fd27b2014-07-24 14:25:39 +0000908}
909
910MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
911 if (!A || !B)
912 return nullptr;
913
David Majnemer66280952016-08-16 18:48:37 +0000914 SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
915 SmallPtrSet<Metadata *, 4> BSet(B->op_begin(), B->op_end());
916 MDs.remove_if([&](Metadata *MD) { return !is_contained(BSet, MD); });
Hal Finkel16fd27b2014-07-24 14:25:39 +0000917
Duncan P. N. Exon Smith7280d8c2014-12-07 19:52:06 +0000918 // FIXME: This preserves long-standing behaviour, but is it really the right
919 // behaviour? Or was that an unintended side-effect of node uniquing?
David Majnemer66280952016-08-16 18:48:37 +0000920 return getOrSelfReference(A->getContext(), MDs.getArrayRef());
Hal Finkel16fd27b2014-07-24 14:25:39 +0000921}
922
Bjorn Steinbrink61a16d22015-02-08 17:07:14 +0000923MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
924 if (!A || !B)
925 return nullptr;
926
David Majnemer9c509582016-08-16 18:48:34 +0000927 return concatenate(A, B);
Bjorn Steinbrink61a16d22015-02-08 17:07:14 +0000928}
929
Hal Finkel7b4ff932012-06-16 20:33:37 +0000930MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
931 if (!A || !B)
Craig Topperec0f0bc2014-04-09 06:08:46 +0000932 return nullptr;
Hal Finkel7b4ff932012-06-16 20:33:37 +0000933
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000934 APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
935 APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
Hal Finkel7b4ff932012-06-16 20:33:37 +0000936 if (AVal.compare(BVal) == APFloat::cmpLessThan)
937 return A;
938 return B;
939}
940
941static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
942 return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
943}
944
945static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
946 return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
947}
948
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000949static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
950 ConstantInt *Low, ConstantInt *High) {
Hal Finkel7b4ff932012-06-16 20:33:37 +0000951 ConstantRange NewRange(Low->getValue(), High->getValue());
952 unsigned Size = EndPoints.size();
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000953 APInt LB = EndPoints[Size - 2]->getValue();
954 APInt LE = EndPoints[Size - 1]->getValue();
Hal Finkel7b4ff932012-06-16 20:33:37 +0000955 ConstantRange LastRange(LB, LE);
956 if (canBeMerged(NewRange, LastRange)) {
957 ConstantRange Union = LastRange.unionWith(NewRange);
958 Type *Ty = High->getType();
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000959 EndPoints[Size - 2] =
960 cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
961 EndPoints[Size - 1] =
962 cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
Hal Finkel7b4ff932012-06-16 20:33:37 +0000963 return true;
964 }
965 return false;
966}
967
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000968static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
969 ConstantInt *Low, ConstantInt *High) {
Hal Finkel7b4ff932012-06-16 20:33:37 +0000970 if (!EndPoints.empty())
971 if (tryMergeRange(EndPoints, Low, High))
972 return;
973
974 EndPoints.push_back(Low);
975 EndPoints.push_back(High);
976}
977
978MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
979 // Given two ranges, we want to compute the union of the ranges. This
Craig Toppere5cb2e52017-04-27 05:48:29 +0000980 // is slightly complicated by having to combine the intervals and merge
Hal Finkel7b4ff932012-06-16 20:33:37 +0000981 // the ones that overlap.
982
983 if (!A || !B)
Craig Topperec0f0bc2014-04-09 06:08:46 +0000984 return nullptr;
Hal Finkel7b4ff932012-06-16 20:33:37 +0000985
986 if (A == B)
987 return A;
988
Craig Toppere5cb2e52017-04-27 05:48:29 +0000989 // First, walk both lists in order of the lower boundary of each interval.
Hal Finkel7b4ff932012-06-16 20:33:37 +0000990 // At each step, try to merge the new interval to the last one we adedd.
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000991 SmallVector<ConstantInt *, 4> EndPoints;
Hal Finkel7b4ff932012-06-16 20:33:37 +0000992 int AI = 0;
993 int BI = 0;
994 int AN = A->getNumOperands() / 2;
995 int BN = B->getNumOperands() / 2;
996 while (AI < AN && BI < BN) {
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +0000997 ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
998 ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
Hal Finkel7b4ff932012-06-16 20:33:37 +0000999
1000 if (ALow->getValue().slt(BLow->getValue())) {
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00001001 addRange(EndPoints, ALow,
1002 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel7b4ff932012-06-16 20:33:37 +00001003 ++AI;
1004 } else {
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00001005 addRange(EndPoints, BLow,
1006 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel7b4ff932012-06-16 20:33:37 +00001007 ++BI;
1008 }
1009 }
1010 while (AI < AN) {
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00001011 addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
1012 mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
Hal Finkel7b4ff932012-06-16 20:33:37 +00001013 ++AI;
1014 }
1015 while (BI < BN) {
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00001016 addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
1017 mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
Hal Finkel7b4ff932012-06-16 20:33:37 +00001018 ++BI;
1019 }
1020
1021 // If we have more than 2 ranges (4 endpoints) we have to try to merge
1022 // the last and first ones.
1023 unsigned Size = EndPoints.size();
1024 if (Size > 4) {
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00001025 ConstantInt *FB = EndPoints[0];
1026 ConstantInt *FE = EndPoints[1];
Hal Finkel7b4ff932012-06-16 20:33:37 +00001027 if (tryMergeRange(EndPoints, FB, FE)) {
1028 for (unsigned i = 0; i < Size - 2; ++i) {
1029 EndPoints[i] = EndPoints[i + 2];
1030 }
1031 EndPoints.resize(Size - 2);
1032 }
1033 }
1034
1035 // If in the end we have a single range, it is possible that it is now the
1036 // full range. Just drop the metadata in that case.
1037 if (EndPoints.size() == 2) {
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00001038 ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
Hal Finkel7b4ff932012-06-16 20:33:37 +00001039 if (Range.isFullSet())
Craig Topperec0f0bc2014-04-09 06:08:46 +00001040 return nullptr;
Hal Finkel7b4ff932012-06-16 20:33:37 +00001041 }
1042
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00001043 SmallVector<Metadata *, 4> MDs;
1044 MDs.reserve(EndPoints.size());
1045 for (auto *I : EndPoints)
1046 MDs.push_back(ConstantAsMetadata::get(I));
1047 return MDNode::get(A->getContext(), MDs);
Hal Finkel7b4ff932012-06-16 20:33:37 +00001048}
1049
Artur Pilipenkobf7f89f2015-11-02 17:53:51 +00001050MDNode *MDNode::getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B) {
1051 if (!A || !B)
1052 return nullptr;
1053
1054 ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
1055 ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
1056 if (AVal->getZExtValue() < BVal->getZExtValue())
1057 return A;
1058 return B;
1059}
1060
Devang Patelf457d132009-07-29 00:33:07 +00001061//===----------------------------------------------------------------------===//
Chris Lattnerb2a33b462009-10-19 07:10:59 +00001062// NamedMDNode implementation.
Devang Patelf457d132009-07-29 00:33:07 +00001063//
Devang Patel26028f22010-01-12 18:34:06 +00001064
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00001065static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
1066 return *(SmallVector<TrackingMDRef, 4> *)Operands;
Chris Lattner57109692009-12-28 08:07:14 +00001067}
1068
Dan Gohman17aa92c2010-07-21 23:38:33 +00001069NamedMDNode::NamedMDNode(const Twine &N)
Eugene Zelenkob1df7872017-02-17 00:00:09 +00001070 : Name(N.str()), Operands(new SmallVector<TrackingMDRef, 4>()) {}
Devang Patelab67e702009-08-11 18:01:24 +00001071
Chris Lattner57109692009-12-28 08:07:14 +00001072NamedMDNode::~NamedMDNode() {
1073 dropAllReferences();
1074 delete &getNMDOps(Operands);
1075}
1076
Chris Lattner5d0cacd2009-12-31 01:22:29 +00001077unsigned NamedMDNode::getNumOperands() const {
Chris Lattner57109692009-12-28 08:07:14 +00001078 return (unsigned)getNMDOps(Operands).size();
1079}
1080
Duncan P. N. Exon Smith5bf8ade2014-11-11 21:30:22 +00001081MDNode *NamedMDNode::getOperand(unsigned i) const {
Chris Lattner5d0cacd2009-12-31 01:22:29 +00001082 assert(i < getNumOperands() && "Invalid Operand number!");
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00001083 auto *N = getNMDOps(Operands)[i].get();
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00001084 return cast_or_null<MDNode>(N);
Chris Lattner57109692009-12-28 08:07:14 +00001085}
1086
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00001087void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
Chris Lattner57109692009-12-28 08:07:14 +00001088
Duncan P. N. Exon Smithc742e3a2015-01-07 21:32:27 +00001089void NamedMDNode::setOperand(unsigned I, MDNode *New) {
1090 assert(I < getNumOperands() && "Invalid operand number");
1091 getNMDOps(Operands)[I].reset(New);
1092}
1093
Dehao Chen47462142016-09-16 18:27:20 +00001094void NamedMDNode::eraseFromParent() { getParent()->eraseNamedMetadata(this); }
Devang Patela82f8832009-08-03 06:19:01 +00001095
Michael Ilseman5bd98bf2016-10-25 18:44:13 +00001096void NamedMDNode::clearOperands() { getNMDOps(Operands).clear(); }
Devang Patela82f8832009-08-03 06:19:01 +00001097
Dehao Chen47462142016-09-16 18:27:20 +00001098StringRef NamedMDNode::getName() const { return StringRef(Name); }
Devang Patel937b1e92009-09-16 18:09:00 +00001099
1100//===----------------------------------------------------------------------===//
Chris Lattner3990b122009-12-28 23:41:32 +00001101// Instruction Metadata method implementations.
1102//
Duncan P. N. Exon Smith223d9cf2015-04-24 20:36:25 +00001103void MDAttachmentMap::set(unsigned ID, MDNode &MD) {
1104 for (auto &I : Attachments)
1105 if (I.first == ID) {
1106 I.second.reset(&MD);
1107 return;
1108 }
1109 Attachments.emplace_back(std::piecewise_construct, std::make_tuple(ID),
1110 std::make_tuple(&MD));
1111}
1112
Benjamin Kramerf4eac502018-05-31 13:29:58 +00001113bool MDAttachmentMap::erase(unsigned ID) {
Duncan P. N. Exon Smith223d9cf2015-04-24 20:36:25 +00001114 if (empty())
Benjamin Kramerf4eac502018-05-31 13:29:58 +00001115 return false;
Duncan P. N. Exon Smith223d9cf2015-04-24 20:36:25 +00001116
1117 // Common case is one/last value.
1118 if (Attachments.back().first == ID) {
1119 Attachments.pop_back();
Benjamin Kramerf4eac502018-05-31 13:29:58 +00001120 return true;
Duncan P. N. Exon Smith223d9cf2015-04-24 20:36:25 +00001121 }
1122
1123 for (auto I = Attachments.begin(), E = std::prev(Attachments.end()); I != E;
1124 ++I)
1125 if (I->first == ID) {
1126 *I = std::move(Attachments.back());
1127 Attachments.pop_back();
Benjamin Kramerf4eac502018-05-31 13:29:58 +00001128 return true;
Duncan P. N. Exon Smith223d9cf2015-04-24 20:36:25 +00001129 }
Benjamin Kramerf4eac502018-05-31 13:29:58 +00001130
1131 return false;
Duncan P. N. Exon Smith223d9cf2015-04-24 20:36:25 +00001132}
1133
1134MDNode *MDAttachmentMap::lookup(unsigned ID) const {
1135 for (const auto &I : Attachments)
1136 if (I.first == ID)
1137 return I.second;
1138 return nullptr;
1139}
1140
1141void MDAttachmentMap::getAll(
1142 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
1143 Result.append(Attachments.begin(), Attachments.end());
1144
1145 // Sort the resulting array so it is stable.
1146 if (Result.size() > 1)
1147 array_pod_sort(Result.begin(), Result.end());
1148}
Chris Lattner3990b122009-12-28 23:41:32 +00001149
Peter Collingbourned8d85ac2016-06-01 01:17:57 +00001150void MDGlobalAttachmentMap::insert(unsigned ID, MDNode &MD) {
1151 Attachments.push_back({ID, TrackingMDNodeRef(&MD)});
1152}
1153
Benjamin Kramerf4eac502018-05-31 13:29:58 +00001154MDNode *MDGlobalAttachmentMap::lookup(unsigned ID) const {
1155 for (const auto &A : Attachments)
1156 if (A.MDKind == ID)
1157 return A.Node;
1158 return nullptr;
1159}
1160
Peter Collingbourned8d85ac2016-06-01 01:17:57 +00001161void MDGlobalAttachmentMap::get(unsigned ID,
Benjamin Kramerf4eac502018-05-31 13:29:58 +00001162 SmallVectorImpl<MDNode *> &Result) const {
1163 for (const auto &A : Attachments)
Peter Collingbourned8d85ac2016-06-01 01:17:57 +00001164 if (A.MDKind == ID)
1165 Result.push_back(A.Node);
1166}
1167
Benjamin Kramerf4eac502018-05-31 13:29:58 +00001168bool MDGlobalAttachmentMap::erase(unsigned ID) {
1169 auto I = std::remove_if(Attachments.begin(), Attachments.end(),
1170 [ID](const Attachment &A) { return A.MDKind == ID; });
1171 bool Changed = I != Attachments.end();
1172 Attachments.erase(I, Attachments.end());
1173 return Changed;
Peter Collingbourned8d85ac2016-06-01 01:17:57 +00001174}
1175
1176void MDGlobalAttachmentMap::getAll(
1177 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Benjamin Kramerf4eac502018-05-31 13:29:58 +00001178 for (const auto &A : Attachments)
Peter Collingbourned8d85ac2016-06-01 01:17:57 +00001179 Result.emplace_back(A.MDKind, A.Node);
1180
1181 // Sort the resulting array so it is stable with respect to metadata IDs. We
1182 // need to preserve the original insertion order though.
1183 std::stable_sort(
1184 Result.begin(), Result.end(),
1185 [](const std::pair<unsigned, MDNode *> &A,
1186 const std::pair<unsigned, MDNode *> &B) { return A.first < B.first; });
1187}
1188
Duncan P. N. Exon Smith5bf8ade2014-11-11 21:30:22 +00001189void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
1190 if (!Node && !hasMetadata())
1191 return;
1192 setMetadata(getContext().getMDKindID(Kind), Node);
Chris Lattner3990b122009-12-28 23:41:32 +00001193}
1194
Duncan P. N. Exon Smith5bf8ade2014-11-11 21:30:22 +00001195MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
Chris Lattner08113472009-12-29 09:01:33 +00001196 return getMetadataImpl(getContext().getMDKindID(Kind));
Chris Lattner3990b122009-12-28 23:41:32 +00001197}
1198
Adrian Prantl178fbb32015-08-20 22:00:30 +00001199void Instruction::dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs) {
Rafael Espindolaf611ae42014-01-28 16:56:46 +00001200 if (!hasMetadataHashEntry())
1201 return; // Nothing to remove!
1202
Duncan P. N. Exon Smithd8c574a2015-04-24 20:19:13 +00001203 auto &InstructionMetadata = getContext().pImpl->InstructionMetadata;
Rafael Espindolaf611ae42014-01-28 16:56:46 +00001204
Aditya Kumar077587912016-09-26 21:01:13 +00001205 SmallSet<unsigned, 4> KnownSet;
1206 KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
Rafael Espindolaf611ae42014-01-28 16:56:46 +00001207 if (KnownSet.empty()) {
1208 // Just drop our entry at the store.
Duncan P. N. Exon Smith4eae7e02015-04-24 20:16:42 +00001209 InstructionMetadata.erase(this);
Rafael Espindolaf611ae42014-01-28 16:56:46 +00001210 setHasMetadataHashEntry(false);
1211 return;
1212 }
1213
Duncan P. N. Exon Smithd8c574a2015-04-24 20:19:13 +00001214 auto &Info = InstructionMetadata[this];
Duncan P. N. Exon Smith223d9cf2015-04-24 20:36:25 +00001215 Info.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
1216 return !KnownSet.count(I.first);
1217 });
Rafael Espindolaf611ae42014-01-28 16:56:46 +00001218
Duncan P. N. Exon Smith9cd7a4b2015-04-24 20:23:44 +00001219 if (Info.empty()) {
Rafael Espindolaf611ae42014-01-28 16:56:46 +00001220 // Drop our entry at the store.
Duncan P. N. Exon Smith4eae7e02015-04-24 20:16:42 +00001221 InstructionMetadata.erase(this);
Rafael Espindolaf611ae42014-01-28 16:56:46 +00001222 setHasMetadataHashEntry(false);
1223 }
1224}
1225
Duncan P. N. Exon Smith5bf8ade2014-11-11 21:30:22 +00001226void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
1227 if (!Node && !hasMetadata())
1228 return;
Mikhail Glushenkov0d75d872010-01-10 18:48:49 +00001229
Chris Lattnerec39f092010-03-30 23:03:27 +00001230 // Handle 'dbg' as a special case since it is not stored in the hash table.
1231 if (KindID == LLVMContext::MD_dbg) {
Duncan P. N. Exon Smith39acf8f2015-03-30 19:40:05 +00001232 DbgLoc = DebugLoc(Node);
Chris Lattnerec39f092010-03-30 23:03:27 +00001233 return;
1234 }
Dehao Chen47462142016-09-16 18:27:20 +00001235
Chris Lattner08113472009-12-29 09:01:33 +00001236 // Handle the case when we're adding/updating metadata on an instruction.
1237 if (Node) {
Duncan P. N. Exon Smithd8c574a2015-04-24 20:19:13 +00001238 auto &Info = getContext().pImpl->InstructionMetadata[this];
Chris Lattnerec39f092010-03-30 23:03:27 +00001239 assert(!Info.empty() == hasMetadataHashEntry() &&
1240 "HasMetadata bit is wonked");
Duncan P. N. Exon Smith223d9cf2015-04-24 20:36:25 +00001241 if (Info.empty())
Chris Lattnerec39f092010-03-30 23:03:27 +00001242 setHasMetadataHashEntry(true);
Duncan P. N. Exon Smith223d9cf2015-04-24 20:36:25 +00001243 Info.set(KindID, *Node);
Chris Lattner08113472009-12-29 09:01:33 +00001244 return;
1245 }
Mikhail Glushenkov0d75d872010-01-10 18:48:49 +00001246
Chris Lattner08113472009-12-29 09:01:33 +00001247 // Otherwise, we're removing metadata from an instruction.
Nick Lewyckyda32cc62011-12-27 01:17:40 +00001248 assert((hasMetadataHashEntry() ==
Duncan P. N. Exon Smith4eae7e02015-04-24 20:16:42 +00001249 (getContext().pImpl->InstructionMetadata.count(this) > 0)) &&
Chris Lattner08113472009-12-29 09:01:33 +00001250 "HasMetadata bit out of date!");
Nick Lewyckyda32cc62011-12-27 01:17:40 +00001251 if (!hasMetadataHashEntry())
Dehao Chen47462142016-09-16 18:27:20 +00001252 return; // Nothing to remove!
Duncan P. N. Exon Smithd8c574a2015-04-24 20:19:13 +00001253 auto &Info = getContext().pImpl->InstructionMetadata[this];
Mikhail Glushenkov0d75d872010-01-10 18:48:49 +00001254
Chris Lattnerec39f092010-03-30 23:03:27 +00001255 // Handle removal of an existing value.
Duncan P. N. Exon Smith223d9cf2015-04-24 20:36:25 +00001256 Info.erase(KindID);
1257
1258 if (!Info.empty())
1259 return;
1260
1261 getContext().pImpl->InstructionMetadata.erase(this);
1262 setHasMetadataHashEntry(false);
Chris Lattner3990b122009-12-28 23:41:32 +00001263}
1264
Hal Finkel2c7c54c2014-07-24 12:16:19 +00001265void Instruction::setAAMetadata(const AAMDNodes &N) {
1266 setMetadata(LLVMContext::MD_tbaa, N.TBAA);
Hal Finkel16fd27b2014-07-24 14:25:39 +00001267 setMetadata(LLVMContext::MD_alias_scope, N.Scope);
1268 setMetadata(LLVMContext::MD_noalias, N.NoAlias);
Hal Finkel2c7c54c2014-07-24 12:16:19 +00001269}
1270
Duncan P. N. Exon Smith5bf8ade2014-11-11 21:30:22 +00001271MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
Chris Lattnerec39f092010-03-30 23:03:27 +00001272 // Handle 'dbg' as a special case since it is not stored in the hash table.
1273 if (KindID == LLVMContext::MD_dbg)
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00001274 return DbgLoc.getAsMDNode();
1275
Duncan P. N. Exon Smith223d9cf2015-04-24 20:36:25 +00001276 if (!hasMetadataHashEntry())
1277 return nullptr;
Duncan P. N. Exon Smithd8c574a2015-04-24 20:19:13 +00001278 auto &Info = getContext().pImpl->InstructionMetadata[this];
Chris Lattnerec39f092010-03-30 23:03:27 +00001279 assert(!Info.empty() && "bit out of sync with hash table");
Mikhail Glushenkov0d75d872010-01-10 18:48:49 +00001280
Duncan P. N. Exon Smith223d9cf2015-04-24 20:36:25 +00001281 return Info.lookup(KindID);
Chris Lattner3990b122009-12-28 23:41:32 +00001282}
1283
Duncan P. N. Exon Smithb2187ed2014-11-01 00:26:42 +00001284void Instruction::getAllMetadataImpl(
Duncan P. N. Exon Smith5bf8ade2014-11-11 21:30:22 +00001285 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattnerec39f092010-03-30 23:03:27 +00001286 Result.clear();
Dehao Chen47462142016-09-16 18:27:20 +00001287
Chris Lattnerec39f092010-03-30 23:03:27 +00001288 // Handle 'dbg' as a special case since it is not stored in the hash table.
Duncan P. N. Exon Smith39acf8f2015-03-30 19:40:05 +00001289 if (DbgLoc) {
Duncan P. N. Exon Smithdad20b22014-12-09 18:38:53 +00001290 Result.push_back(
1291 std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
Dehao Chen47462142016-09-16 18:27:20 +00001292 if (!hasMetadataHashEntry())
1293 return;
Chris Lattnerec39f092010-03-30 23:03:27 +00001294 }
Duncan P. N. Exon Smith4eae7e02015-04-24 20:16:42 +00001295
Chris Lattnerec39f092010-03-30 23:03:27 +00001296 assert(hasMetadataHashEntry() &&
Duncan P. N. Exon Smith4eae7e02015-04-24 20:16:42 +00001297 getContext().pImpl->InstructionMetadata.count(this) &&
Chris Lattner08113472009-12-29 09:01:33 +00001298 "Shouldn't have called this");
Duncan P. N. Exon Smithd8c574a2015-04-24 20:19:13 +00001299 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
Chris Lattner08113472009-12-29 09:01:33 +00001300 assert(!Info.empty() && "Shouldn't have called this");
Duncan P. N. Exon Smith223d9cf2015-04-24 20:36:25 +00001301 Info.getAll(Result);
Chris Lattner3990b122009-12-28 23:41:32 +00001302}
1303
Duncan P. N. Exon Smith5e847602014-11-03 18:13:57 +00001304void Instruction::getAllMetadataOtherThanDebugLocImpl(
Duncan P. N. Exon Smith5bf8ade2014-11-11 21:30:22 +00001305 SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
Chris Lattner61336ae2010-04-01 05:23:13 +00001306 Result.clear();
1307 assert(hasMetadataHashEntry() &&
Duncan P. N. Exon Smith4eae7e02015-04-24 20:16:42 +00001308 getContext().pImpl->InstructionMetadata.count(this) &&
Chris Lattner61336ae2010-04-01 05:23:13 +00001309 "Shouldn't have called this");
Duncan P. N. Exon Smithd8c574a2015-04-24 20:19:13 +00001310 const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
Chris Lattner61336ae2010-04-01 05:23:13 +00001311 assert(!Info.empty() && "Shouldn't have called this");
Duncan P. N. Exon Smith223d9cf2015-04-24 20:36:25 +00001312 Info.getAll(Result);
Chris Lattner61336ae2010-04-01 05:23:13 +00001313}
1314
Dehao Chen47462142016-09-16 18:27:20 +00001315bool Instruction::extractProfMetadata(uint64_t &TrueVal,
1316 uint64_t &FalseVal) const {
1317 assert(
1318 (getOpcode() == Instruction::Br || getOpcode() == Instruction::Select) &&
1319 "Looking for branch weights on something besides branch or select");
Sanjay Patel6f5aa792016-04-26 17:11:17 +00001320
1321 auto *ProfileData = getMetadata(LLVMContext::MD_prof);
1322 if (!ProfileData || ProfileData->getNumOperands() != 3)
1323 return false;
1324
1325 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
1326 if (!ProfDataName || !ProfDataName->getString().equals("branch_weights"))
1327 return false;
1328
1329 auto *CITrue = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
1330 auto *CIFalse = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
1331 if (!CITrue || !CIFalse)
1332 return false;
1333
1334 TrueVal = CITrue->getValue().getZExtValue();
1335 FalseVal = CIFalse->getValue().getZExtValue();
1336
1337 return true;
1338}
1339
Dehao Chen47462142016-09-16 18:27:20 +00001340bool Instruction::extractProfTotalWeight(uint64_t &TotalVal) const {
Dehao Chenbc3b9e52016-07-11 16:48:54 +00001341 assert((getOpcode() == Instruction::Br ||
1342 getOpcode() == Instruction::Select ||
Dehao Chen1c6f7ab2016-07-11 17:36:02 +00001343 getOpcode() == Instruction::Call ||
Dehao Chen1d2f9bc2016-10-11 18:53:00 +00001344 getOpcode() == Instruction::Invoke ||
1345 getOpcode() == Instruction::Switch) &&
Dehao Chenbc3b9e52016-07-11 16:48:54 +00001346 "Looking for branch weights on something besides branch");
1347
1348 TotalVal = 0;
1349 auto *ProfileData = getMetadata(LLVMContext::MD_prof);
1350 if (!ProfileData)
1351 return false;
1352
1353 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
Dehao Chen22478be2017-03-31 15:59:52 +00001354 if (!ProfDataName)
Dehao Chenbc3b9e52016-07-11 16:48:54 +00001355 return false;
1356
Dehao Chen22478be2017-03-31 15:59:52 +00001357 if (ProfDataName->getString().equals("branch_weights")) {
1358 TotalVal = 0;
1359 for (unsigned i = 1; i < ProfileData->getNumOperands(); i++) {
1360 auto *V = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i));
1361 if (!V)
1362 return false;
1363 TotalVal += V->getValue().getZExtValue();
1364 }
1365 return true;
1366 } else if (ProfDataName->getString().equals("VP") &&
1367 ProfileData->getNumOperands() > 3) {
1368 TotalVal = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2))
1369 ->getValue()
1370 .getZExtValue();
1371 return true;
Dehao Chenbc3b9e52016-07-11 16:48:54 +00001372 }
Dehao Chen22478be2017-03-31 15:59:52 +00001373 return false;
Dehao Chenbc3b9e52016-07-11 16:48:54 +00001374}
1375
Dan Gohman4f1be4a2010-07-20 22:25:04 +00001376void Instruction::clearMetadataHashEntries() {
1377 assert(hasMetadataHashEntry() && "Caller should check");
Duncan P. N. Exon Smith4eae7e02015-04-24 20:16:42 +00001378 getContext().pImpl->InstructionMetadata.erase(this);
Dan Gohman4f1be4a2010-07-20 22:25:04 +00001379 setHasMetadataHashEntry(false);
Chris Lattner508b19a2009-12-29 07:44:16 +00001380}
Duncan P. N. Exon Smitheb79bb62015-04-24 21:51:02 +00001381
Peter Collingbourned8d85ac2016-06-01 01:17:57 +00001382void GlobalObject::getMetadata(unsigned KindID,
1383 SmallVectorImpl<MDNode *> &MDs) const {
1384 if (hasMetadata())
1385 getContext().pImpl->GlobalObjectMetadata[this].get(KindID, MDs);
Duncan P. N. Exon Smitheb79bb62015-04-24 21:51:02 +00001386}
1387
Peter Collingbourned8d85ac2016-06-01 01:17:57 +00001388void GlobalObject::getMetadata(StringRef Kind,
1389 SmallVectorImpl<MDNode *> &MDs) const {
1390 if (hasMetadata())
1391 getMetadata(getContext().getMDKindID(Kind), MDs);
Duncan P. N. Exon Smitheb79bb62015-04-24 21:51:02 +00001392}
1393
Peter Collingbourned8d85ac2016-06-01 01:17:57 +00001394void GlobalObject::addMetadata(unsigned KindID, MDNode &MD) {
1395 if (!hasMetadata())
1396 setHasMetadataHashEntry(true);
Duncan P. N. Exon Smitheb79bb62015-04-24 21:51:02 +00001397
Peter Collingbourned8d85ac2016-06-01 01:17:57 +00001398 getContext().pImpl->GlobalObjectMetadata[this].insert(KindID, MD);
1399}
Duncan P. N. Exon Smitheb79bb62015-04-24 21:51:02 +00001400
Peter Collingbourned8d85ac2016-06-01 01:17:57 +00001401void GlobalObject::addMetadata(StringRef Kind, MDNode &MD) {
1402 addMetadata(getContext().getMDKindID(Kind), MD);
1403}
1404
Benjamin Kramerf4eac502018-05-31 13:29:58 +00001405bool GlobalObject::eraseMetadata(unsigned KindID) {
Duncan P. N. Exon Smitheb79bb62015-04-24 21:51:02 +00001406 // Nothing to unset.
1407 if (!hasMetadata())
Benjamin Kramerf4eac502018-05-31 13:29:58 +00001408 return false;
Duncan P. N. Exon Smitheb79bb62015-04-24 21:51:02 +00001409
Peter Collingbourne6aef9f92016-05-31 23:01:54 +00001410 auto &Store = getContext().pImpl->GlobalObjectMetadata[this];
Benjamin Kramerf4eac502018-05-31 13:29:58 +00001411 bool Changed = Store.erase(KindID);
Duncan P. N. Exon Smitheb79bb62015-04-24 21:51:02 +00001412 if (Store.empty())
1413 clearMetadata();
Benjamin Kramerf4eac502018-05-31 13:29:58 +00001414 return Changed;
Duncan P. N. Exon Smitheb79bb62015-04-24 21:51:02 +00001415}
1416
Peter Collingbourne6aef9f92016-05-31 23:01:54 +00001417void GlobalObject::getAllMetadata(
Duncan P. N. Exon Smitheb79bb62015-04-24 21:51:02 +00001418 SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
1419 MDs.clear();
1420
1421 if (!hasMetadata())
1422 return;
1423
Peter Collingbourne6aef9f92016-05-31 23:01:54 +00001424 getContext().pImpl->GlobalObjectMetadata[this].getAll(MDs);
Duncan P. N. Exon Smitheb79bb62015-04-24 21:51:02 +00001425}
1426
Peter Collingbourne6aef9f92016-05-31 23:01:54 +00001427void GlobalObject::clearMetadata() {
Duncan P. N. Exon Smitheb79bb62015-04-24 21:51:02 +00001428 if (!hasMetadata())
1429 return;
Peter Collingbourne6aef9f92016-05-31 23:01:54 +00001430 getContext().pImpl->GlobalObjectMetadata.erase(this);
Duncan P. N. Exon Smitheb79bb62015-04-24 21:51:02 +00001431 setHasMetadataHashEntry(false);
1432}
Duncan P. N. Exon Smith819d0a52015-08-28 21:55:35 +00001433
Peter Collingbourned8d85ac2016-06-01 01:17:57 +00001434void GlobalObject::setMetadata(unsigned KindID, MDNode *N) {
1435 eraseMetadata(KindID);
1436 if (N)
1437 addMetadata(KindID, *N);
1438}
1439
1440void GlobalObject::setMetadata(StringRef Kind, MDNode *N) {
1441 setMetadata(getContext().getMDKindID(Kind), N);
1442}
1443
1444MDNode *GlobalObject::getMetadata(unsigned KindID) const {
Benjamin Kramerf4eac502018-05-31 13:29:58 +00001445 if (hasMetadata())
1446 return getContext().pImpl->GlobalObjectMetadata[this].lookup(KindID);
1447 return nullptr;
Peter Collingbourned8d85ac2016-06-01 01:17:57 +00001448}
1449
1450MDNode *GlobalObject::getMetadata(StringRef Kind) const {
1451 return getMetadata(getContext().getMDKindID(Kind));
1452}
1453
Peter Collingbournedba91462016-06-24 21:21:32 +00001454void GlobalObject::copyMetadata(const GlobalObject *Other, unsigned Offset) {
Peter Collingbourne43c51392016-06-24 17:42:21 +00001455 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1456 Other->getAllMetadata(MDs);
Peter Collingbournedba91462016-06-24 21:21:32 +00001457 for (auto &MD : MDs) {
1458 // We need to adjust the type metadata offset.
1459 if (Offset != 0 && MD.first == LLVMContext::MD_type) {
1460 auto *OffsetConst = cast<ConstantInt>(
1461 cast<ConstantAsMetadata>(MD.second->getOperand(0))->getValue());
1462 Metadata *TypeId = MD.second->getOperand(1);
1463 auto *NewOffsetMD = ConstantAsMetadata::get(ConstantInt::get(
1464 OffsetConst->getType(), OffsetConst->getValue() + Offset));
1465 addMetadata(LLVMContext::MD_type,
1466 *MDNode::get(getContext(), {NewOffsetMD, TypeId}));
1467 continue;
1468 }
Peter Collingbourne5420de32016-09-13 01:12:59 +00001469 // If an offset adjustment was specified we need to modify the DIExpression
1470 // to prepend the adjustment:
1471 // !DIExpression(DW_OP_plus, Offset, [original expr])
Adrian Prantl7b500b42016-12-20 02:09:43 +00001472 auto *Attachment = MD.second;
Peter Collingbourne5420de32016-09-13 01:12:59 +00001473 if (Offset != 0 && MD.first == LLVMContext::MD_dbg) {
Adrian Prantl7b500b42016-12-20 02:09:43 +00001474 DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(Attachment);
1475 DIExpression *E = nullptr;
1476 if (!GV) {
1477 auto *GVE = cast<DIGlobalVariableExpression>(Attachment);
1478 GV = GVE->getVariable();
1479 E = GVE->getExpression();
1480 }
Peter Collingbourne5420de32016-09-13 01:12:59 +00001481 ArrayRef<uint64_t> OrigElements;
1482 if (E)
1483 OrigElements = E->getElements();
1484 std::vector<uint64_t> Elements(OrigElements.size() + 2);
Florian Hahn50963b32017-06-14 13:14:38 +00001485 Elements[0] = dwarf::DW_OP_plus_uconst;
Peter Collingbourne5420de32016-09-13 01:12:59 +00001486 Elements[1] = Offset;
Fangrui Song53a62242018-11-17 01:44:25 +00001487 llvm::copy(OrigElements, Elements.begin() + 2);
Adrian Prantl7b500b42016-12-20 02:09:43 +00001488 E = DIExpression::get(getContext(), Elements);
1489 Attachment = DIGlobalVariableExpression::get(getContext(), GV, E);
Peter Collingbourne5420de32016-09-13 01:12:59 +00001490 }
Adrian Prantl7b500b42016-12-20 02:09:43 +00001491 addMetadata(MD.first, *Attachment);
Peter Collingbournedba91462016-06-24 21:21:32 +00001492 }
1493}
1494
1495void GlobalObject::addTypeMetadata(unsigned Offset, Metadata *TypeID) {
1496 addMetadata(
1497 LLVMContext::MD_type,
1498 *MDTuple::get(getContext(),
Eugene Zelenkof1934002017-06-19 22:05:08 +00001499 {ConstantAsMetadata::get(ConstantInt::get(
Peter Collingbournedba91462016-06-24 21:21:32 +00001500 Type::getInt64Ty(getContext()), Offset)),
1501 TypeID}));
Peter Collingbourne43c51392016-06-24 17:42:21 +00001502}
1503
Duncan P. N. Exon Smith819d0a52015-08-28 21:55:35 +00001504void Function::setSubprogram(DISubprogram *SP) {
1505 setMetadata(LLVMContext::MD_dbg, SP);
1506}
1507
1508DISubprogram *Function::getSubprogram() const {
1509 return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));
1510}
Peter Collingbourne5420de32016-09-13 01:12:59 +00001511
Dehao Chend0b28d92017-02-10 21:09:07 +00001512bool Function::isDebugInfoForProfiling() const {
1513 if (DISubprogram *SP = getSubprogram()) {
1514 if (DICompileUnit *CU = SP->getUnit()) {
1515 return CU->getDebugInfoForProfiling();
1516 }
1517 }
1518 return false;
1519}
1520
Adrian Prantl7b500b42016-12-20 02:09:43 +00001521void GlobalVariable::addDebugInfo(DIGlobalVariableExpression *GV) {
Peter Collingbourne5420de32016-09-13 01:12:59 +00001522 addMetadata(LLVMContext::MD_dbg, *GV);
1523}
1524
1525void GlobalVariable::getDebugInfo(
Adrian Prantl7b500b42016-12-20 02:09:43 +00001526 SmallVectorImpl<DIGlobalVariableExpression *> &GVs) const {
Peter Collingbourne5420de32016-09-13 01:12:59 +00001527 SmallVector<MDNode *, 1> MDs;
1528 getMetadata(LLVMContext::MD_dbg, MDs);
1529 for (MDNode *MD : MDs)
Adrian Prantl7b500b42016-12-20 02:09:43 +00001530 GVs.push_back(cast<DIGlobalVariableExpression>(MD));
Peter Collingbourne5420de32016-09-13 01:12:59 +00001531}