Metadata.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648
  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/STLExtras.h"
  20. #include "llvm/ADT/SetVector.h"
  21. #include "llvm/ADT/SmallPtrSet.h"
  22. #include "llvm/ADT/SmallSet.h"
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/ADT/StringMap.h"
  25. #include "llvm/ADT/StringRef.h"
  26. #include "llvm/ADT/Twine.h"
  27. #include "llvm/IR/Argument.h"
  28. #include "llvm/IR/BasicBlock.h"
  29. #include "llvm/IR/Constant.h"
  30. #include "llvm/IR/ConstantRange.h"
  31. #include "llvm/IR/Constants.h"
  32. #include "llvm/IR/DebugInfoMetadata.h"
  33. #include "llvm/IR/DebugLoc.h"
  34. #include "llvm/IR/Function.h"
  35. #include "llvm/IR/GlobalObject.h"
  36. #include "llvm/IR/GlobalVariable.h"
  37. #include "llvm/IR/Instruction.h"
  38. #include "llvm/IR/LLVMContext.h"
  39. #include "llvm/IR/MDBuilder.h"
  40. #include "llvm/IR/Module.h"
  41. #include "llvm/IR/ProfDataUtils.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, std::nullopt);
  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, std::nullopt);
  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::SalvageDebugInfo(const Constant &C) {
  221. if (!C.isUsedByMetadata()) {
  222. return;
  223. }
  224. LLVMContext &Context = C.getType()->getContext();
  225. auto &Store = Context.pImpl->ValuesAsMetadata;
  226. auto I = Store.find(&C);
  227. ValueAsMetadata *MD = I->second;
  228. using UseTy =
  229. std::pair<void *, std::pair<MetadataTracking::OwnerTy, uint64_t>>;
  230. // Copy out uses and update value of Constant used by debug info metadata with undef below
  231. SmallVector<UseTy, 8> Uses(MD->UseMap.begin(), MD->UseMap.end());
  232. for (const auto &Pair : Uses) {
  233. MetadataTracking::OwnerTy Owner = Pair.second.first;
  234. if (!Owner)
  235. continue;
  236. if (!Owner.is<Metadata *>())
  237. continue;
  238. auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
  239. if (!OwnerMD)
  240. continue;
  241. if (isa<DINode>(OwnerMD)) {
  242. OwnerMD->handleChangedOperand(
  243. Pair.first, ValueAsMetadata::get(UndefValue::get(C.getType())));
  244. }
  245. }
  246. }
  247. void ReplaceableMetadataImpl::replaceAllUsesWith(Metadata *MD) {
  248. if (UseMap.empty())
  249. return;
  250. // Copy out uses since UseMap will get touched below.
  251. using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
  252. SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
  253. llvm::sort(Uses, llvm::less_second());
  254. for (const auto &Pair : Uses) {
  255. // Check that this Ref hasn't disappeared after RAUW (when updating a
  256. // previous Ref).
  257. if (!UseMap.count(Pair.first))
  258. continue;
  259. OwnerTy Owner = Pair.second.first;
  260. if (!Owner) {
  261. // Update unowned tracking references directly.
  262. Metadata *&Ref = *static_cast<Metadata **>(Pair.first);
  263. Ref = MD;
  264. if (MD)
  265. MetadataTracking::track(Ref);
  266. UseMap.erase(Pair.first);
  267. continue;
  268. }
  269. // Check for MetadataAsValue.
  270. if (Owner.is<MetadataAsValue *>()) {
  271. Owner.get<MetadataAsValue *>()->handleChangedMetadata(MD);
  272. continue;
  273. }
  274. // There's a Metadata owner -- dispatch.
  275. Metadata *OwnerMD = Owner.get<Metadata *>();
  276. switch (OwnerMD->getMetadataID()) {
  277. #define HANDLE_METADATA_LEAF(CLASS) \
  278. case Metadata::CLASS##Kind: \
  279. cast<CLASS>(OwnerMD)->handleChangedOperand(Pair.first, MD); \
  280. continue;
  281. #include "llvm/IR/Metadata.def"
  282. default:
  283. llvm_unreachable("Invalid metadata subclass");
  284. }
  285. }
  286. assert(UseMap.empty() && "Expected all uses to be replaced");
  287. }
  288. void ReplaceableMetadataImpl::resolveAllUses(bool ResolveUsers) {
  289. if (UseMap.empty())
  290. return;
  291. if (!ResolveUsers) {
  292. UseMap.clear();
  293. return;
  294. }
  295. // Copy out uses since UseMap could get touched below.
  296. using UseTy = std::pair<void *, std::pair<OwnerTy, uint64_t>>;
  297. SmallVector<UseTy, 8> Uses(UseMap.begin(), UseMap.end());
  298. llvm::sort(Uses, [](const UseTy &L, const UseTy &R) {
  299. return L.second.second < R.second.second;
  300. });
  301. UseMap.clear();
  302. for (const auto &Pair : Uses) {
  303. auto Owner = Pair.second.first;
  304. if (!Owner)
  305. continue;
  306. if (Owner.is<MetadataAsValue *>())
  307. continue;
  308. // Resolve MDNodes that point at this.
  309. auto *OwnerMD = dyn_cast<MDNode>(Owner.get<Metadata *>());
  310. if (!OwnerMD)
  311. continue;
  312. if (OwnerMD->isResolved())
  313. continue;
  314. OwnerMD->decrementUnresolvedOperandCount();
  315. }
  316. }
  317. ReplaceableMetadataImpl *ReplaceableMetadataImpl::getOrCreate(Metadata &MD) {
  318. if (auto *N = dyn_cast<MDNode>(&MD))
  319. return N->isResolved() ? nullptr : N->Context.getOrCreateReplaceableUses();
  320. return dyn_cast<ValueAsMetadata>(&MD);
  321. }
  322. ReplaceableMetadataImpl *ReplaceableMetadataImpl::getIfExists(Metadata &MD) {
  323. if (auto *N = dyn_cast<MDNode>(&MD))
  324. return N->isResolved() ? nullptr : N->Context.getReplaceableUses();
  325. return dyn_cast<ValueAsMetadata>(&MD);
  326. }
  327. bool ReplaceableMetadataImpl::isReplaceable(const Metadata &MD) {
  328. if (auto *N = dyn_cast<MDNode>(&MD))
  329. return !N->isResolved();
  330. return isa<ValueAsMetadata>(&MD);
  331. }
  332. static DISubprogram *getLocalFunctionMetadata(Value *V) {
  333. assert(V && "Expected value");
  334. if (auto *A = dyn_cast<Argument>(V)) {
  335. if (auto *Fn = A->getParent())
  336. return Fn->getSubprogram();
  337. return nullptr;
  338. }
  339. if (BasicBlock *BB = cast<Instruction>(V)->getParent()) {
  340. if (auto *Fn = BB->getParent())
  341. return Fn->getSubprogram();
  342. return nullptr;
  343. }
  344. return nullptr;
  345. }
  346. ValueAsMetadata *ValueAsMetadata::get(Value *V) {
  347. assert(V && "Unexpected null Value");
  348. auto &Context = V->getContext();
  349. auto *&Entry = Context.pImpl->ValuesAsMetadata[V];
  350. if (!Entry) {
  351. assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
  352. "Expected constant or function-local value");
  353. assert(!V->IsUsedByMD && "Expected this to be the only metadata use");
  354. V->IsUsedByMD = true;
  355. if (auto *C = dyn_cast<Constant>(V))
  356. Entry = new ConstantAsMetadata(C);
  357. else
  358. Entry = new LocalAsMetadata(V);
  359. }
  360. return Entry;
  361. }
  362. ValueAsMetadata *ValueAsMetadata::getIfExists(Value *V) {
  363. assert(V && "Unexpected null Value");
  364. return V->getContext().pImpl->ValuesAsMetadata.lookup(V);
  365. }
  366. void ValueAsMetadata::handleDeletion(Value *V) {
  367. assert(V && "Expected valid value");
  368. auto &Store = V->getType()->getContext().pImpl->ValuesAsMetadata;
  369. auto I = Store.find(V);
  370. if (I == Store.end())
  371. return;
  372. // Remove old entry from the map.
  373. ValueAsMetadata *MD = I->second;
  374. assert(MD && "Expected valid metadata");
  375. assert(MD->getValue() == V && "Expected valid mapping");
  376. Store.erase(I);
  377. // Delete the metadata.
  378. MD->replaceAllUsesWith(nullptr);
  379. delete MD;
  380. }
  381. void ValueAsMetadata::handleRAUW(Value *From, Value *To) {
  382. assert(From && "Expected valid value");
  383. assert(To && "Expected valid value");
  384. assert(From != To && "Expected changed value");
  385. assert(From->getType() == To->getType() && "Unexpected type change");
  386. LLVMContext &Context = From->getType()->getContext();
  387. auto &Store = Context.pImpl->ValuesAsMetadata;
  388. auto I = Store.find(From);
  389. if (I == Store.end()) {
  390. assert(!From->IsUsedByMD && "Expected From not to be used by metadata");
  391. return;
  392. }
  393. // Remove old entry from the map.
  394. assert(From->IsUsedByMD && "Expected From to be used by metadata");
  395. From->IsUsedByMD = false;
  396. ValueAsMetadata *MD = I->second;
  397. assert(MD && "Expected valid metadata");
  398. assert(MD->getValue() == From && "Expected valid mapping");
  399. Store.erase(I);
  400. if (isa<LocalAsMetadata>(MD)) {
  401. if (auto *C = dyn_cast<Constant>(To)) {
  402. // Local became a constant.
  403. MD->replaceAllUsesWith(ConstantAsMetadata::get(C));
  404. delete MD;
  405. return;
  406. }
  407. if (getLocalFunctionMetadata(From) && getLocalFunctionMetadata(To) &&
  408. getLocalFunctionMetadata(From) != getLocalFunctionMetadata(To)) {
  409. // DISubprogram changed.
  410. MD->replaceAllUsesWith(nullptr);
  411. delete MD;
  412. return;
  413. }
  414. } else if (!isa<Constant>(To)) {
  415. // Changed to function-local value.
  416. MD->replaceAllUsesWith(nullptr);
  417. delete MD;
  418. return;
  419. }
  420. auto *&Entry = Store[To];
  421. if (Entry) {
  422. // The target already exists.
  423. MD->replaceAllUsesWith(Entry);
  424. delete MD;
  425. return;
  426. }
  427. // Update MD in place (and update the map entry).
  428. assert(!To->IsUsedByMD && "Expected this to be the only metadata use");
  429. To->IsUsedByMD = true;
  430. MD->V = To;
  431. Entry = MD;
  432. }
  433. //===----------------------------------------------------------------------===//
  434. // MDString implementation.
  435. //
  436. MDString *MDString::get(LLVMContext &Context, StringRef Str) {
  437. auto &Store = Context.pImpl->MDStringCache;
  438. auto I = Store.try_emplace(Str);
  439. auto &MapEntry = I.first->getValue();
  440. if (!I.second)
  441. return &MapEntry;
  442. MapEntry.Entry = &*I.first;
  443. return &MapEntry;
  444. }
  445. StringRef MDString::getString() const {
  446. assert(Entry && "Expected to find string map entry");
  447. return Entry->first();
  448. }
  449. //===----------------------------------------------------------------------===//
  450. // MDNode implementation.
  451. //
  452. // Assert that the MDNode types will not be unaligned by the objects
  453. // prepended to them.
  454. #define HANDLE_MDNODE_LEAF(CLASS) \
  455. static_assert( \
  456. alignof(uint64_t) >= alignof(CLASS), \
  457. "Alignment is insufficient after objects prepended to " #CLASS);
  458. #include "llvm/IR/Metadata.def"
  459. void *MDNode::operator new(size_t Size, size_t NumOps, StorageType Storage) {
  460. // uint64_t is the most aligned type we need support (ensured by static_assert
  461. // above)
  462. size_t AllocSize =
  463. alignTo(Header::getAllocSize(Storage, NumOps), alignof(uint64_t));
  464. char *Mem = reinterpret_cast<char *>(::operator new(AllocSize + Size));
  465. Header *H = new (Mem + AllocSize - sizeof(Header)) Header(NumOps, Storage);
  466. return reinterpret_cast<void *>(H + 1);
  467. }
  468. void MDNode::operator delete(void *N) {
  469. Header *H = reinterpret_cast<Header *>(N) - 1;
  470. void *Mem = H->getAllocation();
  471. H->~Header();
  472. ::operator delete(Mem);
  473. }
  474. MDNode::MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
  475. ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2)
  476. : Metadata(ID, Storage), Context(Context) {
  477. unsigned Op = 0;
  478. for (Metadata *MD : Ops1)
  479. setOperand(Op++, MD);
  480. for (Metadata *MD : Ops2)
  481. setOperand(Op++, MD);
  482. if (!isUniqued())
  483. return;
  484. // Count the unresolved operands. If there are any, RAUW support will be
  485. // added lazily on first reference.
  486. countUnresolvedOperands();
  487. }
  488. TempMDNode MDNode::clone() const {
  489. switch (getMetadataID()) {
  490. default:
  491. llvm_unreachable("Invalid MDNode subclass");
  492. #define HANDLE_MDNODE_LEAF(CLASS) \
  493. case CLASS##Kind: \
  494. return cast<CLASS>(this)->cloneImpl();
  495. #include "llvm/IR/Metadata.def"
  496. }
  497. }
  498. MDNode::Header::Header(size_t NumOps, StorageType Storage) {
  499. IsLarge = isLarge(NumOps);
  500. IsResizable = isResizable(Storage);
  501. SmallSize = getSmallSize(NumOps, IsResizable, IsLarge);
  502. if (IsLarge) {
  503. SmallNumOps = 0;
  504. new (getLargePtr()) LargeStorageVector();
  505. getLarge().resize(NumOps);
  506. return;
  507. }
  508. SmallNumOps = NumOps;
  509. MDOperand *O = reinterpret_cast<MDOperand *>(this) - SmallSize;
  510. for (MDOperand *E = O + SmallSize; O != E;)
  511. (void)new (O++) MDOperand();
  512. }
  513. MDNode::Header::~Header() {
  514. if (IsLarge) {
  515. getLarge().~LargeStorageVector();
  516. return;
  517. }
  518. MDOperand *O = reinterpret_cast<MDOperand *>(this);
  519. for (MDOperand *E = O - SmallSize; O != E; --O)
  520. (void)(O - 1)->~MDOperand();
  521. }
  522. void *MDNode::Header::getSmallPtr() {
  523. static_assert(alignof(MDOperand) <= alignof(Header),
  524. "MDOperand too strongly aligned");
  525. return reinterpret_cast<char *>(const_cast<Header *>(this)) -
  526. sizeof(MDOperand) * SmallSize;
  527. }
  528. void MDNode::Header::resize(size_t NumOps) {
  529. assert(IsResizable && "Node is not resizable");
  530. if (operands().size() == NumOps)
  531. return;
  532. if (IsLarge)
  533. getLarge().resize(NumOps);
  534. else if (NumOps <= SmallSize)
  535. resizeSmall(NumOps);
  536. else
  537. resizeSmallToLarge(NumOps);
  538. }
  539. void MDNode::Header::resizeSmall(size_t NumOps) {
  540. assert(!IsLarge && "Expected a small MDNode");
  541. assert(NumOps <= SmallSize && "NumOps too large for small resize");
  542. MutableArrayRef<MDOperand> ExistingOps = operands();
  543. assert(NumOps != ExistingOps.size() && "Expected a different size");
  544. int NumNew = (int)NumOps - (int)ExistingOps.size();
  545. MDOperand *O = ExistingOps.end();
  546. for (int I = 0, E = NumNew; I < E; ++I)
  547. (O++)->reset();
  548. for (int I = 0, E = NumNew; I > E; --I)
  549. (--O)->reset();
  550. SmallNumOps = NumOps;
  551. assert(O == operands().end() && "Operands not (un)initialized until the end");
  552. }
  553. void MDNode::Header::resizeSmallToLarge(size_t NumOps) {
  554. assert(!IsLarge && "Expected a small MDNode");
  555. assert(NumOps > SmallSize && "Expected NumOps to be larger than allocation");
  556. LargeStorageVector NewOps;
  557. NewOps.resize(NumOps);
  558. llvm::move(operands(), NewOps.begin());
  559. resizeSmall(0);
  560. new (getLargePtr()) LargeStorageVector(std::move(NewOps));
  561. IsLarge = true;
  562. }
  563. static bool isOperandUnresolved(Metadata *Op) {
  564. if (auto *N = dyn_cast_or_null<MDNode>(Op))
  565. return !N->isResolved();
  566. return false;
  567. }
  568. void MDNode::countUnresolvedOperands() {
  569. assert(getNumUnresolved() == 0 && "Expected unresolved ops to be uncounted");
  570. assert(isUniqued() && "Expected this to be uniqued");
  571. setNumUnresolved(count_if(operands(), isOperandUnresolved));
  572. }
  573. void MDNode::makeUniqued() {
  574. assert(isTemporary() && "Expected this to be temporary");
  575. assert(!isResolved() && "Expected this to be unresolved");
  576. // Enable uniquing callbacks.
  577. for (auto &Op : mutable_operands())
  578. Op.reset(Op.get(), this);
  579. // Make this 'uniqued'.
  580. Storage = Uniqued;
  581. countUnresolvedOperands();
  582. if (!getNumUnresolved()) {
  583. dropReplaceableUses();
  584. assert(isResolved() && "Expected this to be resolved");
  585. }
  586. assert(isUniqued() && "Expected this to be uniqued");
  587. }
  588. void MDNode::makeDistinct() {
  589. assert(isTemporary() && "Expected this to be temporary");
  590. assert(!isResolved() && "Expected this to be unresolved");
  591. // Drop RAUW support and store as a distinct node.
  592. dropReplaceableUses();
  593. storeDistinctInContext();
  594. assert(isDistinct() && "Expected this to be distinct");
  595. assert(isResolved() && "Expected this to be resolved");
  596. }
  597. void MDNode::resolve() {
  598. assert(isUniqued() && "Expected this to be uniqued");
  599. assert(!isResolved() && "Expected this to be unresolved");
  600. setNumUnresolved(0);
  601. dropReplaceableUses();
  602. assert(isResolved() && "Expected this to be resolved");
  603. }
  604. void MDNode::dropReplaceableUses() {
  605. assert(!getNumUnresolved() && "Unexpected unresolved operand");
  606. // Drop any RAUW support.
  607. if (Context.hasReplaceableUses())
  608. Context.takeReplaceableUses()->resolveAllUses();
  609. }
  610. void MDNode::resolveAfterOperandChange(Metadata *Old, Metadata *New) {
  611. assert(isUniqued() && "Expected this to be uniqued");
  612. assert(getNumUnresolved() != 0 && "Expected unresolved operands");
  613. // Check if an operand was resolved.
  614. if (!isOperandUnresolved(Old)) {
  615. if (isOperandUnresolved(New))
  616. // An operand was un-resolved!
  617. setNumUnresolved(getNumUnresolved() + 1);
  618. } else if (!isOperandUnresolved(New))
  619. decrementUnresolvedOperandCount();
  620. }
  621. void MDNode::decrementUnresolvedOperandCount() {
  622. assert(!isResolved() && "Expected this to be unresolved");
  623. if (isTemporary())
  624. return;
  625. assert(isUniqued() && "Expected this to be uniqued");
  626. setNumUnresolved(getNumUnresolved() - 1);
  627. if (getNumUnresolved())
  628. return;
  629. // Last unresolved operand has just been resolved.
  630. dropReplaceableUses();
  631. assert(isResolved() && "Expected this to become resolved");
  632. }
  633. void MDNode::resolveCycles() {
  634. if (isResolved())
  635. return;
  636. // Resolve this node immediately.
  637. resolve();
  638. // Resolve all operands.
  639. for (const auto &Op : operands()) {
  640. auto *N = dyn_cast_or_null<MDNode>(Op);
  641. if (!N)
  642. continue;
  643. assert(!N->isTemporary() &&
  644. "Expected all forward declarations to be resolved");
  645. if (!N->isResolved())
  646. N->resolveCycles();
  647. }
  648. }
  649. static bool hasSelfReference(MDNode *N) {
  650. return llvm::is_contained(N->operands(), N);
  651. }
  652. MDNode *MDNode::replaceWithPermanentImpl() {
  653. switch (getMetadataID()) {
  654. default:
  655. // If this type isn't uniquable, replace with a distinct node.
  656. return replaceWithDistinctImpl();
  657. #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
  658. case CLASS##Kind: \
  659. break;
  660. #include "llvm/IR/Metadata.def"
  661. }
  662. // Even if this type is uniquable, self-references have to be distinct.
  663. if (hasSelfReference(this))
  664. return replaceWithDistinctImpl();
  665. return replaceWithUniquedImpl();
  666. }
  667. MDNode *MDNode::replaceWithUniquedImpl() {
  668. // Try to uniquify in place.
  669. MDNode *UniquedNode = uniquify();
  670. if (UniquedNode == this) {
  671. makeUniqued();
  672. return this;
  673. }
  674. // Collision, so RAUW instead.
  675. replaceAllUsesWith(UniquedNode);
  676. deleteAsSubclass();
  677. return UniquedNode;
  678. }
  679. MDNode *MDNode::replaceWithDistinctImpl() {
  680. makeDistinct();
  681. return this;
  682. }
  683. void MDTuple::recalculateHash() {
  684. setHash(MDTupleInfo::KeyTy::calculateHash(this));
  685. }
  686. void MDNode::dropAllReferences() {
  687. for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
  688. setOperand(I, nullptr);
  689. if (Context.hasReplaceableUses()) {
  690. Context.getReplaceableUses()->resolveAllUses(/* ResolveUsers */ false);
  691. (void)Context.takeReplaceableUses();
  692. }
  693. }
  694. void MDNode::handleChangedOperand(void *Ref, Metadata *New) {
  695. unsigned Op = static_cast<MDOperand *>(Ref) - op_begin();
  696. assert(Op < getNumOperands() && "Expected valid operand");
  697. if (!isUniqued()) {
  698. // This node is not uniqued. Just set the operand and be done with it.
  699. setOperand(Op, New);
  700. return;
  701. }
  702. // This node is uniqued.
  703. eraseFromStore();
  704. Metadata *Old = getOperand(Op);
  705. setOperand(Op, New);
  706. // Drop uniquing for self-reference cycles and deleted constants.
  707. if (New == this || (!New && Old && isa<ConstantAsMetadata>(Old))) {
  708. if (!isResolved())
  709. resolve();
  710. storeDistinctInContext();
  711. return;
  712. }
  713. // Re-unique the node.
  714. auto *Uniqued = uniquify();
  715. if (Uniqued == this) {
  716. if (!isResolved())
  717. resolveAfterOperandChange(Old, New);
  718. return;
  719. }
  720. // Collision.
  721. if (!isResolved()) {
  722. // Still unresolved, so RAUW.
  723. //
  724. // First, clear out all operands to prevent any recursion (similar to
  725. // dropAllReferences(), but we still need the use-list).
  726. for (unsigned O = 0, E = getNumOperands(); O != E; ++O)
  727. setOperand(O, nullptr);
  728. if (Context.hasReplaceableUses())
  729. Context.getReplaceableUses()->replaceAllUsesWith(Uniqued);
  730. deleteAsSubclass();
  731. return;
  732. }
  733. // Store in non-uniqued form if RAUW isn't possible.
  734. storeDistinctInContext();
  735. }
  736. void MDNode::deleteAsSubclass() {
  737. switch (getMetadataID()) {
  738. default:
  739. llvm_unreachable("Invalid subclass of MDNode");
  740. #define HANDLE_MDNODE_LEAF(CLASS) \
  741. case CLASS##Kind: \
  742. delete cast<CLASS>(this); \
  743. break;
  744. #include "llvm/IR/Metadata.def"
  745. }
  746. }
  747. template <class T, class InfoT>
  748. static T *uniquifyImpl(T *N, DenseSet<T *, InfoT> &Store) {
  749. if (T *U = getUniqued(Store, N))
  750. return U;
  751. Store.insert(N);
  752. return N;
  753. }
  754. template <class NodeTy> struct MDNode::HasCachedHash {
  755. using Yes = char[1];
  756. using No = char[2];
  757. template <class U, U Val> struct SFINAE {};
  758. template <class U>
  759. static Yes &check(SFINAE<void (U::*)(unsigned), &U::setHash> *);
  760. template <class U> static No &check(...);
  761. static const bool value = sizeof(check<NodeTy>(nullptr)) == sizeof(Yes);
  762. };
  763. MDNode *MDNode::uniquify() {
  764. assert(!hasSelfReference(this) && "Cannot uniquify a self-referencing node");
  765. // Try to insert into uniquing store.
  766. switch (getMetadataID()) {
  767. default:
  768. llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
  769. #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
  770. case CLASS##Kind: { \
  771. CLASS *SubclassThis = cast<CLASS>(this); \
  772. std::integral_constant<bool, HasCachedHash<CLASS>::value> \
  773. ShouldRecalculateHash; \
  774. dispatchRecalculateHash(SubclassThis, ShouldRecalculateHash); \
  775. return uniquifyImpl(SubclassThis, getContext().pImpl->CLASS##s); \
  776. }
  777. #include "llvm/IR/Metadata.def"
  778. }
  779. }
  780. void MDNode::eraseFromStore() {
  781. switch (getMetadataID()) {
  782. default:
  783. llvm_unreachable("Invalid or non-uniquable subclass of MDNode");
  784. #define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS) \
  785. case CLASS##Kind: \
  786. getContext().pImpl->CLASS##s.erase(cast<CLASS>(this)); \
  787. break;
  788. #include "llvm/IR/Metadata.def"
  789. }
  790. }
  791. MDTuple *MDTuple::getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
  792. StorageType Storage, bool ShouldCreate) {
  793. unsigned Hash = 0;
  794. if (Storage == Uniqued) {
  795. MDTupleInfo::KeyTy Key(MDs);
  796. if (auto *N = getUniqued(Context.pImpl->MDTuples, Key))
  797. return N;
  798. if (!ShouldCreate)
  799. return nullptr;
  800. Hash = Key.getHash();
  801. } else {
  802. assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
  803. }
  804. return storeImpl(new (MDs.size(), Storage)
  805. MDTuple(Context, Storage, Hash, MDs),
  806. Storage, Context.pImpl->MDTuples);
  807. }
  808. void MDNode::deleteTemporary(MDNode *N) {
  809. assert(N->isTemporary() && "Expected temporary node");
  810. N->replaceAllUsesWith(nullptr);
  811. N->deleteAsSubclass();
  812. }
  813. void MDNode::storeDistinctInContext() {
  814. assert(!Context.hasReplaceableUses() && "Unexpected replaceable uses");
  815. assert(!getNumUnresolved() && "Unexpected unresolved nodes");
  816. Storage = Distinct;
  817. assert(isResolved() && "Expected this to be resolved");
  818. // Reset the hash.
  819. switch (getMetadataID()) {
  820. default:
  821. llvm_unreachable("Invalid subclass of MDNode");
  822. #define HANDLE_MDNODE_LEAF(CLASS) \
  823. case CLASS##Kind: { \
  824. std::integral_constant<bool, HasCachedHash<CLASS>::value> ShouldResetHash; \
  825. dispatchResetHash(cast<CLASS>(this), ShouldResetHash); \
  826. break; \
  827. }
  828. #include "llvm/IR/Metadata.def"
  829. }
  830. getContext().pImpl->DistinctMDNodes.push_back(this);
  831. }
  832. void MDNode::replaceOperandWith(unsigned I, Metadata *New) {
  833. if (getOperand(I) == New)
  834. return;
  835. if (!isUniqued()) {
  836. setOperand(I, New);
  837. return;
  838. }
  839. handleChangedOperand(mutable_begin() + I, New);
  840. }
  841. void MDNode::setOperand(unsigned I, Metadata *New) {
  842. assert(I < getNumOperands());
  843. mutable_begin()[I].reset(New, isUniqued() ? this : nullptr);
  844. }
  845. /// Get a node or a self-reference that looks like it.
  846. ///
  847. /// Special handling for finding self-references, for use by \a
  848. /// MDNode::concatenate() and \a MDNode::intersect() to maintain behaviour from
  849. /// when self-referencing nodes were still uniqued. If the first operand has
  850. /// the same operands as \c Ops, return the first operand instead.
  851. static MDNode *getOrSelfReference(LLVMContext &Context,
  852. ArrayRef<Metadata *> Ops) {
  853. if (!Ops.empty())
  854. if (MDNode *N = dyn_cast_or_null<MDNode>(Ops[0]))
  855. if (N->getNumOperands() == Ops.size() && N == N->getOperand(0)) {
  856. for (unsigned I = 1, E = Ops.size(); I != E; ++I)
  857. if (Ops[I] != N->getOperand(I))
  858. return MDNode::get(Context, Ops);
  859. return N;
  860. }
  861. return MDNode::get(Context, Ops);
  862. }
  863. MDNode *MDNode::concatenate(MDNode *A, MDNode *B) {
  864. if (!A)
  865. return B;
  866. if (!B)
  867. return A;
  868. SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
  869. MDs.insert(B->op_begin(), B->op_end());
  870. // FIXME: This preserves long-standing behaviour, but is it really the right
  871. // behaviour? Or was that an unintended side-effect of node uniquing?
  872. return getOrSelfReference(A->getContext(), MDs.getArrayRef());
  873. }
  874. MDNode *MDNode::intersect(MDNode *A, MDNode *B) {
  875. if (!A || !B)
  876. return nullptr;
  877. SmallSetVector<Metadata *, 4> MDs(A->op_begin(), A->op_end());
  878. SmallPtrSet<Metadata *, 4> BSet(B->op_begin(), B->op_end());
  879. MDs.remove_if([&](Metadata *MD) { return !BSet.count(MD); });
  880. // FIXME: This preserves long-standing behaviour, but is it really the right
  881. // behaviour? Or was that an unintended side-effect of node uniquing?
  882. return getOrSelfReference(A->getContext(), MDs.getArrayRef());
  883. }
  884. MDNode *MDNode::getMostGenericAliasScope(MDNode *A, MDNode *B) {
  885. if (!A || !B)
  886. return nullptr;
  887. // Take the intersection of domains then union the scopes
  888. // within those domains
  889. SmallPtrSet<const MDNode *, 16> ADomains;
  890. SmallPtrSet<const MDNode *, 16> IntersectDomains;
  891. SmallSetVector<Metadata *, 4> MDs;
  892. for (const MDOperand &MDOp : A->operands())
  893. if (const MDNode *NAMD = dyn_cast<MDNode>(MDOp))
  894. if (const MDNode *Domain = AliasScopeNode(NAMD).getDomain())
  895. ADomains.insert(Domain);
  896. for (const MDOperand &MDOp : B->operands())
  897. if (const MDNode *NAMD = dyn_cast<MDNode>(MDOp))
  898. if (const MDNode *Domain = AliasScopeNode(NAMD).getDomain())
  899. if (ADomains.contains(Domain)) {
  900. IntersectDomains.insert(Domain);
  901. MDs.insert(MDOp);
  902. }
  903. for (const MDOperand &MDOp : A->operands())
  904. if (const MDNode *NAMD = dyn_cast<MDNode>(MDOp))
  905. if (const MDNode *Domain = AliasScopeNode(NAMD).getDomain())
  906. if (IntersectDomains.contains(Domain))
  907. MDs.insert(MDOp);
  908. return MDs.empty() ? nullptr
  909. : getOrSelfReference(A->getContext(), MDs.getArrayRef());
  910. }
  911. MDNode *MDNode::getMostGenericFPMath(MDNode *A, MDNode *B) {
  912. if (!A || !B)
  913. return nullptr;
  914. APFloat AVal = mdconst::extract<ConstantFP>(A->getOperand(0))->getValueAPF();
  915. APFloat BVal = mdconst::extract<ConstantFP>(B->getOperand(0))->getValueAPF();
  916. if (AVal < BVal)
  917. return A;
  918. return B;
  919. }
  920. static bool isContiguous(const ConstantRange &A, const ConstantRange &B) {
  921. return A.getUpper() == B.getLower() || A.getLower() == B.getUpper();
  922. }
  923. static bool canBeMerged(const ConstantRange &A, const ConstantRange &B) {
  924. return !A.intersectWith(B).isEmptySet() || isContiguous(A, B);
  925. }
  926. static bool tryMergeRange(SmallVectorImpl<ConstantInt *> &EndPoints,
  927. ConstantInt *Low, ConstantInt *High) {
  928. ConstantRange NewRange(Low->getValue(), High->getValue());
  929. unsigned Size = EndPoints.size();
  930. APInt LB = EndPoints[Size - 2]->getValue();
  931. APInt LE = EndPoints[Size - 1]->getValue();
  932. ConstantRange LastRange(LB, LE);
  933. if (canBeMerged(NewRange, LastRange)) {
  934. ConstantRange Union = LastRange.unionWith(NewRange);
  935. Type *Ty = High->getType();
  936. EndPoints[Size - 2] =
  937. cast<ConstantInt>(ConstantInt::get(Ty, Union.getLower()));
  938. EndPoints[Size - 1] =
  939. cast<ConstantInt>(ConstantInt::get(Ty, Union.getUpper()));
  940. return true;
  941. }
  942. return false;
  943. }
  944. static void addRange(SmallVectorImpl<ConstantInt *> &EndPoints,
  945. ConstantInt *Low, ConstantInt *High) {
  946. if (!EndPoints.empty())
  947. if (tryMergeRange(EndPoints, Low, High))
  948. return;
  949. EndPoints.push_back(Low);
  950. EndPoints.push_back(High);
  951. }
  952. MDNode *MDNode::getMostGenericRange(MDNode *A, MDNode *B) {
  953. // Given two ranges, we want to compute the union of the ranges. This
  954. // is slightly complicated by having to combine the intervals and merge
  955. // the ones that overlap.
  956. if (!A || !B)
  957. return nullptr;
  958. if (A == B)
  959. return A;
  960. // First, walk both lists in order of the lower boundary of each interval.
  961. // At each step, try to merge the new interval to the last one we adedd.
  962. SmallVector<ConstantInt *, 4> EndPoints;
  963. int AI = 0;
  964. int BI = 0;
  965. int AN = A->getNumOperands() / 2;
  966. int BN = B->getNumOperands() / 2;
  967. while (AI < AN && BI < BN) {
  968. ConstantInt *ALow = mdconst::extract<ConstantInt>(A->getOperand(2 * AI));
  969. ConstantInt *BLow = mdconst::extract<ConstantInt>(B->getOperand(2 * BI));
  970. if (ALow->getValue().slt(BLow->getValue())) {
  971. addRange(EndPoints, ALow,
  972. mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
  973. ++AI;
  974. } else {
  975. addRange(EndPoints, BLow,
  976. mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
  977. ++BI;
  978. }
  979. }
  980. while (AI < AN) {
  981. addRange(EndPoints, mdconst::extract<ConstantInt>(A->getOperand(2 * AI)),
  982. mdconst::extract<ConstantInt>(A->getOperand(2 * AI + 1)));
  983. ++AI;
  984. }
  985. while (BI < BN) {
  986. addRange(EndPoints, mdconst::extract<ConstantInt>(B->getOperand(2 * BI)),
  987. mdconst::extract<ConstantInt>(B->getOperand(2 * BI + 1)));
  988. ++BI;
  989. }
  990. // If we have more than 2 ranges (4 endpoints) we have to try to merge
  991. // the last and first ones.
  992. unsigned Size = EndPoints.size();
  993. if (Size > 4) {
  994. ConstantInt *FB = EndPoints[0];
  995. ConstantInt *FE = EndPoints[1];
  996. if (tryMergeRange(EndPoints, FB, FE)) {
  997. for (unsigned i = 0; i < Size - 2; ++i) {
  998. EndPoints[i] = EndPoints[i + 2];
  999. }
  1000. EndPoints.resize(Size - 2);
  1001. }
  1002. }
  1003. // If in the end we have a single range, it is possible that it is now the
  1004. // full range. Just drop the metadata in that case.
  1005. if (EndPoints.size() == 2) {
  1006. ConstantRange Range(EndPoints[0]->getValue(), EndPoints[1]->getValue());
  1007. if (Range.isFullSet())
  1008. return nullptr;
  1009. }
  1010. SmallVector<Metadata *, 4> MDs;
  1011. MDs.reserve(EndPoints.size());
  1012. for (auto *I : EndPoints)
  1013. MDs.push_back(ConstantAsMetadata::get(I));
  1014. return MDNode::get(A->getContext(), MDs);
  1015. }
  1016. MDNode *MDNode::getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B) {
  1017. if (!A || !B)
  1018. return nullptr;
  1019. ConstantInt *AVal = mdconst::extract<ConstantInt>(A->getOperand(0));
  1020. ConstantInt *BVal = mdconst::extract<ConstantInt>(B->getOperand(0));
  1021. if (AVal->getZExtValue() < BVal->getZExtValue())
  1022. return A;
  1023. return B;
  1024. }
  1025. //===----------------------------------------------------------------------===//
  1026. // NamedMDNode implementation.
  1027. //
  1028. static SmallVector<TrackingMDRef, 4> &getNMDOps(void *Operands) {
  1029. return *(SmallVector<TrackingMDRef, 4> *)Operands;
  1030. }
  1031. NamedMDNode::NamedMDNode(const Twine &N)
  1032. : Name(N.str()), Operands(new SmallVector<TrackingMDRef, 4>()) {}
  1033. NamedMDNode::~NamedMDNode() {
  1034. dropAllReferences();
  1035. delete &getNMDOps(Operands);
  1036. }
  1037. unsigned NamedMDNode::getNumOperands() const {
  1038. return (unsigned)getNMDOps(Operands).size();
  1039. }
  1040. MDNode *NamedMDNode::getOperand(unsigned i) const {
  1041. assert(i < getNumOperands() && "Invalid Operand number!");
  1042. auto *N = getNMDOps(Operands)[i].get();
  1043. return cast_or_null<MDNode>(N);
  1044. }
  1045. void NamedMDNode::addOperand(MDNode *M) { getNMDOps(Operands).emplace_back(M); }
  1046. void NamedMDNode::setOperand(unsigned I, MDNode *New) {
  1047. assert(I < getNumOperands() && "Invalid operand number");
  1048. getNMDOps(Operands)[I].reset(New);
  1049. }
  1050. void NamedMDNode::eraseFromParent() { getParent()->eraseNamedMetadata(this); }
  1051. void NamedMDNode::clearOperands() { getNMDOps(Operands).clear(); }
  1052. StringRef NamedMDNode::getName() const { return StringRef(Name); }
  1053. //===----------------------------------------------------------------------===//
  1054. // Instruction Metadata method implementations.
  1055. //
  1056. MDNode *MDAttachments::lookup(unsigned ID) const {
  1057. for (const auto &A : Attachments)
  1058. if (A.MDKind == ID)
  1059. return A.Node;
  1060. return nullptr;
  1061. }
  1062. void MDAttachments::get(unsigned ID, SmallVectorImpl<MDNode *> &Result) const {
  1063. for (const auto &A : Attachments)
  1064. if (A.MDKind == ID)
  1065. Result.push_back(A.Node);
  1066. }
  1067. void MDAttachments::getAll(
  1068. SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
  1069. for (const auto &A : Attachments)
  1070. Result.emplace_back(A.MDKind, A.Node);
  1071. // Sort the resulting array so it is stable with respect to metadata IDs. We
  1072. // need to preserve the original insertion order though.
  1073. if (Result.size() > 1)
  1074. llvm::stable_sort(Result, less_first());
  1075. }
  1076. void MDAttachments::set(unsigned ID, MDNode *MD) {
  1077. erase(ID);
  1078. if (MD)
  1079. insert(ID, *MD);
  1080. }
  1081. void MDAttachments::insert(unsigned ID, MDNode &MD) {
  1082. Attachments.push_back({ID, TrackingMDNodeRef(&MD)});
  1083. }
  1084. bool MDAttachments::erase(unsigned ID) {
  1085. if (empty())
  1086. return false;
  1087. // Common case is one value.
  1088. if (Attachments.size() == 1 && Attachments.back().MDKind == ID) {
  1089. Attachments.pop_back();
  1090. return true;
  1091. }
  1092. auto OldSize = Attachments.size();
  1093. llvm::erase_if(Attachments,
  1094. [ID](const Attachment &A) { return A.MDKind == ID; });
  1095. return OldSize != Attachments.size();
  1096. }
  1097. MDNode *Value::getMetadata(unsigned KindID) const {
  1098. if (!hasMetadata())
  1099. return nullptr;
  1100. const auto &Info = getContext().pImpl->ValueMetadata[this];
  1101. assert(!Info.empty() && "bit out of sync with hash table");
  1102. return Info.lookup(KindID);
  1103. }
  1104. MDNode *Value::getMetadata(StringRef Kind) const {
  1105. if (!hasMetadata())
  1106. return nullptr;
  1107. const auto &Info = getContext().pImpl->ValueMetadata[this];
  1108. assert(!Info.empty() && "bit out of sync with hash table");
  1109. return Info.lookup(getContext().getMDKindID(Kind));
  1110. }
  1111. void Value::getMetadata(unsigned KindID, SmallVectorImpl<MDNode *> &MDs) const {
  1112. if (hasMetadata())
  1113. getContext().pImpl->ValueMetadata[this].get(KindID, MDs);
  1114. }
  1115. void Value::getMetadata(StringRef Kind, SmallVectorImpl<MDNode *> &MDs) const {
  1116. if (hasMetadata())
  1117. getMetadata(getContext().getMDKindID(Kind), MDs);
  1118. }
  1119. void Value::getAllMetadata(
  1120. SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const {
  1121. if (hasMetadata()) {
  1122. assert(getContext().pImpl->ValueMetadata.count(this) &&
  1123. "bit out of sync with hash table");
  1124. const auto &Info = getContext().pImpl->ValueMetadata.find(this)->second;
  1125. assert(!Info.empty() && "Shouldn't have called this");
  1126. Info.getAll(MDs);
  1127. }
  1128. }
  1129. void Value::setMetadata(unsigned KindID, MDNode *Node) {
  1130. assert(isa<Instruction>(this) || isa<GlobalObject>(this));
  1131. // Handle the case when we're adding/updating metadata on a value.
  1132. if (Node) {
  1133. auto &Info = getContext().pImpl->ValueMetadata[this];
  1134. assert(!Info.empty() == HasMetadata && "bit out of sync with hash table");
  1135. if (Info.empty())
  1136. HasMetadata = true;
  1137. Info.set(KindID, Node);
  1138. return;
  1139. }
  1140. // Otherwise, we're removing metadata from an instruction.
  1141. assert((HasMetadata == (getContext().pImpl->ValueMetadata.count(this) > 0)) &&
  1142. "bit out of sync with hash table");
  1143. if (!HasMetadata)
  1144. return; // Nothing to remove!
  1145. auto &Info = getContext().pImpl->ValueMetadata[this];
  1146. // Handle removal of an existing value.
  1147. Info.erase(KindID);
  1148. if (!Info.empty())
  1149. return;
  1150. getContext().pImpl->ValueMetadata.erase(this);
  1151. HasMetadata = false;
  1152. }
  1153. void Value::setMetadata(StringRef Kind, MDNode *Node) {
  1154. if (!Node && !HasMetadata)
  1155. return;
  1156. setMetadata(getContext().getMDKindID(Kind), Node);
  1157. }
  1158. void Value::addMetadata(unsigned KindID, MDNode &MD) {
  1159. assert(isa<Instruction>(this) || isa<GlobalObject>(this));
  1160. if (!HasMetadata)
  1161. HasMetadata = true;
  1162. getContext().pImpl->ValueMetadata[this].insert(KindID, MD);
  1163. }
  1164. void Value::addMetadata(StringRef Kind, MDNode &MD) {
  1165. addMetadata(getContext().getMDKindID(Kind), MD);
  1166. }
  1167. bool Value::eraseMetadata(unsigned KindID) {
  1168. // Nothing to unset.
  1169. if (!HasMetadata)
  1170. return false;
  1171. auto &Store = getContext().pImpl->ValueMetadata[this];
  1172. bool Changed = Store.erase(KindID);
  1173. if (Store.empty())
  1174. clearMetadata();
  1175. return Changed;
  1176. }
  1177. void Value::clearMetadata() {
  1178. if (!HasMetadata)
  1179. return;
  1180. assert(getContext().pImpl->ValueMetadata.count(this) &&
  1181. "bit out of sync with hash table");
  1182. getContext().pImpl->ValueMetadata.erase(this);
  1183. HasMetadata = false;
  1184. }
  1185. void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
  1186. if (!Node && !hasMetadata())
  1187. return;
  1188. setMetadata(getContext().getMDKindID(Kind), Node);
  1189. }
  1190. MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
  1191. return getMetadataImpl(getContext().getMDKindID(Kind));
  1192. }
  1193. void Instruction::dropUnknownNonDebugMetadata(ArrayRef<unsigned> KnownIDs) {
  1194. if (!Value::hasMetadata())
  1195. return; // Nothing to remove!
  1196. SmallSet<unsigned, 4> KnownSet;
  1197. KnownSet.insert(KnownIDs.begin(), KnownIDs.end());
  1198. // A DIAssignID attachment is debug metadata, don't drop it.
  1199. KnownSet.insert(LLVMContext::MD_DIAssignID);
  1200. auto &MetadataStore = getContext().pImpl->ValueMetadata;
  1201. auto &Info = MetadataStore[this];
  1202. assert(!Info.empty() && "bit out of sync with hash table");
  1203. Info.remove_if([&KnownSet](const MDAttachments::Attachment &I) {
  1204. return !KnownSet.count(I.MDKind);
  1205. });
  1206. if (Info.empty()) {
  1207. // Drop our entry at the store.
  1208. clearMetadata();
  1209. }
  1210. }
  1211. void Instruction::updateDIAssignIDMapping(DIAssignID *ID) {
  1212. auto &IDToInstrs = getContext().pImpl->AssignmentIDToInstrs;
  1213. if (const DIAssignID *CurrentID =
  1214. cast_or_null<DIAssignID>(getMetadata(LLVMContext::MD_DIAssignID))) {
  1215. // Nothing to do if the ID isn't changing.
  1216. if (ID == CurrentID)
  1217. return;
  1218. // Unmap this instruction from its current ID.
  1219. auto InstrsIt = IDToInstrs.find(CurrentID);
  1220. assert(InstrsIt != IDToInstrs.end() &&
  1221. "Expect existing attachment to be mapped");
  1222. auto &InstVec = InstrsIt->second;
  1223. auto *InstIt = std::find(InstVec.begin(), InstVec.end(), this);
  1224. assert(InstIt != InstVec.end() &&
  1225. "Expect instruction to be mapped to attachment");
  1226. // The vector contains a ptr to this. If this is the only element in the
  1227. // vector, remove the ID:vector entry, otherwise just remove the
  1228. // instruction from the vector.
  1229. if (InstVec.size() == 1)
  1230. IDToInstrs.erase(InstrsIt);
  1231. else
  1232. InstVec.erase(InstIt);
  1233. }
  1234. // Map this instruction to the new ID.
  1235. if (ID)
  1236. IDToInstrs[ID].push_back(this);
  1237. }
  1238. void Instruction::setMetadata(unsigned KindID, MDNode *Node) {
  1239. if (!Node && !hasMetadata())
  1240. return;
  1241. // Handle 'dbg' as a special case since it is not stored in the hash table.
  1242. if (KindID == LLVMContext::MD_dbg) {
  1243. DbgLoc = DebugLoc(Node);
  1244. return;
  1245. }
  1246. // Update DIAssignID to Instruction(s) mapping.
  1247. if (KindID == LLVMContext::MD_DIAssignID) {
  1248. // The DIAssignID tracking infrastructure doesn't support RAUWing temporary
  1249. // nodes with DIAssignIDs. The cast_or_null below would also catch this, but
  1250. // having a dedicated assert helps make this obvious.
  1251. assert((!Node || !Node->isTemporary()) &&
  1252. "Temporary DIAssignIDs are invalid");
  1253. updateDIAssignIDMapping(cast_or_null<DIAssignID>(Node));
  1254. }
  1255. Value::setMetadata(KindID, Node);
  1256. }
  1257. void Instruction::addAnnotationMetadata(StringRef Name) {
  1258. MDBuilder MDB(getContext());
  1259. auto *Existing = getMetadata(LLVMContext::MD_annotation);
  1260. SmallVector<Metadata *, 4> Names;
  1261. bool AppendName = true;
  1262. if (Existing) {
  1263. auto *Tuple = cast<MDTuple>(Existing);
  1264. for (auto &N : Tuple->operands()) {
  1265. if (cast<MDString>(N.get())->getString() == Name)
  1266. AppendName = false;
  1267. Names.push_back(N.get());
  1268. }
  1269. }
  1270. if (AppendName)
  1271. Names.push_back(MDB.createString(Name));
  1272. MDNode *MD = MDTuple::get(getContext(), Names);
  1273. setMetadata(LLVMContext::MD_annotation, MD);
  1274. }
  1275. AAMDNodes Instruction::getAAMetadata() const {
  1276. AAMDNodes Result;
  1277. // Not using Instruction::hasMetadata() because we're not interested in
  1278. // DebugInfoMetadata.
  1279. if (Value::hasMetadata()) {
  1280. const auto &Info = getContext().pImpl->ValueMetadata[this];
  1281. Result.TBAA = Info.lookup(LLVMContext::MD_tbaa);
  1282. Result.TBAAStruct = Info.lookup(LLVMContext::MD_tbaa_struct);
  1283. Result.Scope = Info.lookup(LLVMContext::MD_alias_scope);
  1284. Result.NoAlias = Info.lookup(LLVMContext::MD_noalias);
  1285. }
  1286. return Result;
  1287. }
  1288. void Instruction::setAAMetadata(const AAMDNodes &N) {
  1289. setMetadata(LLVMContext::MD_tbaa, N.TBAA);
  1290. setMetadata(LLVMContext::MD_tbaa_struct, N.TBAAStruct);
  1291. setMetadata(LLVMContext::MD_alias_scope, N.Scope);
  1292. setMetadata(LLVMContext::MD_noalias, N.NoAlias);
  1293. }
  1294. MDNode *Instruction::getMetadataImpl(unsigned KindID) const {
  1295. // Handle 'dbg' as a special case since it is not stored in the hash table.
  1296. if (KindID == LLVMContext::MD_dbg)
  1297. return DbgLoc.getAsMDNode();
  1298. return Value::getMetadata(KindID);
  1299. }
  1300. void Instruction::getAllMetadataImpl(
  1301. SmallVectorImpl<std::pair<unsigned, MDNode *>> &Result) const {
  1302. Result.clear();
  1303. // Handle 'dbg' as a special case since it is not stored in the hash table.
  1304. if (DbgLoc) {
  1305. Result.push_back(
  1306. std::make_pair((unsigned)LLVMContext::MD_dbg, DbgLoc.getAsMDNode()));
  1307. }
  1308. Value::getAllMetadata(Result);
  1309. }
  1310. bool Instruction::extractProfTotalWeight(uint64_t &TotalVal) const {
  1311. assert(
  1312. (getOpcode() == Instruction::Br || getOpcode() == Instruction::Select ||
  1313. getOpcode() == Instruction::Call || getOpcode() == Instruction::Invoke ||
  1314. getOpcode() == Instruction::IndirectBr ||
  1315. getOpcode() == Instruction::Switch) &&
  1316. "Looking for branch weights on something besides branch");
  1317. return ::extractProfTotalWeight(*this, TotalVal);
  1318. }
  1319. void GlobalObject::copyMetadata(const GlobalObject *Other, unsigned Offset) {
  1320. SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
  1321. Other->getAllMetadata(MDs);
  1322. for (auto &MD : MDs) {
  1323. // We need to adjust the type metadata offset.
  1324. if (Offset != 0 && MD.first == LLVMContext::MD_type) {
  1325. auto *OffsetConst = cast<ConstantInt>(
  1326. cast<ConstantAsMetadata>(MD.second->getOperand(0))->getValue());
  1327. Metadata *TypeId = MD.second->getOperand(1);
  1328. auto *NewOffsetMD = ConstantAsMetadata::get(ConstantInt::get(
  1329. OffsetConst->getType(), OffsetConst->getValue() + Offset));
  1330. addMetadata(LLVMContext::MD_type,
  1331. *MDNode::get(getContext(), {NewOffsetMD, TypeId}));
  1332. continue;
  1333. }
  1334. // If an offset adjustment was specified we need to modify the DIExpression
  1335. // to prepend the adjustment:
  1336. // !DIExpression(DW_OP_plus, Offset, [original expr])
  1337. auto *Attachment = MD.second;
  1338. if (Offset != 0 && MD.first == LLVMContext::MD_dbg) {
  1339. DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(Attachment);
  1340. DIExpression *E = nullptr;
  1341. if (!GV) {
  1342. auto *GVE = cast<DIGlobalVariableExpression>(Attachment);
  1343. GV = GVE->getVariable();
  1344. E = GVE->getExpression();
  1345. }
  1346. ArrayRef<uint64_t> OrigElements;
  1347. if (E)
  1348. OrigElements = E->getElements();
  1349. std::vector<uint64_t> Elements(OrigElements.size() + 2);
  1350. Elements[0] = dwarf::DW_OP_plus_uconst;
  1351. Elements[1] = Offset;
  1352. llvm::copy(OrigElements, Elements.begin() + 2);
  1353. E = DIExpression::get(getContext(), Elements);
  1354. Attachment = DIGlobalVariableExpression::get(getContext(), GV, E);
  1355. }
  1356. addMetadata(MD.first, *Attachment);
  1357. }
  1358. }
  1359. void GlobalObject::addTypeMetadata(unsigned Offset, Metadata *TypeID) {
  1360. addMetadata(
  1361. LLVMContext::MD_type,
  1362. *MDTuple::get(getContext(),
  1363. {ConstantAsMetadata::get(ConstantInt::get(
  1364. Type::getInt64Ty(getContext()), Offset)),
  1365. TypeID}));
  1366. }
  1367. void GlobalObject::setVCallVisibilityMetadata(VCallVisibility Visibility) {
  1368. // Remove any existing vcall visibility metadata first in case we are
  1369. // updating.
  1370. eraseMetadata(LLVMContext::MD_vcall_visibility);
  1371. addMetadata(LLVMContext::MD_vcall_visibility,
  1372. *MDNode::get(getContext(),
  1373. {ConstantAsMetadata::get(ConstantInt::get(
  1374. Type::getInt64Ty(getContext()), Visibility))}));
  1375. }
  1376. GlobalObject::VCallVisibility GlobalObject::getVCallVisibility() const {
  1377. if (MDNode *MD = getMetadata(LLVMContext::MD_vcall_visibility)) {
  1378. uint64_t Val = cast<ConstantInt>(
  1379. cast<ConstantAsMetadata>(MD->getOperand(0))->getValue())
  1380. ->getZExtValue();
  1381. assert(Val <= 2 && "unknown vcall visibility!");
  1382. return (VCallVisibility)Val;
  1383. }
  1384. return VCallVisibility::VCallVisibilityPublic;
  1385. }
  1386. void Function::setSubprogram(DISubprogram *SP) {
  1387. setMetadata(LLVMContext::MD_dbg, SP);
  1388. }
  1389. DISubprogram *Function::getSubprogram() const {
  1390. return cast_or_null<DISubprogram>(getMetadata(LLVMContext::MD_dbg));
  1391. }
  1392. bool Function::shouldEmitDebugInfoForProfiling() const {
  1393. if (DISubprogram *SP = getSubprogram()) {
  1394. if (DICompileUnit *CU = SP->getUnit()) {
  1395. return CU->getDebugInfoForProfiling();
  1396. }
  1397. }
  1398. return false;
  1399. }
  1400. void GlobalVariable::addDebugInfo(DIGlobalVariableExpression *GV) {
  1401. addMetadata(LLVMContext::MD_dbg, *GV);
  1402. }
  1403. void GlobalVariable::getDebugInfo(
  1404. SmallVectorImpl<DIGlobalVariableExpression *> &GVs) const {
  1405. SmallVector<MDNode *, 1> MDs;
  1406. getMetadata(LLVMContext::MD_dbg, MDs);
  1407. for (MDNode *MD : MDs)
  1408. GVs.push_back(cast<DIGlobalVariableExpression>(MD));
  1409. }