Metadata.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560
  1. //===- Metadata.cpp - Implement Metadata classes --------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the Metadata classes.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/IR/Metadata.h"
  13. #include "LLVMContextImpl.h"
  14. #include "MetadataImpl.h"
  15. #include "llvm/ADT/APFloat.h"
  16. #include "llvm/ADT/APInt.h"
  17. #include "llvm/ADT/ArrayRef.h"
  18. #include "llvm/ADT/DenseSet.h"
  19. #include "llvm/ADT/None.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/SetVector.h"
  22. #include "llvm/ADT/SmallPtrSet.h"
  23. #include "llvm/ADT/SmallSet.h"
  24. #include "llvm/ADT/SmallVector.h"
  25. #include "llvm/ADT/StringMap.h"
  26. #include "llvm/ADT/StringRef.h"
  27. #include "llvm/ADT/Twine.h"
  28. #include "llvm/IR/Argument.h"
  29. #include "llvm/IR/BasicBlock.h"
  30. #include "llvm/IR/Constant.h"
  31. #include "llvm/IR/ConstantRange.h"
  32. #include "llvm/IR/Constants.h"
  33. #include "llvm/IR/DebugInfoMetadata.h"
  34. #include "llvm/IR/DebugLoc.h"
  35. #include "llvm/IR/Function.h"
  36. #include "llvm/IR/GlobalObject.h"
  37. #include "llvm/IR/GlobalVariable.h"
  38. #include "llvm/IR/Instruction.h"
  39. #include "llvm/IR/LLVMContext.h"
  40. #include "llvm/IR/MDBuilder.h"
  41. #include "llvm/IR/Module.h"
  42. #include "llvm/IR/TrackingMDRef.h"
  43. #include "llvm/IR/Type.h"
  44. #include "llvm/IR/Value.h"
  45. #include "llvm/Support/Casting.h"
  46. #include "llvm/Support/ErrorHandling.h"
  47. #include "llvm/Support/MathExtras.h"
  48. #include <algorithm>
  49. #include <cassert>
  50. #include <cstddef>
  51. #include <cstdint>
  52. #include <type_traits>
  53. #include <utility>
  54. #include <vector>
  55. using namespace llvm;
  56. MetadataAsValue::MetadataAsValue(Type *Ty, Metadata *MD)
  57. : Value(Ty, MetadataAsValueVal), MD(MD) {
  58. track();
  59. }
  60. MetadataAsValue::~MetadataAsValue() {
  61. getType()->getContext().pImpl->MetadataAsValues.erase(MD);
  62. untrack();
  63. }
  64. /// Canonicalize metadata arguments to intrinsics.
  65. ///
  66. /// To support bitcode upgrades (and assembly semantic sugar) for \a
  67. /// MetadataAsValue, we need to canonicalize certain metadata.
  68. ///
  69. /// - nullptr is replaced by an empty MDNode.
  70. /// - An MDNode with a single null operand is replaced by an empty MDNode.
  71. /// - An MDNode whose only operand is a \a ConstantAsMetadata gets skipped.
  72. ///
  73. /// This maintains readability of bitcode from when metadata was a type of
  74. /// value, and these bridges were unnecessary.
  75. static Metadata *canonicalizeMetadataForValue(LLVMContext &Context,
  76. Metadata *MD) {
  77. if (!MD)
  78. // !{}
  79. return MDNode::get(Context, None);
  80. // Return early if this isn't a single-operand MDNode.
  81. auto *N = dyn_cast<MDNode>(MD);
  82. if (!N || N->getNumOperands() != 1)
  83. return MD;
  84. if (!N->getOperand(0))
  85. // !{}
  86. return MDNode::get(Context, None);
  87. if (auto *C = dyn_cast<ConstantAsMetadata>(N->getOperand(0)))
  88. // Look through the MDNode.
  89. return C;
  90. return MD;
  91. }
  92. MetadataAsValue *MetadataAsValue::get(LLVMContext &Context, Metadata *MD) {
  93. MD = canonicalizeMetadataForValue(Context, MD);
  94. auto *&Entry = Context.pImpl->MetadataAsValues[MD];
  95. if (!Entry)
  96. Entry = new MetadataAsValue(Type::getMetadataTy(Context), MD);
  97. return Entry;
  98. }
  99. MetadataAsValue *MetadataAsValue::getIfExists(LLVMContext &Context,
  100. Metadata *MD) {
  101. MD = canonicalizeMetadataForValue(Context, MD);
  102. auto &Store = Context.pImpl->MetadataAsValues;
  103. return Store.lookup(MD);
  104. }
  105. void MetadataAsValue::handleChangedMetadata(Metadata *MD) {
  106. LLVMContext &Context = getContext();
  107. MD = canonicalizeMetadataForValue(Context, MD);
  108. auto &Store = Context.pImpl->MetadataAsValues;
  109. // Stop tracking the old metadata.
  110. Store.erase(this->MD);
  111. untrack();
  112. this->MD = nullptr;
  113. // Start tracking MD, or RAUW if necessary.
  114. auto *&Entry = Store[MD];
  115. if (Entry) {
  116. replaceAllUsesWith(Entry);
  117. delete this;
  118. return;
  119. }
  120. this->MD = MD;
  121. track();
  122. Entry = this;
  123. }
  124. void MetadataAsValue::track() {
  125. if (MD)
  126. MetadataTracking::track(&MD, *MD, *this);
  127. }
  128. void MetadataAsValue::untrack() {
  129. if (MD)
  130. MetadataTracking::untrack(MD);
  131. }
  132. bool MetadataTracking::track(void *Ref, Metadata &MD, OwnerTy Owner) {
  133. assert(Ref && "Expected live reference");
  134. assert((Owner || *static_cast<Metadata **>(Ref) == &MD) &&
  135. "Reference without owner must be direct");
  136. if (auto *R = ReplaceableMetadataImpl::getOrCreate(MD)) {
  137. R->addRef(Ref, Owner);
  138. return true;
  139. }
  140. if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD)) {
  141. assert(!PH->Use && "Placeholders can only be used once");
  142. assert(!Owner && "Unexpected callback to owner");
  143. PH->Use = static_cast<Metadata **>(Ref);
  144. return true;
  145. }
  146. return false;
  147. }
  148. void MetadataTracking::untrack(void *Ref, Metadata &MD) {
  149. assert(Ref && "Expected live reference");
  150. if (auto *R = ReplaceableMetadataImpl::getIfExists(MD))
  151. R->dropRef(Ref);
  152. else if (auto *PH = dyn_cast<DistinctMDOperandPlaceholder>(&MD))
  153. PH->Use = nullptr;
  154. }
  155. bool MetadataTracking::retrack(void *Ref, Metadata &MD, void *New) {
  156. assert(Ref && "Expected live reference");
  157. assert(New && "Expected live reference");
  158. assert(Ref != New && "Expected change");
  159. if (auto *R = ReplaceableMetadataImpl::getIfExists(MD)) {
  160. R->moveRef(Ref, New, MD);
  161. return true;
  162. }
  163. assert(!isa<DistinctMDOperandPlaceholder>(MD) &&
  164. "Unexpected move of an MDOperand");
  165. assert(!isReplaceable(MD) &&
  166. "Expected un-replaceable metadata, since we didn't move a reference");
  167. return false;
  168. }
  169. bool MetadataTracking::isReplaceable(const Metadata &MD) {
  170. return ReplaceableMetadataImpl::isReplaceable(MD);
  171. }
  172. SmallVector<Metadata *> ReplaceableMetadataImpl::getAllArgListUsers() {
  173. SmallVector<std::pair<OwnerTy, uint64_t> *> MDUsersWithID;
  174. for (auto Pair : UseMap) {
  175. OwnerTy Owner = Pair.second.first;
  176. if (!Owner.is<Metadata *>())
  177. continue;
  178. Metadata *OwnerMD = Owner.get<Metadata *>();
  179. if (OwnerMD->getMetadataID() == Metadata::DIArgListKind)
  180. MDUsersWithID.push_back(&UseMap[Pair.first]);
  181. }
  182. llvm::sort(MDUsersWithID, [](auto UserA, auto UserB) {
  183. return UserA->second < UserB->second;
  184. });
  185. SmallVector<Metadata *> MDUsers;
  186. for (auto UserWithID : MDUsersWithID)
  187. MDUsers.push_back(UserWithID->first.get<Metadata *>());
  188. return MDUsers;
  189. }
  190. void ReplaceableMetadataImpl::addRef(void *Ref, OwnerTy Owner) {
  191. bool WasInserted =
  192. UseMap.insert(std::make_pair(Ref, std::make_pair(Owner, NextIndex)))
  193. .second;
  194. (void)WasInserted;
  195. assert(WasInserted && "Expected to add a reference");
  196. ++NextIndex;
  197. assert(NextIndex != 0 && "Unexpected overflow");
  198. }
  199. void ReplaceableMetadataImpl::dropRef(void *Ref) {
  200. bool WasErased = UseMap.erase(Ref);
  201. (void)WasErased;
  202. assert(WasErased && "Expected to drop a reference");
  203. }
  204. void ReplaceableMetadataImpl::moveRef(void *Ref, void *New,
  205. const Metadata &MD) {
  206. auto I = UseMap.find(Ref);
  207. assert(I != UseMap.end() && "Expected to move a reference");
  208. auto OwnerAndIndex = I->second;
  209. UseMap.erase(I);
  210. bool WasInserted = UseMap.insert(std::make_pair(New, OwnerAndIndex)).second;
  211. (void)WasInserted;
  212. assert(WasInserted && "Expected to add a reference");
  213. // Check that the references are direct if there's no owner.
  214. (void)MD;
  215. assert((OwnerAndIndex.first || *static_cast<Metadata **>(Ref) == &MD) &&
  216. "Reference without owner must be direct");
  217. assert((OwnerAndIndex.first || *static_cast<Metadata **>(New) == &MD) &&
  218. "Reference without owner must be direct");
  219. }
  220. void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
  221. if (UseMap.empty())
  222. return;
  223. // Copy out uses since UseMap will get touched below.
  224. using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
  225. SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
  226. llvm::sort(Uses, [](const UseTy &L, const UseTy &R) {
  227. return L.second.second < R.second.second;
  228. });
  229. for (const auto &Pair : Uses) {
  230. // Check that this Ref hasn't disappeared after RAUW (when updating a
  231. // previous Ref).
  232. if (!UseMap.count(Pair.first))
  233. continue;
  234. OwnerTy Owner = Pair.second.first;
  235. if (!Owner) {
  236. // Update unowned tracking references directly.
  237. Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
  238. Ref = MD;
  239. if (MD)
  240. MetadataTracking::track(Ref);
  241. UseMap.erase(Pair.first);
  242. continue;
  243. }
  244. // Check for MetadataAsValue.
  245. if (Owner.is<MetadataAsValue *>()) {
  246. Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
  247. continue;
  248. }
  249. // There's a Metadata owner -- dispatch.
  250. Metadata *OwnerMD = Owner.get<Metadata *>();
  251. switch (OwnerMD->getMetadataID()) {
  252. #define HANDLE_METADATA_LEAF(CLASS) \
  253. case Metadata::CLASS##Kind: \
  254. cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
  255. continue;
  256. #include "llvm/IR/Metadata.def"
  257. default:
  258. llvm_unreachable("Invalid metadata subclass");
  259. }
  260. }
  261. assert(UseMap.empty() && "Expected all uses to be replaced");
  262. }
  263. void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
  264. if (UseMap.empty())
  265. return;
  266. if (!ResolveUsers) {
  267. UseMap.clear();
  268. return;
  269. }
  270. // Copy out uses since UseMap could get touched below.
  271. using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
  272. SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
  273. llvm::sort(Uses, [](const UseTy &L, const UseTy &R) {
  274. return L.second.second < R.second.second;
  275. });
  276. UseMap.clear();
  277. for (const auto &Pair : Uses) {
  278. auto Owner = Pair.second.first;
  279. if (!Owner)
  280. continue;
  281. if (Owner.is<MetadataAsValue *>())
  282. continue;
  283. // Resolve MDNodes that point at this.
  284. auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
  285. if (!OwnerMD)
  286. continue;
  287. if (OwnerMD->isResolved())
  288. continue;
  289. OwnerMD->decrementUnresolvedOperandCount();
  290. }
  291. }
  292. ReplaceableMetadataImpl *ReplaceableMetadataImpl::getOrCreate(Metadata &MD) {
  293. if (auto *N = dyn_cast<MDNode>(&MD))
  294. return N->isResolved() ? nullptr : N->Context.getOrCreateReplaceableUses();
  295. return dyn_cast<ValueAsMetadata>(&MD);
  296. }
  297. ReplaceableMetadataImpl *ReplaceableMetadataImpl::getIfExists(Metadata &MD) {
  298. if (auto *N = dyn_cast<MDNode>(&MD))
  299. return N->isResolved() ? nullptr : N->Context.getReplaceableUses();
  300. return dyn_cast<ValueAsMetadata>(&MD);
  301. }
  302. bool ReplaceableMetadataImpl::isReplaceable(const Metadata &MD) {
  303. if (auto *N = dyn_cast<MDNode>(&MD))
  304. return !N->isResolved();
  305. return isa<ValueAsMetadata>(&MD);
  306. }
  307. static DISubprogram *getLocalFunctionMetadata(Value *V) {
  308. assert(V && "Expected value");
  309. if (auto *A = dyn_cast<Argument>(V)) {
  310. if (auto *Fn = A->getParent())
  311. return Fn->getSubprogram();
  312. return nullptr;
  313. }
  314. if (BasicBlock *BB = cast<Instruction>(V)->getParent()) {
  315. if (auto *Fn = BB->getParent())
  316. return Fn->getSubprogram();
  317. return nullptr;
  318. }
  319. return nullptr;
  320. }
  321. ValueAsMetadata *ValueAsMetadata::get(Value *V) {
  322. assert(V && "Unexpected null Value");
  323. auto &Context = V->getContext();
  324. auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
  325. if (!Entry) {
  326. assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
  327. "Expected constant or function-local value");
  328. assert(!V->IsUsedByMD && "Expected this to be the only metadata use");
  329. V->IsUsedByMD = true;
  330. if (auto *C = dyn_cast<Constant>(V))
  331. Entry = new ConstantAsMetadata(C);
  332. else
  333. Entry = new LocalAsMetadata(V);
  334. }
  335. return Entry;
  336. }
  337. ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
  338. assert(V && "Unexpected null Value");
  339. return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
  340. }
  341. void ValueAsMetadata::handleDeletion(Value *V) {
  342. assert(V && "Expected valid value");
  343. auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
  344. auto I = Store.find(V);
  345. if (I == Store.end())
  346. return;
  347. // Remove old entry from the map.
  348. ValueAsMetadata *MD = I->second;
  349. assert(MD && "Expected valid metadata");
  350. assert(MD->getValue() == V && "Expected valid mapping");
  351. Store.erase(I);
  352. // Delete the metadata.
  353. MD->replaceAllUsesWith(nullptr);
  354. delete MD;
  355. }
  356. void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
  357. assert(From && "Expected valid value");
  358. assert(To && "Expected valid value");
  359. assert(From != To && "Expected changed value");
  360. assert(From->getType() == To->getType() && "Unexpected type change");
  361. LLVMContext &Context = From->getType()->getContext();
  362. auto &Store = Context.pImpl->ValuesAsMetadata;
  363. auto I = Store.find(From);
  364. if (I == Store.end()) {
  365. assert(!From->IsUsedByMD && "Expected From not to be used by metadata");
  366. return;
  367. }
  368. // Remove old entry from the map.
  369. assert(From->IsUsedByMD && "Expected From to be used by metadata");
  370. From->IsUsedByMD = false;
  371. ValueAsMetadata *MD = I->second;
  372. assert(MD && "Expected valid metadata");
  373. assert(MD->getValue() == From && "Expected valid mapping");
  374. Store.erase(I);
  375. if (isa<LocalAsMetadata>(MD)) {
  376. if (auto *C = dyn_cast<Constant>(To)) {
  377. // Local became a constant.
  378. MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
  379. delete MD;
  380. return;
  381. }
  382. if (getLocalFunctionMetadata(From) && getLocalFunctionMetadata(To) &&
  383. getLocalFunctionMetadata(From) != getLocalFunctionMetadata(To)) {
  384. // DISubprogram changed.
  385. MD->replaceAllUsesWith(nullptr);
  386. delete MD;
  387. return;
  388. }
  389. } else if (!isa<Constant>(To)) {
  390. // Changed to function-local value.
  391. MD->replaceAllUsesWith(nullptr);
  392. delete MD;
  393. return;
  394. }
  395. auto *&Entry = Store[To];
  396. if (Entry) {
  397. // The target already exists.
  398. MD->replaceAllUsesWith(Entry);
  399. delete MD;
  400. return;
  401. }
  402. // Update MD in place (and update the map entry).
  403. assert(!To->IsUsedByMD && "Expected this to be the only metadata use");
  404. To->IsUsedByMD = true;
  405. MD->V = To;
  406. Entry = MD;
  407. }
  408. //===----------------------------------------------------------------------===//
  409. // MDString implementation.
  410. //
  411. MDString *MDString::get(LLVMContext &Context, StringRef Str) {
  412. auto &Store = Context.pImpl->MDStringCache;
  413. auto I = Store.try_emplace(Str);
  414. auto &MapEntry = I.first->getValue();
  415. if (!I.second)
  416. return &MapEntry;
  417. MapEntry.Entry = &*I.first;
  418. return &MapEntry;
  419. }
  420. StringRef MDString::getString() const {
  421. assert(Entry && "Expected to find string map entry");
  422. return Entry->first();
  423. }
  424. //===----------------------------------------------------------------------===//
  425. // MDNode implementation.
  426. //
  427. // Assert that the MDNode types will not be unaligned by the objects
  428. // prepended to them.
  429. #define HANDLE_MDNODE_LEAF(CLASS) \
  430. static_assert( \
  431. alignof(uint64_t) >= alignof(CLASS), \
  432. "Alignment is insufficient after objects prepended to " #CLASS);
  433. #include "llvm/IR/Metadata.def"
  434. void *MDNode::operator new(size_t Size, unsigned NumOps) {
  435. size_t OpSize = NumOps * sizeof(MDOperand);
  436. // uint64_t is the most aligned type we need support (ensured by static_assert
  437. // above)
  438. OpSize = alignTo(OpSize, alignof(uint64_t));
  439. void *Ptr = reinterpret_cast<char *>(::operator new(OpSize + Size)) + OpSize;
  440. MDOperand *O = static_cast<MDOperand *>(Ptr);
  441. for (MDOperand *E = O - NumOps; O != E; --O)
  442. (void)new (O - 1) MDOperand;
  443. return Ptr;
  444. }
  445. // Repress memory sanitization, due to use-after-destroy by operator
  446. // delete. Bug report 24578 identifies this issue.
  447. LLVM_NO_SANITIZE_MEMORY_ATTRIBUTE void MDNode::operator delete(void *Mem) {
  448. MDNode *N = static_cast<MDNode *>(Mem);
  449. size_t OpSize = N->NumOperands * sizeof(MDOperand);
  450. OpSize = alignTo(OpSize, alignof(uint64_t));
  451. MDOperand *O = static_cast<MDOperand *>(Mem);
  452. for (MDOperand *E = O - N->NumOperands; O != E; --O)
  453. (O - 1)->~MDOperand();
  454. ::operator delete(reinterpret_cast<char *>(Mem) - OpSize);
  455. }
  456. MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
  457. ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
  458. : Metadata(ID, Storage), NumOperands(Ops1.size() + Ops2.size()),
  459. NumUnresolved(0), Context(Context) {
  460. unsigned Op = 0;
  461. for (Metadata *MD : Ops1)
  462. setOperand(Op++, MD);
  463. for (Metadata *MD : Ops2)
  464. setOperand(Op++, MD);
  465. if (!isUniqued())
  466. return;
  467. // Count the unresolved operands. If there are any, RAUW support will be
  468. // added lazily on first reference.
  469. countUnresolvedOperands();
  470. }
  471. TempMDNode MDNode::clone() const {
  472. switch (getMetadataID()) {
  473. default:
  474. llvm_unreachable("Invalid MDNode subclass");
  475. #define HANDLE_MDNODE_LEAF(CLASS) \
  476. case CLASS##Kind: \
  477. return cast<CLASS>(this)->cloneImpl();
  478. #include "llvm/IR/Metadata.def"
  479. }
  480. }
  481. static bool isOperandUnresolved(Metadata *Op) {
  482. if (auto *N = dyn_cast_or_null<MDNode>(Op))
  483. return !N->isResolved();
  484. return false;
  485. }
  486. void MDNode::countUnresolvedOperands() {
  487. assert(NumUnresolved == 0 && "Expected unresolved ops to be uncounted");
  488. assert(isUniqued() && "Expected this to be uniqued");
  489. NumUnresolved = count_if(operands(), isOperandUnresolved);
  490. }
  491. void MDNode::makeUniqued() {
  492. assert(isTemporary() && "Expected this to be temporary");
  493. assert(!isResolved() && "Expected this to be unresolved");
  494. // Enable uniquing callbacks.
  495. for (auto &Op : mutable_operands())
  496. Op.reset(Op.get(), this);
  497. // Make this 'uniqued'.
  498. Storage = Uniqued;
  499. countUnresolvedOperands();
  500. if (!NumUnresolved) {
  501. dropReplaceableUses();
  502. assert(isResolved() && "Expected this to be resolved");
  503. }
  504. assert(isUniqued() && "Expected this to be uniqued");
  505. }
  506. void MDNode::makeDistinct() {
  507. assert(isTemporary() && "Expected this to be temporary");
  508. assert(!isResolved() && "Expected this to be unresolved");
  509. // Drop RAUW support and store as a distinct node.
  510. dropReplaceableUses();
  511. storeDistinctInContext();
  512. assert(isDistinct() && "Expected this to be distinct");
  513. assert(isResolved() && "Expected this to be resolved");
  514. }
  515. void MDNode::resolve() {
  516. assert(isUniqued() && "Expected this to be uniqued");
  517. assert(!isResolved() && "Expected this to be unresolved");
  518. NumUnresolved = 0;
  519. dropReplaceableUses();
  520. assert(isResolved() && "Expected this to be resolved");
  521. }
  522. void MDNode::dropReplaceableUses() {
  523. assert(!NumUnresolved && "Unexpected unresolved operand");
  524. // Drop any RAUW support.
  525. if (Context.hasReplaceableUses())
  526. Context.takeReplaceableUses()->resolveAllUses();
  527. }
  528. void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
  529. assert(isUniqued() && "Expected this to be uniqued");
  530. assert(NumUnresolved != 0 && "Expected unresolved operands");
  531. // Check if an operand was resolved.
  532. if (!isOperandUnresolved(Old)) {
  533. if (isOperandUnresolved(New))
  534. // An operand was un-resolved!
  535. ++NumUnresolved;
  536. } else if (!isOperandUnresolved(New))
  537. decrementUnresolvedOperandCount();
  538. }
  539. void MDNode::decrementUnresolvedOperandCount() {
  540. assert(!isResolved() && "Expected this to be unresolved");
  541. if (isTemporary())
  542. return;
  543. assert(isUniqued() && "Expected this to be uniqued");
  544. if (--NumUnresolved)
  545. return;
  546. // Last unresolved operand has just been resolved.
  547. dropReplaceableUses();
  548. assert(isResolved() && "Expected this to become resolved");
  549. }
  550. void MDNode::resolveCycles() {
  551. if (isResolved())
  552. return;
  553. // Resolve this node immediately.
  554. resolve();
  555. // Resolve all operands.
  556. for (const auto &Op : operands()) {
  557. auto *N = dyn_cast_or_null<MDNode>(Op);
  558. if (!N)
  559. continue;
  560. assert(!N->isTemporary() &&
  561. "Expected all forward declarations to be resolved");
  562. if (!N->isResolved())
  563. N->resolveCycles();
  564. }
  565. }
  566. static bool hasSelfReference(MDNode *N) {
  567. return llvm::is_contained(N->operands(), N);
  568. }
  569. MDNode *MDNode::replaceWithPermanentImpl() {
  570. switch (getMetadataID()) {
  571. default:
  572. // If this type isn't uniquable, replace with a distinct node.
  573. return replaceWithDistinctImpl();
  574. #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
  575. case CLASS##Kind: \
  576. break;
  577. #include "llvm/IR/Metadata.def"
  578. }
  579. // Even if this type is uniquable, self-references have to be distinct.
  580. if (hasSelfReference(this))
  581. return replaceWithDistinctImpl();
  582. return replaceWithUniquedImpl();
  583. }
  584. MDNode *MDNode::replaceWithUniquedImpl() {
  585. // Try to uniquify in place.
  586. MDNode *UniquedNode = uniquify();
  587. if (UniquedNode == this) {
  588. makeUniqued();
  589. return this;
  590. }
  591. // Collision, so RAUW instead.
  592. replaceAllUsesWith(UniquedNode);
  593. deleteAsSubclass();
  594. return UniquedNode;
  595. }
  596. MDNode *MDNode::replaceWithDistinctImpl() {
  597. makeDistinct();
  598. return this;
  599. }
  600. void MDTuple::recalculateHash() {
  601. setHash(MDTupleInfo::KeyTy::calculateHash(this));
  602. }
  603. void MDNode::dropAllReferences() {
  604. for (unsigned I = 0, E = NumOperands; I != E; ++I)
  605. setOperand(I, nullptr);
  606. if (Context.hasReplaceableUses()) {
  607. Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
  608. (void)Context.takeReplaceableUses();
  609. }
  610. }
  611. void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
  612. unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
  613. assert(Op < getNumOperands() && "Expected valid operand");
  614. if (!isUniqued()) {
  615. // This node is not uniqued. Just set the operand and be done with it.
  616. setOperand(Op, New);
  617. return;
  618. }
  619. // This node is uniqued.
  620. eraseFromStore();
  621. Metadata *Old = getOperand(Op);
  622. setOperand(Op, New);
  623. // Drop uniquing for self-reference cycles and deleted constants.
  624. if (New == this || (!New && Old && isa<ConstantAsMetadata>(Old))) {
  625. if (!isResolved())
  626. resolve();
  627. storeDistinctInContext();
  628. return;
  629. }
  630. // Re-unique the node.
  631. auto *Uniqued = uniquify();
  632. if (Uniqued == this) {
  633. if (!isResolved())
  634. resolveAfterOperandChange(Old, New);
  635. return;
  636. }
  637. // Collision.
  638. if (!isResolved()) {
  639. // Still unresolved, so RAUW.
  640. //
  641. // First, clear out all operands to prevent any recursion (similar to
  642. // dropAllReferences(), but we still need the use-list).
  643. for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
  644. setOperand(O, nullptr);
  645. if (Context.hasReplaceableUses())
  646. Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
  647. deleteAsSubclass();
  648. return;
  649. }
  650. // Store in non-uniqued form if RAUW isn't possible.
  651. storeDistinctInContext();
  652. }
  653. void MDNode::deleteAsSubclass() {
  654. switch (getMetadataID()) {
  655. default:
  656. llvm_unreachable("Invalid subclass of MDNode");
  657. #define HANDLE_MDNODE_LEAF(CLASS) \
  658. case CLASS##Kind: \
  659. delete cast<CLASS>(this); \
  660. break;
  661. #include "llvm/IR/Metadata.def"
  662. }
  663. }
  664. template <class T, class InfoT>
  665. static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
  666. if (T *U = getUniqued(Store, N))
  667. return U;
  668. Store.insert(N);
  669. return N;
  670. }
  671. template <class NodeTy> struct MDNode::HasCachedHash {
  672. using Yes = char[1];
  673. using No = char[2];
  674. template <class U, U Val> struct SFINAE {};
  675. template <class U>
  676. static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
  677. template <class U> static No &check(...);
  678. static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
  679. };
  680. MDNode *MDNode::uniquify() {
  681. assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
  682. // Try to insert into uniquing store.
  683. switch (getMetadataID()) {
  684. default:
  685. llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
  686. #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
  687. case CLASS##Kind: { \
  688. CLASS *SubclassThis = cast<CLASS>(this); \
  689. std::integral_constant<bool, HasCachedHash<CLASS>::value> \
  690. ShouldRecalculateHash; \
  691. dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
  692. return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
  693. }
  694. #include "llvm/IR/Metadata.def"
  695. }
  696. }
  697. void MDNode::eraseFromStore() {
  698. switch (getMetadataID()) {
  699. default:
  700. llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
  701. #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
  702. case CLASS##Kind: \
  703. getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
  704. break;
  705. #include "llvm/IR/Metadata.def"
  706. }
  707. }
  708. MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
  709. StorageType Storage, bool ShouldCreate) {
  710. unsigned Hash = 0;
  711. if (Storage == Uniqued) {
  712. MDTupleInfo::KeyTy Key(MDs);
  713. if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
  714. return N;
  715. if (!ShouldCreate)
  716. return nullptr;
  717. Hash = Key.getHash();
  718. } else {
  719. assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
  720. }
  721. return storeImpl(new (MDs.size()) MDTuple(Context, Storage, Hash, MDs),
  722. Storage, Context.pImpl->MDTuples);
  723. }
  724. void MDNode::deleteTemporary(MDNode *N) {
  725. assert(N->isTemporary() && "Expected temporary node");
  726. N->replaceAllUsesWith(nullptr);
  727. N->deleteAsSubclass();
  728. }
  729. void MDNode::storeDistinctInContext() {
  730. assert(!Context.hasReplaceableUses() && "Unexpected replaceable uses");
  731. assert(!NumUnresolved && "Unexpected unresolved nodes");
  732. Storage = Distinct;
  733. assert(isResolved() && "Expected this to be resolved");
  734. // Reset the hash.
  735. switch (getMetadataID()) {
  736. default:
  737. llvm_unreachable("Invalid subclass of MDNode");
  738. #define HANDLE_MDNODE_LEAF(CLASS) \
  739. case CLASS##Kind: { \
  740. std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
  741. dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
  742. break; \
  743. }
  744. #include "llvm/IR/Metadata.def"
  745. }
  746. getContext().pImpl->DistinctMDNodes.push_back(this);
  747. }
  748. void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
  749. if (getOperand(I) == New)
  750. return;
  751. if (!isUniqued()) {
  752. setOperand(I, New);
  753. return;
  754. }
  755. handleChangedOperand(mutable_begin() + I, New);
  756. }
  757. void MDNode::setOperand(unsigned I, Metadata *New) {
  758. assert(I < NumOperands);
  759. mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
  760. }
  761. /// Get a node or a self-reference that looks like it.
  762. ///
  763. /// Special handling for finding self-references, for use by \a
  764. /// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
  765. /// when self-referencing nodes were still uniqued. If the first operand has
  766. /// the same operands as \c Ops, return the first operand instead.
  767. static MDNode *getOrSelfReference(LLVMContext &Context,
  768. ArrayRef<Metadata *> Ops) {
  769. if (!Ops.empty())
  770. if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
  771. if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
  772. for (unsigned I = 1, E = Ops.size(); I != E; ++I)
  773. if (Ops[I] != N->getOperand(I))
  774. return MDNode::get(Context, Ops);
  775. return N;
  776. }
  777. return MDNode::get(Context, Ops);
  778. }
  779. MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
  780. if (!A)
  781. return B;
  782. if (!B)
  783. return A;
  784. SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
  785. MDs.insert(B->op_begin(), B->op_end());
  786. // FIXME: This preserves long-standing behaviour, but is it really the right
  787. // behaviour? Or was that an unintended side-effect of node uniquing?
  788. return getOrSelfReference(A->getContext(), MDs.getArrayRef());
  789. }
  790. MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
  791. if (!A || !B)
  792. return nullptr;
  793. SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
  794. SmallPtrSet<Metadata *, 4> BSet(B->op_begin(), B->op_end());
  795. MDs.remove_if([&](Metadata *MD) { return !BSet.count(MD); });
  796. // FIXME: This preserves long-standing behaviour, but is it really the right
  797. // behaviour? Or was that an unintended side-effect of node uniquing?
  798. return getOrSelfReference(A->getContext(), MDs.getArrayRef());
  799. }
  800. MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
  801. if (!A || !B)
  802. return nullptr;
  803. // Take the intersection of domains then union the scopes
  804. // within those domains
  805. SmallPtrSet<const MDNode *, 16> ADomains;
  806. SmallPtrSet<const MDNode *, 16> IntersectDomains;
  807. SmallSetVector<Metadata *, 4> MDs;
  808. for (const MDOperand &MDOp : A->operands())
  809. if (const MDNode *NAMD = dyn_cast<MDNode>(MDOp))
  810. if (const MDNode *Domain = AliasScopeNode(NAMD).getDomain())
  811. ADomains.insert(Domain);
  812. for (const MDOperand &MDOp : B->operands())
  813. if (const MDNode *NAMD = dyn_cast<MDNode>(MDOp))
  814. if (const MDNode *Domain = AliasScopeNode(NAMD).getDomain())
  815. if (ADomains.contains(Domain)) {
  816. IntersectDomains.insert(Domain);
  817. MDs.insert(MDOp);
  818. }
  819. for (const MDOperand &MDOp : A->operands())
  820. if (const MDNode *NAMD = dyn_cast<MDNode>(MDOp))
  821. if (const MDNode *Domain = AliasScopeNode(NAMD).getDomain())
  822. if (IntersectDomains.contains(Domain))
  823. MDs.insert(MDOp);
  824. return MDs.empty() ? nullptr
  825. : getOrSelfReference(A->getContext(), MDs.getArrayRef());
  826. }
  827. MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
  828. if (!A || !B)
  829. return nullptr;
  830. APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
  831. APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
  832. if (AVal < BVal)
  833. return A;
  834. return B;
  835. }
  836. static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
  837. return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
  838. }
  839. static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
  840. return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
  841. }
  842. static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
  843. ConstantInt *Low, ConstantInt *High) {
  844. ConstantRange NewRange(Low->getValue(), High->getValue());
  845. unsigned Size = EndPoints.size();
  846. APInt LB = EndPoints[Size - 2]->getValue();
  847. APInt LE = EndPoints[Size - 1]->getValue();
  848. ConstantRange LastRange(LB, LE);
  849. if (canBeMerged(NewRange, LastRange)) {
  850. ConstantRange Union = LastRange.unionWith(NewRange);
  851. Type *Ty = High->getType();
  852. EndPoints[Size - 2] =
  853. cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
  854. EndPoints[Size - 1] =
  855. cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
  856. return true;
  857. }
  858. return false;
  859. }
  860. static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
  861. ConstantInt *Low, ConstantInt *High) {
  862. if (!EndPoints.empty())
  863. if (tryMergeRange(EndPoints, Low, High))
  864. return;
  865. EndPoints.push_back(Low);
  866. EndPoints.push_back(High);
  867. }
  868. MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
  869. // Given two ranges, we want to compute the union of the ranges. This
  870. // is slightly complicated by having to combine the intervals and merge
  871. // the ones that overlap.
  872. if (!A || !B)
  873. return nullptr;
  874. if (A == B)
  875. return A;
  876. // First, walk both lists in order of the lower boundary of each interval.
  877. // At each step, try to merge the new interval to the last one we adedd.
  878. SmallVector<ConstantInt *, 4> EndPoints;
  879. int AI = 0;
  880. int BI = 0;
  881. int AN = A->getNumOperands() / 2;
  882. int BN = B->getNumOperands() / 2;
  883. while (AI < AN && BI < BN) {
  884. ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
  885. ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
  886. if (ALow->getValue().slt(BLow->getValue())) {
  887. addRange(EndPoints, ALow,
  888. mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
  889. ++AI;
  890. } else {
  891. addRange(EndPoints, BLow,
  892. mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
  893. ++BI;
  894. }
  895. }
  896. while (AI < AN) {
  897. addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
  898. mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
  899. ++AI;
  900. }
  901. while (BI < BN) {
  902. addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
  903. mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
  904. ++BI;
  905. }
  906. // If we have more than 2 ranges (4 endpoints) we have to try to merge
  907. // the last and first ones.
  908. unsigned Size = EndPoints.size();
  909. if (Size > 4) {
  910. ConstantInt *FB = EndPoints[0];
  911. ConstantInt *FE = EndPoints[1];
  912. if (tryMergeRange(EndPoints, FB, FE)) {
  913. for (unsigned i = 0; i < Size - 2; ++i) {
  914. EndPoints[i] = EndPoints[i + 2];
  915. }
  916. EndPoints.resize(Size - 2);
  917. }
  918. }
  919. // If in the end we have a single range, it is possible that it is now the
  920. // full range. Just drop the metadata in that case.
  921. if (EndPoints.size() == 2) {
  922. ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
  923. if (Range.isFullSet())
  924. return nullptr;
  925. }
  926. SmallVector<Metadata *, 4> MDs;
  927. MDs.reserve(EndPoints.size());
  928. for (auto *I : EndPoints)
  929. MDs.push_back(ConstantAsMetadata::get(I));
  930. return MDNode::get(A->getContext(), MDs);
  931. }
  932. MDNode *MDNode::getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B) {
  933. if (!A || !B)
  934. return nullptr;
  935. ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
  936. ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
  937. if (AVal->getZExtValue() < BVal->getZExtValue())
  938. return A;
  939. return B;
  940. }
  941. //===----------------------------------------------------------------------===//
  942. // NamedMDNode implementation.
  943. //
  944. static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
  945. return *(SmallVector<TrackingMDRef, 4> *)Operands;
  946. }
  947. NamedMDNode::NamedMDNode(const Twine &N)
  948. : Name(N.str()), Operands(new SmallVector<TrackingMDRef, 4>()) {}
  949. NamedMDNode::~NamedMDNode() {
  950. dropAllReferences();
  951. delete &getNMDOps(Operands);
  952. }
  953. unsigned NamedMDNode::getNumOperands() const {
  954. return (unsigned)getNMDOps(Operands).size();
  955. }
  956. MDNode *NamedMDNode::getOperand(unsigned i) const {
  957. assert(i < getNumOperands() && "Invalid Operand number!");
  958. auto *N = getNMDOps(Operands)[i].get();
  959. return cast_or_null<MDNode>(N);
  960. }
  961. void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
  962. void NamedMDNode::setOperand(unsigned I, MDNode *New) {
  963. assert(I < getNumOperands() && "Invalid operand number");
  964. getNMDOps(Operands)[I].reset(New);
  965. }
  966. void NamedMDNode::eraseFromParent() { getParent()->eraseNamedMetadata(this); }
  967. void NamedMDNode::clearOperands() { getNMDOps(Operands).clear(); }
  968. StringRef NamedMDNode::getName() const { return StringRef(Name); }
  969. //===----------------------------------------------------------------------===//
  970. // Instruction Metadata method implementations.
  971. //
  972. MDNode *MDAttachments::lookup(unsigned ID) const {
  973. for (const auto &A : Attachments)
  974. if (A.MDKind == ID)
  975. return A.Node;
  976. return nullptr;
  977. }
  978. void MDAttachments::get(unsigned ID, SmallVectorImpl<MDNode *> &Result) const {
  979. for (const auto &A : Attachments)
  980. if (A.MDKind == ID)
  981. Result.push_back(A.Node);
  982. }
  983. void MDAttachments::getAll(
  984. SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
  985. for (const auto &A : Attachments)
  986. Result.emplace_back(A.MDKind, A.Node);
  987. // Sort the resulting array so it is stable with respect to metadata IDs. We
  988. // need to preserve the original insertion order though.
  989. if (Result.size() > 1)
  990. llvm::stable_sort(Result, less_first());
  991. }
  992. void MDAttachments::set(unsigned ID, MDNode *MD) {
  993. erase(ID);
  994. if (MD)
  995. insert(ID, *MD);
  996. }
  997. void MDAttachments::insert(unsigned ID, MDNode &MD) {
  998. Attachments.push_back({ID, TrackingMDNodeRef(&MD)});
  999. }
  1000. bool MDAttachments::erase(unsigned ID) {
  1001. if (empty())
  1002. return false;
  1003. // Common case is one value.
  1004. if (Attachments.size() == 1 && Attachments.back().MDKind == ID) {
  1005. Attachments.pop_back();
  1006. return true;
  1007. }
  1008. auto OldSize = Attachments.size();
  1009. llvm::erase_if(Attachments,
  1010. [ID](const Attachment &A) { return A.MDKind == ID; });
  1011. return OldSize != Attachments.size();
  1012. }
  1013. MDNode *Value::getMetadata(unsigned KindID) const {
  1014. if (!hasMetadata())
  1015. return nullptr;
  1016. const auto &Info = getContext().pImpl->ValueMetadata[this];
  1017. assert(!Info.empty() && "bit out of sync with hash table");
  1018. return Info.lookup(KindID);
  1019. }
  1020. MDNode *Value::getMetadata(StringRef Kind) const {
  1021. if (!hasMetadata())
  1022. return nullptr;
  1023. const auto &Info = getContext().pImpl->ValueMetadata[this];
  1024. assert(!Info.empty() && "bit out of sync with hash table");
  1025. return Info.lookup(getContext().getMDKindID(Kind));
  1026. }
  1027. void Value::getMetadata(unsigned KindID, SmallVectorImpl<MDNode *> &MDs) const {
  1028. if (hasMetadata())
  1029. getContext().pImpl->ValueMetadata[this].get(KindID, MDs);
  1030. }
  1031. void Value::getMetadata(StringRef Kind, SmallVectorImpl<MDNode *> &MDs) const {
  1032. if (hasMetadata())
  1033. getMetadata(getContext().getMDKindID(Kind), MDs);
  1034. }
  1035. void Value::getAllMetadata(
  1036. SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
  1037. if (hasMetadata()) {
  1038. assert(getContext().pImpl->ValueMetadata.count(this) &&
  1039. "bit out of sync with hash table");
  1040. const auto &Info = getContext().pImpl->ValueMetadata.find(this)->second;
  1041. assert(!Info.empty() && "Shouldn't have called this");
  1042. Info.getAll(MDs);
  1043. }
  1044. }
  1045. void Value::setMetadata(unsigned KindID, MDNode *Node) {
  1046. assert(isa<Instruction>(this) || isa<GlobalObject>(this));
  1047. // Handle the case when we're adding/updating metadata on a value.
  1048. if (Node) {
  1049. auto &Info = getContext().pImpl->ValueMetadata[this];
  1050. assert(!Info.empty() == HasMetadata && "bit out of sync with hash table");
  1051. if (Info.empty())
  1052. HasMetadata = true;
  1053. Info.set(KindID, Node);
  1054. return;
  1055. }
  1056. // Otherwise, we're removing metadata from an instruction.
  1057. assert((HasMetadata == (getContext().pImpl->ValueMetadata.count(this) > 0)) &&
  1058. "bit out of sync with hash table");
  1059. if (!HasMetadata)
  1060. return; // Nothing to remove!
  1061. auto &Info = getContext().pImpl->ValueMetadata[this];
  1062. // Handle removal of an existing value.
  1063. Info.erase(KindID);
  1064. if (!Info.empty())
  1065. return;
  1066. getContext().pImpl->ValueMetadata.erase(this);
  1067. HasMetadata = false;
  1068. }
  1069. void Value::setMetadata(StringRef Kind, MDNode *Node) {
  1070. if (!Node && !HasMetadata)
  1071. return;
  1072. setMetadata(getContext().getMDKindID(Kind), Node);
  1073. }
  1074. void Value::addMetadata(unsigned KindID, MDNode &MD) {
  1075. assert(isa<Instruction>(this) || isa<GlobalObject>(this));
  1076. if (!HasMetadata)
  1077. HasMetadata = true;
  1078. getContext().pImpl->ValueMetadata[this].insert(KindID, MD);
  1079. }
  1080. void Value::addMetadata(StringRef Kind, MDNode &MD) {
  1081. addMetadata(getContext().getMDKindID(Kind), MD);
  1082. }
  1083. bool Value::eraseMetadata(unsigned KindID) {
  1084. // Nothing to unset.
  1085. if (!HasMetadata)
  1086. return false;
  1087. auto &Store = getContext().pImpl->ValueMetadata[this];
  1088. bool Changed = Store.erase(KindID);
  1089. if (Store.empty())
  1090. clearMetadata();
  1091. return Changed;
  1092. }
  1093. void Value::clearMetadata() {
  1094. if (!HasMetadata)
  1095. return;
  1096. assert(getContext().pImpl->ValueMetadata.count(this) &&
  1097. "bit out of sync with hash table");
  1098. getContext().pImpl->ValueMetadata.erase(this);
  1099. HasMetadata = false;
  1100. }
  1101. void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
  1102. if (!Node && !hasMetadata())
  1103. return;
  1104. setMetadata(getContext().getMDKindID(Kind), Node);
  1105. }
  1106. MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
  1107. return getMetadataImpl(getContext().getMDKindID(Kind));
  1108. }
  1109. void Instruction::dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs) {
  1110. if (!Value::hasMetadata())
  1111. return; // Nothing to remove!
  1112. if (KnownIDs.empty()) {
  1113. // Just drop our entry at the store.
  1114. clearMetadata();
  1115. return;
  1116. }
  1117. SmallSet<unsigned, 4> KnownSet;
  1118. KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
  1119. auto &MetadataStore = getContext().pImpl->ValueMetadata;
  1120. auto &Info = MetadataStore[this];
  1121. assert(!Info.empty() && "bit out of sync with hash table");
  1122. Info.remove_if([&KnownSet](const MDAttachments::Attachment &I) {
  1123. return !KnownSet.count(I.MDKind);
  1124. });
  1125. if (Info.empty()) {
  1126. // Drop our entry at the store.
  1127. clearMetadata();
  1128. }
  1129. }
  1130. void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
  1131. if (!Node && !hasMetadata())
  1132. return;
  1133. // Handle 'dbg' as a special case since it is not stored in the hash table.
  1134. if (KindID == LLVMContext::MD_dbg) {
  1135. DbgLoc = DebugLoc(Node);
  1136. return;
  1137. }
  1138. Value::setMetadata(KindID, Node);
  1139. }
  1140. void Instruction::addAnnotationMetadata(StringRef Name) {
  1141. MDBuilder MDB(getContext());
  1142. auto *Existing = getMetadata(LLVMContext::MD_annotation);
  1143. SmallVector<Metadata *, 4> Names;
  1144. bool AppendName = true;
  1145. if (Existing) {
  1146. auto *Tuple = cast<MDTuple>(Existing);
  1147. for (auto &N : Tuple->operands()) {
  1148. if (cast<MDString>(N.get())->getString() == Name)
  1149. AppendName = false;
  1150. Names.push_back(N.get());
  1151. }
  1152. }
  1153. if (AppendName)
  1154. Names.push_back(MDB.createString(Name));
  1155. MDNode *MD = MDTuple::get(getContext(), Names);
  1156. setMetadata(LLVMContext::MD_annotation, MD);
  1157. }
  1158. AAMDNodes Instruction::getAAMetadata() const {
  1159. AAMDNodes Result;
  1160. Result.TBAA = getMetadata(LLVMContext::MD_tbaa);
  1161. Result.TBAAStruct = getMetadata(LLVMContext::MD_tbaa_struct);
  1162. Result.Scope = getMetadata(LLVMContext::MD_alias_scope);
  1163. Result.NoAlias = getMetadata(LLVMContext::MD_noalias);
  1164. return Result;
  1165. }
  1166. void Instruction::setAAMetadata(const AAMDNodes &N) {
  1167. setMetadata(LLVMContext::MD_tbaa, N.TBAA);
  1168. setMetadata(LLVMContext::MD_tbaa_struct, N.TBAAStruct);
  1169. setMetadata(LLVMContext::MD_alias_scope, N.Scope);
  1170. setMetadata(LLVMContext::MD_noalias, N.NoAlias);
  1171. }
  1172. MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
  1173. // Handle 'dbg' as a special case since it is not stored in the hash table.
  1174. if (KindID == LLVMContext::MD_dbg)
  1175. return DbgLoc.getAsMDNode();
  1176. return Value::getMetadata(KindID);
  1177. }
  1178. void Instruction::getAllMetadataImpl(
  1179. SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
  1180. Result.clear();
  1181. // Handle 'dbg' as a special case since it is not stored in the hash table.
  1182. if (DbgLoc) {
  1183. Result.push_back(
  1184. std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
  1185. }
  1186. Value::getAllMetadata(Result);
  1187. }
  1188. bool Instruction::extractProfMetadata(uint64_t &TrueVal,
  1189. uint64_t &FalseVal) const {
  1190. assert(
  1191. (getOpcode() == Instruction::Br || getOpcode() == Instruction::Select) &&
  1192. "Looking for branch weights on something besides branch or select");
  1193. auto *ProfileData = getMetadata(LLVMContext::MD_prof);
  1194. if (!ProfileData || ProfileData->getNumOperands() != 3)
  1195. return false;
  1196. auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
  1197. if (!ProfDataName || !ProfDataName->getString().equals("branch_weights"))
  1198. return false;
  1199. auto *CITrue = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
  1200. auto *CIFalse = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
  1201. if (!CITrue || !CIFalse)
  1202. return false;
  1203. TrueVal = CITrue->getValue().getZExtValue();
  1204. FalseVal = CIFalse->getValue().getZExtValue();
  1205. return true;
  1206. }
  1207. bool Instruction::extractProfTotalWeight(uint64_t &TotalVal) const {
  1208. assert(
  1209. (getOpcode() == Instruction::Br || getOpcode() == Instruction::Select ||
  1210. getOpcode() == Instruction::Call || getOpcode() == Instruction::Invoke ||
  1211. getOpcode() == Instruction::IndirectBr ||
  1212. getOpcode() == Instruction::Switch) &&
  1213. "Looking for branch weights on something besides branch");
  1214. TotalVal = 0;
  1215. auto *ProfileData = getMetadata(LLVMContext::MD_prof);
  1216. if (!ProfileData)
  1217. return false;
  1218. auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
  1219. if (!ProfDataName)
  1220. return false;
  1221. if (ProfDataName->getString().equals("branch_weights")) {
  1222. TotalVal = 0;
  1223. for (unsigned i = 1; i < ProfileData->getNumOperands(); i++) {
  1224. auto *V = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i));
  1225. if (!V)
  1226. return false;
  1227. TotalVal += V->getValue().getZExtValue();
  1228. }
  1229. return true;
  1230. } else if (ProfDataName->getString().equals("VP") &&
  1231. ProfileData->getNumOperands() > 3) {
  1232. TotalVal = mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2))
  1233. ->getValue()
  1234. .getZExtValue();
  1235. return true;
  1236. }
  1237. return false;
  1238. }
  1239. void GlobalObject::copyMetadata(const GlobalObject *Other, unsigned Offset) {
  1240. SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
  1241. Other->getAllMetadata(MDs);
  1242. for (auto &MD : MDs) {
  1243. // We need to adjust the type metadata offset.
  1244. if (Offset != 0 && MD.first == LLVMContext::MD_type) {
  1245. auto *OffsetConst = cast<ConstantInt>(
  1246. cast<ConstantAsMetadata>(MD.second->getOperand(0))->getValue());
  1247. Metadata *TypeId = MD.second->getOperand(1);
  1248. auto *NewOffsetMD = ConstantAsMetadata::get(ConstantInt::get(
  1249. OffsetConst->getType(), OffsetConst->getValue() + Offset));
  1250. addMetadata(LLVMContext::MD_type,
  1251. *MDNode::get(getContext(), {NewOffsetMD, TypeId}));
  1252. continue;
  1253. }
  1254. // If an offset adjustment was specified we need to modify the DIExpression
  1255. // to prepend the adjustment:
  1256. // !DIExpression(DW_OP_plus, Offset, [original expr])
  1257. auto *Attachment = MD.second;
  1258. if (Offset != 0 && MD.first == LLVMContext::MD_dbg) {
  1259. DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(Attachment);
  1260. DIExpression *E = nullptr;
  1261. if (!GV) {
  1262. auto *GVE = cast<DIGlobalVariableExpression>(Attachment);
  1263. GV = GVE->getVariable();
  1264. E = GVE->getExpression();
  1265. }
  1266. ArrayRef<uint64_t> OrigElements;
  1267. if (E)
  1268. OrigElements = E->getElements();
  1269. std::vector<uint64_t> Elements(OrigElements.size() + 2);
  1270. Elements[0] = dwarf::DW_OP_plus_uconst;
  1271. Elements[1] = Offset;
  1272. llvm::copy(OrigElements, Elements.begin() + 2);
  1273. E = DIExpression::get(getContext(), Elements);
  1274. Attachment = DIGlobalVariableExpression::get(getContext(), GV, E);
  1275. }
  1276. addMetadata(MD.first, *Attachment);
  1277. }
  1278. }
  1279. void GlobalObject::addTypeMetadata(unsigned Offset, Metadata *TypeID) {
  1280. addMetadata(
  1281. LLVMContext::MD_type,
  1282. *MDTuple::get(getContext(),
  1283. {ConstantAsMetadata::get(ConstantInt::get(
  1284. Type::getInt64Ty(getContext()), Offset)),
  1285. TypeID}));
  1286. }
  1287. void GlobalObject::setVCallVisibilityMetadata(VCallVisibility Visibility) {
  1288. // Remove any existing vcall visibility metadata first in case we are
  1289. // updating.
  1290. eraseMetadata(LLVMContext::MD_vcall_visibility);
  1291. addMetadata(LLVMContext::MD_vcall_visibility,
  1292. *MDNode::get(getContext(),
  1293. {ConstantAsMetadata::get(ConstantInt::get(
  1294. Type::getInt64Ty(getContext()), Visibility))}));
  1295. }
  1296. GlobalObject::VCallVisibility GlobalObject::getVCallVisibility() const {
  1297. if (MDNode *MD = getMetadata(LLVMContext::MD_vcall_visibility)) {
  1298. uint64_t Val = cast<ConstantInt>(
  1299. cast<ConstantAsMetadata>(MD->getOperand(0))->getValue())
  1300. ->getZExtValue();
  1301. assert(Val <= 2 && "unknown vcall visibility!");
  1302. return (VCallVisibility)Val;
  1303. }
  1304. return VCallVisibility::VCallVisibilityPublic;
  1305. }
  1306. void Function::setSubprogram(DISubprogram *SP) {
  1307. setMetadata(LLVMContext::MD_dbg, SP);
  1308. }
  1309. DISubprogram *Function::getSubprogram() const {
  1310. return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));
  1311. }
  1312. bool Function::isDebugInfoForProfiling() const {
  1313. if (DISubprogram *SP = getSubprogram()) {
  1314. if (DICompileUnit *CU = SP->getUnit()) {
  1315. return CU->getDebugInfoForProfiling();
  1316. }
  1317. }
  1318. return false;
  1319. }
  1320. void GlobalVariable::addDebugInfo(DIGlobalVariableExpression *GV) {
  1321. addMetadata(LLVMContext::MD_dbg, *GV);
  1322. }
  1323. void GlobalVariable::getDebugInfo(
  1324. SmallVectorImpl<DIGlobalVariableExpression *> &GVs) const {
  1325. SmallVector<MDNode *, 1> MDs;
  1326. getMetadata(LLVMContext::MD_dbg, MDs);
  1327. for (MDNode *MD : MDs)
  1328. GVs.push_back(cast<DIGlobalVariableExpression>(MD));
  1329. }