Metadata.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  1. //===- Metadata.cpp - Implement Metadata classes --------------------------===//
  2. //
  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. #include "llvm/IR/Metadata.h"
  14. #include "LLVMContextImpl.h"
  15. #include "MetadataImpl.h"
  16. #include "SymbolTableListTraitsImpl.h"
  17. #include "llvm/ADT/DenseMap.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/ADT/SmallSet.h"
  20. #include "llvm/ADT/SmallString.h"
  21. #include "llvm/ADT/StringMap.h"
  22. #include "llvm/IR/ConstantRange.h"
  23. #include "llvm/IR/DebugInfoMetadata.h"
  24. #include "llvm/IR/Instruction.h"
  25. #include "llvm/IR/LLVMContext.h"
  26. #include "llvm/IR/Module.h"
  27. #include "llvm/IR/ValueHandle.h"
  28. using namespace llvm;
  29. MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
  30. : Value(Ty, MetadataAsValueVal), MD(MD) {
  31. track();
  32. }
  33. MetadataAsValue::~MetadataAsValue() {
  34. getType()->getContext().pImpl->MetadataAsValues.erase(MD);
  35. untrack();
  36. }
  37. /// \brief Canonicalize metadata arguments to intrinsics.
  38. ///
  39. /// To support bitcode upgrades (and assembly semantic sugar) for \a
  40. /// MetadataAsValue, we need to canonicalize certain metadata.
  41. ///
  42. /// - nullptr is replaced by an empty MDNode.
  43. /// - An MDNode with a single null operand is replaced by an empty MDNode.
  44. /// - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
  45. ///
  46. /// This maintains readability of bitcode from when metadata was a type of
  47. /// value, and these bridges were unnecessary.
  48. static Metadata *canonicalizeMetadataForValue(LLVMContext &Context,
  49. Metadata *MD) {
  50. if (!MD)
  51. // !{}
  52. return MDNode::get(Context, None);
  53. // Return early if this isn't a single-operand MDNode.
  54. auto *N = dyn_cast<MDNode>(MD);
  55. if (!N || N->getNumOperands() != 1)
  56. return MD;
  57. if (!N->getOperand(0))
  58. // !{}
  59. return MDNode::get(Context, None);
  60. if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
  61. // Look through the MDNode.
  62. return C;
  63. return MD;
  64. }
  65. MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
  66. MD = canonicalizeMetadataForValue(Context, MD);
  67. auto *&Entry = Context.pImpl->MetadataAsValues[MD];
  68. if (!Entry)
  69. Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
  70. return Entry;
  71. }
  72. MetadataAsValue *MetadataAsValue::getIfExists(LLVMContext &Context,
  73. Metadata *MD) {
  74. MD = canonicalizeMetadataForValue(Context, MD);
  75. auto &Store = Context.pImpl->MetadataAsValues;
  76. return Store.lookup(MD);
  77. }
  78. void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
  79. LLVMContext &Context = getContext();
  80. MD = canonicalizeMetadataForValue(Context, MD);
  81. auto &Store = Context.pImpl->MetadataAsValues;
  82. // Stop tracking the old metadata.
  83. Store.erase(this->MD);
  84. untrack();
  85. this->MD = nullptr;
  86. // Start tracking MD, or RAUW if necessary.
  87. auto *&Entry = Store[MD];
  88. if (Entry) {
  89. replaceAllUsesWith(Entry);
  90. delete this;
  91. return;
  92. }
  93. this->MD = MD;
  94. track();
  95. Entry = this;
  96. }
  97. void MetadataAsValue::track() {
  98. if (MD)
  99. MetadataTracking::track(&MD, *MD, *this);
  100. }
  101. void MetadataAsValue::untrack() {
  102. if (MD)
  103. MetadataTracking::untrack(MD);
  104. }
  105. void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
  106. bool WasInserted =
  107. UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
  108. .second;
  109. (void)WasInserted;
  110. assert(WasInserted && "Expected to add a reference");
  111. ++NextIndex;
  112. assert(NextIndex != 0 && "Unexpected overflow");
  113. }
  114. void ReplaceableMetadataImpl::dropRef(void *Ref) {
  115. bool WasErased = UseMap.erase(Ref);
  116. (void)WasErased;
  117. // assert(WasErased && "Expected to drop a reference"); // HLSL Change - not while cleaning up OOM
  118. }
  119. void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
  120. const Metadata &MD) {
  121. auto I = UseMap.find(Ref);
  122. assert(I != UseMap.end() && "Expected to move a reference");
  123. auto OwnerAndIndex = I->second;
  124. UseMap.erase(I);
  125. bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
  126. (void)WasInserted;
  127. assert(WasInserted && "Expected to add a reference");
  128. // Check that the references are direct if there's no owner.
  129. (void)MD;
  130. assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
  131. "Reference without owner must be direct");
  132. assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
  133. "Reference without owner must be direct");
  134. }
  135. void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
  136. assert(!(MD && isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary()) &&
  137. "Expected non-temp node");
  138. if (UseMap.empty())
  139. return;
  140. // Copy out uses since UseMap will get touched below.
  141. typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
  142. SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
  143. std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
  144. return L.second.second < R.second.second;
  145. });
  146. for (const auto &Pair : Uses) {
  147. // Check that this Ref hasn't disappeared after RAUW (when updating a
  148. // previous Ref).
  149. if (!UseMap.count(Pair.first))
  150. continue;
  151. OwnerTy Owner = Pair.second.first;
  152. if (!Owner) {
  153. // Update unowned tracking references directly.
  154. Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
  155. Ref = MD;
  156. if (MD)
  157. MetadataTracking::track(Ref);
  158. UseMap.erase(Pair.first);
  159. continue;
  160. }
  161. // Check for MetadataAsValue.
  162. if (Owner.is<MetadataAsValue *>()) {
  163. Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
  164. continue;
  165. }
  166. // There's a Metadata owner -- dispatch.
  167. Metadata *OwnerMD = Owner.get<Metadata *>();
  168. switch (OwnerMD->getMetadataID()) {
  169. #define HANDLE_METADATA_LEAF(CLASS) \
  170. case Metadata::CLASS##Kind: \
  171. cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
  172. continue;
  173. #include "llvm/IR/Metadata.def"
  174. default:
  175. llvm_unreachable("Invalid metadata subclass");
  176. }
  177. }
  178. assert(UseMap.empty() && "Expected all uses to be replaced");
  179. }
  180. void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
  181. if (UseMap.empty())
  182. return;
  183. if (!ResolveUsers) {
  184. UseMap.clear();
  185. return;
  186. }
  187. // Copy out uses since UseMap could get touched below.
  188. typedef std::pair<void *, std::pair<OwnerTy, uint64_t>> UseTy;
  189. SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
  190. std::sort(Uses.begin(), Uses.end(), [](const UseTy &L, const UseTy &R) {
  191. return L.second.second < R.second.second;
  192. });
  193. UseMap.clear();
  194. for (const auto &Pair : Uses) {
  195. auto Owner = Pair.second.first;
  196. if (!Owner)
  197. continue;
  198. if (Owner.is<MetadataAsValue *>())
  199. continue;
  200. // Resolve MDNodes that point at this.
  201. auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
  202. if (!OwnerMD)
  203. continue;
  204. if (OwnerMD->isResolved())
  205. continue;
  206. OwnerMD->decrementUnresolvedOperandCount();
  207. }
  208. }
  209. static Function *getLocalFunction(Value *V) {
  210. assert(V && "Expected value");
  211. if (auto *A = dyn_cast<Argument>(V))
  212. return A->getParent();
  213. if (BasicBlock *BB = cast<Instruction>(V)->getParent())
  214. return BB->getParent();
  215. return nullptr;
  216. }
  217. ValueAsMetadata *ValueAsMetadata::get(Value *V) {
  218. assert(V && "Unexpected null Value");
  219. auto &Context = V->getContext();
  220. auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
  221. if (!Entry) {
  222. assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
  223. "Expected constant or function-local value");
  224. assert(!V->IsUsedByMD &&
  225. "Expected this to be the only metadata use");
  226. V->IsUsedByMD = true;
  227. if (auto *C = dyn_cast<Constant>(V))
  228. Entry = new ConstantAsMetadata(C);
  229. else
  230. Entry = new LocalAsMetadata(V);
  231. }
  232. return Entry;
  233. }
  234. ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
  235. assert(V && "Unexpected null Value");
  236. return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
  237. }
  238. void ValueAsMetadata::handleDeletion(Value *V) {
  239. assert(V && "Expected valid value");
  240. auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
  241. auto I = Store.find(V);
  242. if (I == Store.end())
  243. return;
  244. // Remove old entry from the map.
  245. ValueAsMetadata *MD = I->second;
  246. // assert(MD && "Expected valid metadata"); // HLSL Change - MD might be nullptr under OOM
  247. // assert(MD->getValue() == V && "Expected valid mapping"); // HLSL Change - MD might be nullptr under OOM
  248. Store.erase(I);
  249. // Delete the metadata.
  250. if (MD) MD->replaceAllUsesWith(nullptr); // HLSL Change - MD might be nullptr under OOM
  251. delete MD;
  252. }
  253. void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
  254. assert(From && "Expected valid value");
  255. assert(To && "Expected valid value");
  256. assert(From != To && "Expected changed value");
  257. assert(From->getType() == To->getType() && "Unexpected type change");
  258. LLVMContext &Context = From->getType()->getContext();
  259. auto &Store = Context.pImpl->ValuesAsMetadata;
  260. auto I = Store.find(From);
  261. if (I == Store.end()) {
  262. assert(!From->IsUsedByMD &&
  263. "Expected From not to be used by metadata");
  264. return;
  265. }
  266. // Remove old entry from the map.
  267. assert(From->IsUsedByMD &&
  268. "Expected From to be used by metadata");
  269. From->IsUsedByMD = false;
  270. ValueAsMetadata *MD = I->second;
  271. assert(MD && "Expected valid metadata");
  272. assert(MD->getValue() == From && "Expected valid mapping");
  273. Store.erase(I);
  274. if (isa<LocalAsMetadata>(MD)) {
  275. if (auto *C = dyn_cast<Constant>(To)) {
  276. // Local became a constant.
  277. MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
  278. delete MD;
  279. return;
  280. }
  281. if (getLocalFunction(From) && getLocalFunction(To) &&
  282. getLocalFunction(From) != getLocalFunction(To)) {
  283. // Function changed.
  284. MD->replaceAllUsesWith(nullptr);
  285. delete MD;
  286. return;
  287. }
  288. } else if (!isa<Constant>(To)) {
  289. // Changed to function-local value.
  290. MD->replaceAllUsesWith(nullptr);
  291. delete MD;
  292. return;
  293. }
  294. auto *&Entry = Store[To];
  295. if (Entry) {
  296. // The target already exists.
  297. MD->replaceAllUsesWith(Entry);
  298. delete MD;
  299. return;
  300. }
  301. // Update MD in place (and update the map entry).
  302. assert(!To->IsUsedByMD &&
  303. "Expected this to be the only metadata use");
  304. To->IsUsedByMD = true;
  305. MD->V = To;
  306. Entry = MD;
  307. }
  308. //===----------------------------------------------------------------------===//
  309. // MDString implementation.
  310. //
  311. MDString *MDString::get(LLVMContext &Context, StringRef Str) {
  312. auto &Store = Context.pImpl->MDStringCache;
  313. auto I = Store.find(Str);
  314. if (I != Store.end())
  315. return &I->second;
  316. auto *Entry =
  317. StringMapEntry<MDString>::Create(Str, Store.getAllocator(), MDString());
  318. // HLSL Change Begin: Don't leak on insertion failure
  319. try {
  320. bool WasInserted = Store.insert(Entry);
  321. (void)WasInserted;
  322. assert(WasInserted && "Expected entry to be inserted");
  323. }
  324. catch (...) {
  325. Entry->Destroy();
  326. throw;
  327. }
  328. // HLSL Change End
  329. Entry->second.Entry = Entry;
  330. return &Entry->second;
  331. }
  332. StringRef MDString::getString() const {
  333. assert(Entry && "Expected to find string map entry");
  334. return Entry->first();
  335. }
  336. //===----------------------------------------------------------------------===//
  337. // MDNode implementation.
  338. //
  339. // Assert that the MDNode types will not be unaligned by the objects
  340. // prepended to them.
  341. #define HANDLE_MDNODE_LEAF(CLASS) \
  342. static_assert( \
  343. llvm::AlignOf<uint64_t>::Alignment >= llvm::AlignOf<CLASS>::Alignment, \
  344. "Alignment is insufficient after objects prepended to " #CLASS);
  345. #include "llvm/IR/Metadata.def"
  346. void *MDNode::operator new(size_t Size, unsigned NumOps) {
  347. size_t OpSize = NumOps * sizeof(MDOperand);
  348. // uint64_t is the most aligned type we need support (ensured by static_assert
  349. // above)
  350. OpSize = RoundUpToAlignment(OpSize, llvm::alignOf<uint64_t>());
  351. void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
  352. MDOperand *O = static_cast<MDOperand *>(Ptr);
  353. for (MDOperand *E = O - NumOps; O != E; --O)
  354. (void)new (O - 1) MDOperand;
  355. return Ptr;
  356. }
  357. void MDNode::operator delete(void *Mem) {
  358. MDNode *N = static_cast<MDNode *>(Mem);
  359. size_t OpSize = N->NumOperands * sizeof(MDOperand);
  360. OpSize = RoundUpToAlignment(OpSize, llvm::alignOf<uint64_t>());
  361. MDOperand *O = static_cast<MDOperand *>(Mem);
  362. for (MDOperand *E = O - N->NumOperands; O != E; --O)
  363. (O - 1)->~MDOperand();
  364. ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
  365. }
  366. MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
  367. ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
  368. : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
  369. NumUnresolved(0), Context(Context) {
  370. unsigned Op = 0;
  371. for (Metadata *MD : Ops1)
  372. setOperand(Op++, MD);
  373. for (Metadata *MD : Ops2)
  374. setOperand(Op++, MD);
  375. if (isDistinct())
  376. return;
  377. if (isUniqued())
  378. // Check whether any operands are unresolved, requiring re-uniquing. If
  379. // not, don't support RAUW.
  380. if (!countUnresolvedOperands())
  381. return;
  382. this->Context.makeReplaceable(make_unique<ReplaceableMetadataImpl>(Context));
  383. }
  384. TempMDNode MDNode::clone() const {
  385. switch (getMetadataID()) {
  386. default:
  387. llvm_unreachable("Invalid MDNode subclass");
  388. #define HANDLE_MDNODE_LEAF(CLASS) \
  389. case CLASS##Kind: \
  390. return cast<CLASS>(this)->cloneImpl();
  391. #include "llvm/IR/Metadata.def"
  392. }
  393. }
  394. static bool isOperandUnresolved(Metadata *Op) {
  395. if (auto *N = dyn_cast_or_null<MDNode>(Op))
  396. return !N->isResolved();
  397. return false;
  398. }
  399. unsigned MDNode::countUnresolvedOperands() {
  400. assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
  401. NumUnresolved = std::count_if(op_begin(), op_end(), isOperandUnresolved);
  402. return NumUnresolved;
  403. }
  404. void MDNode::makeUniqued() {
  405. assert(isTemporary() && "Expected this to be temporary");
  406. assert(!isResolved() && "Expected this to be unresolved");
  407. // Enable uniquing callbacks.
  408. for (auto &Op : mutable_operands())
  409. Op.reset(Op.get(), this);
  410. // Make this 'uniqued'.
  411. Storage = Uniqued;
  412. if (!countUnresolvedOperands())
  413. resolve();
  414. assert(isUniqued() && "Expected this to be uniqued");
  415. }
  416. void MDNode::makeDistinct() {
  417. assert(isTemporary() && "Expected this to be temporary");
  418. assert(!isResolved() && "Expected this to be unresolved");
  419. // Pretend to be uniqued, resolve the node, and then store in distinct table.
  420. Storage = Uniqued;
  421. resolve();
  422. storeDistinctInContext();
  423. assert(isDistinct() && "Expected this to be distinct");
  424. assert(isResolved() && "Expected this to be resolved");
  425. }
  426. void MDNode::resolve() {
  427. assert(isUniqued() && "Expected this to be uniqued");
  428. assert(!isResolved() && "Expected this to be unresolved");
  429. // Move the map, so that this immediately looks resolved.
  430. auto Uses = Context.takeReplaceableUses();
  431. NumUnresolved = 0;
  432. assert(isResolved() && "Expected this to be resolved");
  433. // Drop RAUW support.
  434. Uses->resolveAllUses();
  435. }
  436. void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
  437. assert(NumUnresolved != 0 && "Expected unresolved operands");
  438. // Check if an operand was resolved.
  439. if (!isOperandUnresolved(Old)) {
  440. if (isOperandUnresolved(New))
  441. // An operand was un-resolved!
  442. ++NumUnresolved;
  443. } else if (!isOperandUnresolved(New))
  444. decrementUnresolvedOperandCount();
  445. }
  446. void MDNode::decrementUnresolvedOperandCount() {
  447. if (!--NumUnresolved)
  448. // Last unresolved operand has just been resolved.
  449. resolve();
  450. }
  451. void MDNode::resolveCycles() {
  452. if (isResolved())
  453. return;
  454. // Resolve this node immediately.
  455. resolve();
  456. // Resolve all operands.
  457. for (const auto &Op : operands()) {
  458. auto *N = dyn_cast_or_null<MDNode>(Op);
  459. if (!N)
  460. continue;
  461. assert(!N->isTemporary() &&
  462. "Expected all forward declarations to be resolved");
  463. if (!N->isResolved())
  464. N->resolveCycles();
  465. }
  466. }
  467. static bool hasSelfReference(MDNode *N) {
  468. for (Metadata *MD : N->operands())
  469. if (MD == N)
  470. return true;
  471. return false;
  472. }
  473. MDNode *MDNode::replaceWithPermanentImpl() {
  474. if (hasSelfReference(this))
  475. return replaceWithDistinctImpl();
  476. return replaceWithUniquedImpl();
  477. }
  478. MDNode *MDNode::replaceWithUniquedImpl() {
  479. // Try to uniquify in place.
  480. MDNode *UniquedNode = uniquify();
  481. if (UniquedNode == this) {
  482. makeUniqued();
  483. return this;
  484. }
  485. // Collision, so RAUW instead.
  486. replaceAllUsesWith(UniquedNode);
  487. deleteAsSubclass();
  488. return UniquedNode;
  489. }
  490. MDNode *MDNode::replaceWithDistinctImpl() {
  491. makeDistinct();
  492. return this;
  493. }
  494. void MDTuple::recalculateHash() {
  495. setHash(MDTupleInfo::KeyTy::calculateHash(this));
  496. }
  497. void MDNode::dropAllReferences() {
  498. for (unsigned I = 0, E = NumOperands; I != E; ++I)
  499. setOperand(I, nullptr);
  500. if (!isResolved()) {
  501. Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
  502. (void)Context.takeReplaceableUses();
  503. }
  504. }
  505. void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
  506. unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
  507. assert(Op < getNumOperands() && "Expected valid operand");
  508. if (!isUniqued()) {
  509. // This node is not uniqued. Just set the operand and be done with it.
  510. setOperand(Op, New);
  511. return;
  512. }
  513. // This node is uniqued.
  514. eraseFromStore();
  515. Metadata *Old = getOperand(Op);
  516. setOperand(Op, New);
  517. // Drop uniquing for self-reference cycles.
  518. if (New == this) {
  519. if (!isResolved())
  520. resolve();
  521. storeDistinctInContext();
  522. return;
  523. }
  524. // Re-unique the node.
  525. auto *Uniqued = uniquify();
  526. if (Uniqued == this) {
  527. if (!isResolved())
  528. resolveAfterOperandChange(Old, New);
  529. return;
  530. }
  531. // Collision.
  532. if (!isResolved()) {
  533. // Still unresolved, so RAUW.
  534. //
  535. // First, clear out all operands to prevent any recursion (similar to
  536. // dropAllReferences(), but we still need the use-list).
  537. for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
  538. setOperand(O, nullptr);
  539. Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
  540. deleteAsSubclass();
  541. return;
  542. }
  543. // Store in non-uniqued form if RAUW isn't possible.
  544. storeDistinctInContext();
  545. }
  546. void MDNode::deleteAsSubclass() {
  547. switch (getMetadataID()) {
  548. default:
  549. llvm_unreachable("Invalid subclass of MDNode");
  550. #define HANDLE_MDNODE_LEAF(CLASS) \
  551. case CLASS##Kind: \
  552. delete cast<CLASS>(this); \
  553. break;
  554. #include "llvm/IR/Metadata.def"
  555. }
  556. }
  557. template <class T, class InfoT>
  558. static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
  559. if (T *U = getUniqued(Store, N))
  560. return U;
  561. Store.insert(N);
  562. return N;
  563. }
  564. template <class NodeTy> struct MDNode::HasCachedHash {
  565. typedef char Yes[1];
  566. typedef char No[2];
  567. template <class U, U Val> struct SFINAE {};
  568. template <class U>
  569. static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
  570. template <class U> static No &check(...);
  571. static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
  572. };
  573. MDNode *MDNode::uniquify() {
  574. assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
  575. // Try to insert into uniquing store.
  576. switch (getMetadataID()) {
  577. default:
  578. llvm_unreachable("Invalid subclass of MDNode");
  579. #define HANDLE_MDNODE_LEAF(CLASS) \
  580. case CLASS##Kind: { \
  581. CLASS *SubclassThis = cast<CLASS>(this); \
  582. std::integral_constant<bool, HasCachedHash<CLASS>::value> \
  583. ShouldRecalculateHash; \
  584. dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
  585. return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
  586. }
  587. #include "llvm/IR/Metadata.def"
  588. }
  589. }
  590. void MDNode::eraseFromStore() {
  591. switch (getMetadataID()) {
  592. default:
  593. llvm_unreachable("Invalid subclass of MDNode");
  594. #define HANDLE_MDNODE_LEAF(CLASS) \
  595. case CLASS##Kind: \
  596. getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
  597. break;
  598. #include "llvm/IR/Metadata.def"
  599. }
  600. }
  601. MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
  602. StorageType Storage, bool ShouldCreate) {
  603. unsigned Hash = 0;
  604. if (Storage == Uniqued) {
  605. MDTupleInfo::KeyTy Key(MDs);
  606. if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
  607. return N;
  608. if (!ShouldCreate)
  609. return nullptr;
  610. Hash = Key.getHash();
  611. } else {
  612. assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
  613. }
  614. // HLSL Change - guard with try/catch
  615. MDTuple *MDTuplePtr(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs));
  616. MDTuple *Result;
  617. try {
  618. Result = storeImpl(MDTuplePtr, Storage, Context.pImpl->MDTuples);
  619. } catch (...) {
  620. MDTuplePtr->deleteAsSubclass();
  621. throw;
  622. }
  623. return Result;
  624. }
  625. void MDNode::deleteTemporary(MDNode *N) {
  626. assert(N->isTemporary() && "Expected temporary node");
  627. N->replaceAllUsesWith(nullptr);
  628. N->deleteAsSubclass();
  629. }
  630. void MDNode::storeDistinctInContext() {
  631. assert(isResolved() && "Expected resolved nodes");
  632. Storage = Distinct;
  633. // Reset the hash.
  634. switch (getMetadataID()) {
  635. default:
  636. llvm_unreachable("Invalid subclass of MDNode");
  637. #define HANDLE_MDNODE_LEAF(CLASS) \
  638. case CLASS##Kind: { \
  639. std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
  640. dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
  641. break; \
  642. }
  643. #include "llvm/IR/Metadata.def"
  644. }
  645. getContext().pImpl->DistinctMDNodes.insert(this);
  646. }
  647. void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
  648. if (getOperand(I) == New)
  649. return;
  650. if (!isUniqued()) {
  651. setOperand(I, New);
  652. return;
  653. }
  654. handleChangedOperand(mutable_begin() + I, New);
  655. }
  656. void MDNode::setOperand(unsigned I, Metadata *New) {
  657. assert(I < NumOperands);
  658. mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
  659. }
  660. /// \brief Get a node, or a self-reference that looks like it.
  661. ///
  662. /// Special handling for finding self-references, for use by \a
  663. /// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
  664. /// when self-referencing nodes were still uniqued. If the first operand has
  665. /// the same operands as \c Ops, return the first operand instead.
  666. static MDNode *getOrSelfReference(LLVMContext &Context,
  667. ArrayRef<Metadata *> Ops) {
  668. if (!Ops.empty())
  669. if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
  670. if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
  671. for (unsigned I = 1, E = Ops.size(); I != E; ++I)
  672. if (Ops[I] != N->getOperand(I))
  673. return MDNode::get(Context, Ops);
  674. return N;
  675. }
  676. return MDNode::get(Context, Ops);
  677. }
  678. MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
  679. if (!A)
  680. return B;
  681. if (!B)
  682. return A;
  683. SmallVector<Metadata *, 4> MDs;
  684. MDs.reserve(A->getNumOperands() + B->getNumOperands());
  685. MDs.append(A->op_begin(), A->op_end());
  686. MDs.append(B->op_begin(), B->op_end());
  687. // FIXME: This preserves long-standing behaviour, but is it really the right
  688. // behaviour? Or was that an unintended side-effect of node uniquing?
  689. return getOrSelfReference(A->getContext(), MDs);
  690. }
  691. MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
  692. if (!A || !B)
  693. return nullptr;
  694. SmallVector<Metadata *, 4> MDs;
  695. for (Metadata *MD : A->operands())
  696. if (std::find(B->op_begin(), B->op_end(), MD) != B->op_end())
  697. MDs.push_back(MD);
  698. // FIXME: This preserves long-standing behaviour, but is it really the right
  699. // behaviour? Or was that an unintended side-effect of node uniquing?
  700. return getOrSelfReference(A->getContext(), MDs);
  701. }
  702. MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
  703. if (!A || !B)
  704. return nullptr;
  705. SmallVector<Metadata *, 4> MDs(B->op_begin(), B->op_end());
  706. for (Metadata *MD : A->operands())
  707. if (std::find(B->op_begin(), B->op_end(), MD) == B->op_end())
  708. MDs.push_back(MD);
  709. // FIXME: This preserves long-standing behaviour, but is it really the right
  710. // behaviour? Or was that an unintended side-effect of node uniquing?
  711. return getOrSelfReference(A->getContext(), MDs);
  712. }
  713. MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
  714. if (!A || !B)
  715. return nullptr;
  716. APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
  717. APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
  718. if (AVal.compare(BVal) == APFloat::cmpLessThan)
  719. return A;
  720. return B;
  721. }
  722. static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
  723. return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
  724. }
  725. static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
  726. return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
  727. }
  728. static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
  729. ConstantInt *Low, ConstantInt *High) {
  730. ConstantRange NewRange(Low->getValue(), High->getValue());
  731. unsigned Size = EndPoints.size();
  732. APInt LB = EndPoints[Size - 2]->getValue();
  733. APInt LE = EndPoints[Size - 1]->getValue();
  734. ConstantRange LastRange(LB, LE);
  735. if (canBeMerged(NewRange, LastRange)) {
  736. ConstantRange Union = LastRange.unionWith(NewRange);
  737. Type *Ty = High->getType();
  738. EndPoints[Size - 2] =
  739. cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
  740. EndPoints[Size - 1] =
  741. cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
  742. return true;
  743. }
  744. return false;
  745. }
  746. static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
  747. ConstantInt *Low, ConstantInt *High) {
  748. if (!EndPoints.empty())
  749. if (tryMergeRange(EndPoints, Low, High))
  750. return;
  751. EndPoints.push_back(Low);
  752. EndPoints.push_back(High);
  753. }
  754. MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
  755. // Given two ranges, we want to compute the union of the ranges. This
  756. // is slightly complitade by having to combine the intervals and merge
  757. // the ones that overlap.
  758. if (!A || !B)
  759. return nullptr;
  760. if (A == B)
  761. return A;
  762. // First, walk both lists in older of the lower boundary of each interval.
  763. // At each step, try to merge the new interval to the last one we adedd.
  764. SmallVector<ConstantInt *, 4> EndPoints;
  765. int AI = 0;
  766. int BI = 0;
  767. int AN = A->getNumOperands() / 2;
  768. int BN = B->getNumOperands() / 2;
  769. while (AI < AN && BI < BN) {
  770. ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
  771. ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
  772. if (ALow->getValue().slt(BLow->getValue())) {
  773. addRange(EndPoints, ALow,
  774. mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
  775. ++AI;
  776. } else {
  777. addRange(EndPoints, BLow,
  778. mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
  779. ++BI;
  780. }
  781. }
  782. while (AI < AN) {
  783. addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
  784. mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
  785. ++AI;
  786. }
  787. while (BI < BN) {
  788. addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
  789. mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
  790. ++BI;
  791. }
  792. // If we have more than 2 ranges (4 endpoints) we have to try to merge
  793. // the last and first ones.
  794. unsigned Size = EndPoints.size();
  795. if (Size > 4) {
  796. ConstantInt *FB = EndPoints[0];
  797. ConstantInt *FE = EndPoints[1];
  798. if (tryMergeRange(EndPoints, FB, FE)) {
  799. for (unsigned i = 0; i < Size - 2; ++i) {
  800. EndPoints[i] = EndPoints[i + 2];
  801. }
  802. EndPoints.resize(Size - 2);
  803. }
  804. }
  805. // If in the end we have a single range, it is possible that it is now the
  806. // full range. Just drop the metadata in that case.
  807. if (EndPoints.size() == 2) {
  808. ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
  809. if (Range.isFullSet())
  810. return nullptr;
  811. }
  812. SmallVector<Metadata *, 4> MDs;
  813. MDs.reserve(EndPoints.size());
  814. for (auto *I : EndPoints)
  815. MDs.push_back(ConstantAsMetadata::get(I));
  816. return MDNode::get(A->getContext(), MDs);
  817. }
  818. //===----------------------------------------------------------------------===//
  819. // NamedMDNode implementation.
  820. //
  821. static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
  822. return *(SmallVector<TrackingMDRef, 4> *)Operands;
  823. }
  824. NamedMDNode::NamedMDNode(const Twine &N)
  825. : Name(N.str()), Parent(nullptr),
  826. Operands(new SmallVector<TrackingMDRef, 4>()) {}
  827. NamedMDNode::~NamedMDNode() {
  828. dropAllReferences();
  829. delete &getNMDOps(Operands);
  830. }
  831. unsigned NamedMDNode::getNumOperands() const {
  832. return (unsigned)getNMDOps(Operands).size();
  833. }
  834. MDNode *NamedMDNode::getOperand(unsigned i) const {
  835. assert(i < getNumOperands() && "Invalid Operand number!");
  836. auto *N = getNMDOps(Operands)[i].get();
  837. return cast_or_null<MDNode>(N);
  838. }
  839. void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
  840. void NamedMDNode::setOperand(unsigned I, MDNode *New) {
  841. assert(I < getNumOperands() && "Invalid operand number");
  842. getNMDOps(Operands)[I].reset(New);
  843. }
  844. void NamedMDNode::eraseFromParent() {
  845. getParent()->eraseNamedMetadata(this);
  846. }
  847. void NamedMDNode::dropAllReferences() {
  848. getNMDOps(Operands).clear();
  849. }
  850. StringRef NamedMDNode::getName() const {
  851. return StringRef(Name);
  852. }
  853. //===----------------------------------------------------------------------===//
  854. // Instruction Metadata method implementations.
  855. //
  856. void MDAttachmentMap::set(unsigned ID, MDNode &MD) {
  857. for (auto &I : Attachments)
  858. if (I.first == ID) {
  859. I.second.reset(&MD);
  860. return;
  861. }
  862. Attachments.emplace_back(std::piecewise_construct, std::make_tuple(ID),
  863. std::make_tuple(&MD));
  864. }
  865. void MDAttachmentMap::erase(unsigned ID) {
  866. if (empty())
  867. return;
  868. // Common case is one/last value.
  869. if (Attachments.back().first == ID) {
  870. Attachments.pop_back();
  871. return;
  872. }
  873. for (auto I = Attachments.begin(), E = std::prev(Attachments.end()); I != E;
  874. ++I)
  875. if (I->first == ID) {
  876. *I = std::move(Attachments.back());
  877. Attachments.pop_back();
  878. return;
  879. }
  880. }
  881. MDNode *MDAttachmentMap::lookup(unsigned ID) const {
  882. for (const auto &I : Attachments)
  883. if (I.first == ID)
  884. return I.second;
  885. return nullptr;
  886. }
  887. void MDAttachmentMap::getAll(
  888. SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
  889. Result.append(Attachments.begin(), Attachments.end());
  890. // Sort the resulting array so it is stable.
  891. if (Result.size() > 1)
  892. array_pod_sort(Result.begin(), Result.end());
  893. }
  894. void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
  895. if (!Node && !hasMetadata())
  896. return;
  897. setMetadata(getContext().getMDKindID(Kind), Node);
  898. }
  899. MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
  900. unsigned KindID = 0;
  901. #if 0 // HLSL Change Starts
  902. return getMetadataImpl(getContext().getMDKindID(Kind))
  903. #else
  904. // Calling special function to check for existence of string id,
  905. // so it doesn't get instantiated in the context.
  906. if (getContext().findMDKindID(Kind, &KindID))
  907. return getMetadataImpl(KindID);
  908. return nullptr;
  909. #endif // HLSL Change Ends
  910. }
  911. void Instruction::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
  912. SmallSet<unsigned, 5> KnownSet;
  913. KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
  914. // Drop debug if needed
  915. if (KnownSet.erase(LLVMContext::MD_dbg))
  916. DbgLoc = DebugLoc();
  917. if (!hasMetadataHashEntry())
  918. return; // Nothing to remove!
  919. auto &InstructionMetadata = getContext().pImpl->InstructionMetadata;
  920. if (KnownSet.empty()) {
  921. // Just drop our entry at the store.
  922. InstructionMetadata.erase(this);
  923. setHasMetadataHashEntry(false);
  924. return;
  925. }
  926. auto &Info = InstructionMetadata[this];
  927. Info.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
  928. return !KnownSet.count(I.first);
  929. });
  930. if (Info.empty()) {
  931. // Drop our entry at the store.
  932. InstructionMetadata.erase(this);
  933. setHasMetadataHashEntry(false);
  934. }
  935. }
  936. /// setMetadata - Set the metadata of of the specified kind to the specified
  937. /// node. This updates/replaces metadata if already present, or removes it if
  938. /// Node is null.
  939. void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
  940. if (!Node && !hasMetadata())
  941. return;
  942. // Handle 'dbg' as a special case since it is not stored in the hash table.
  943. if (KindID == LLVMContext::MD_dbg) {
  944. DbgLoc = DebugLoc(Node);
  945. return;
  946. }
  947. // Handle the case when we're adding/updating metadata on an instruction.
  948. if (Node) {
  949. auto &Info = getContext().pImpl->InstructionMetadata[this];
  950. assert(!Info.empty() == hasMetadataHashEntry() &&
  951. "HasMetadata bit is wonked");
  952. if (Info.empty())
  953. setHasMetadataHashEntry(true);
  954. Info.set(KindID, *Node);
  955. return;
  956. }
  957. // Otherwise, we're removing metadata from an instruction.
  958. assert((hasMetadataHashEntry() ==
  959. (getContext().pImpl->InstructionMetadata.count(this) > 0)) &&
  960. "HasMetadata bit out of date!");
  961. if (!hasMetadataHashEntry())
  962. return; // Nothing to remove!
  963. auto &Info = getContext().pImpl->InstructionMetadata[this];
  964. // Handle removal of an existing value.
  965. Info.erase(KindID);
  966. if (!Info.empty())
  967. return;
  968. getContext().pImpl->InstructionMetadata.erase(this);
  969. setHasMetadataHashEntry(false);
  970. }
  971. void Instruction::setAAMetadata(const AAMDNodes &N) {
  972. setMetadata(LLVMContext::MD_tbaa, N.TBAA);
  973. setMetadata(LLVMContext::MD_alias_scope, N.Scope);
  974. setMetadata(LLVMContext::MD_noalias, N.NoAlias);
  975. }
  976. MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
  977. // Handle 'dbg' as a special case since it is not stored in the hash table.
  978. if (KindID == LLVMContext::MD_dbg)
  979. return DbgLoc.getAsMDNode();
  980. if (!hasMetadataHashEntry())
  981. return nullptr;
  982. auto &Info = getContext().pImpl->InstructionMetadata[this];
  983. assert(!Info.empty() && "bit out of sync with hash table");
  984. return Info.lookup(KindID);
  985. }
  986. void Instruction::getAllMetadataImpl(
  987. SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
  988. Result.clear();
  989. // Handle 'dbg' as a special case since it is not stored in the hash table.
  990. if (DbgLoc) {
  991. Result.push_back(
  992. std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
  993. if (!hasMetadataHashEntry()) return;
  994. }
  995. assert(hasMetadataHashEntry() &&
  996. getContext().pImpl->InstructionMetadata.count(this) &&
  997. "Shouldn't have called this");
  998. const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
  999. assert(!Info.empty() && "Shouldn't have called this");
  1000. Info.getAll(Result);
  1001. }
  1002. void Instruction::getAllMetadataOtherThanDebugLocImpl(
  1003. SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
  1004. Result.clear();
  1005. assert(hasMetadataHashEntry() &&
  1006. getContext().pImpl->InstructionMetadata.count(this) &&
  1007. "Shouldn't have called this");
  1008. const auto &Info = getContext().pImpl->InstructionMetadata.find(this)->second;
  1009. assert(!Info.empty() && "Shouldn't have called this");
  1010. Info.getAll(Result);
  1011. }
  1012. /// clearMetadataHashEntries - Clear all hashtable-based metadata from
  1013. /// this instruction.
  1014. void Instruction::clearMetadataHashEntries() {
  1015. assert(hasMetadataHashEntry() && "Caller should check");
  1016. getContext().pImpl->InstructionMetadata.erase(this);
  1017. setHasMetadataHashEntry(false);
  1018. }
  1019. MDNode *Function::getMetadata(unsigned KindID) const {
  1020. if (!hasMetadata())
  1021. return nullptr;
  1022. return getContext().pImpl->FunctionMetadata[this].lookup(KindID);
  1023. }
  1024. MDNode *Function::getMetadata(StringRef Kind) const {
  1025. if (!hasMetadata())
  1026. return nullptr;
  1027. return getMetadata(getContext().getMDKindID(Kind));
  1028. }
  1029. void Function::setMetadata(unsigned KindID, MDNode *MD) {
  1030. if (MD) {
  1031. if (!hasMetadata())
  1032. setHasMetadataHashEntry(true);
  1033. getContext().pImpl->FunctionMetadata[this].set(KindID, *MD);
  1034. return;
  1035. }
  1036. // Nothing to unset.
  1037. if (!hasMetadata())
  1038. return;
  1039. auto &Store = getContext().pImpl->FunctionMetadata[this];
  1040. Store.erase(KindID);
  1041. if (Store.empty())
  1042. clearMetadata();
  1043. }
  1044. void Function::setMetadata(StringRef Kind, MDNode *MD) {
  1045. if (!MD && !hasMetadata())
  1046. return;
  1047. setMetadata(getContext().getMDKindID(Kind), MD);
  1048. }
  1049. void Function::getAllMetadata(
  1050. SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
  1051. MDs.clear();
  1052. if (!hasMetadata())
  1053. return;
  1054. getContext().pImpl->FunctionMetadata[this].getAll(MDs);
  1055. }
  1056. void Function::dropUnknownMetadata(ArrayRef<unsigned> KnownIDs) {
  1057. if (!hasMetadata())
  1058. return;
  1059. if (KnownIDs.empty()) {
  1060. clearMetadata();
  1061. return;
  1062. }
  1063. SmallSet<unsigned, 5> KnownSet;
  1064. KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
  1065. auto &Store = getContext().pImpl->FunctionMetadata[this];
  1066. assert(!Store.empty());
  1067. Store.remove_if([&KnownSet](const std::pair<unsigned, TrackingMDNodeRef> &I) {
  1068. return !KnownSet.count(I.first);
  1069. });
  1070. if (Store.empty())
  1071. clearMetadata();
  1072. }
  1073. void Function::clearMetadata() {
  1074. if (!hasMetadata())
  1075. return;
  1076. getContext().pImpl->FunctionMetadata.erase(this);
  1077. setHasMetadataHashEntry(false);
  1078. }