AliasSetTracker.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/Analysis/AliasSetTracker.h - Build Alias Sets -------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines two classes: AliasSetTracker and AliasSet. These interfaces
  15. // are used to classify a collection of pointer references into a maximal number
  16. // of disjoint sets. Each AliasSet object constructed by the AliasSetTracker
  17. // object refers to memory disjoint from the other sets.
  18. //
  19. //===----------------------------------------------------------------------===//
  20. #ifndef LLVM_ANALYSIS_ALIASSETTRACKER_H
  21. #define LLVM_ANALYSIS_ALIASSETTRACKER_H
  22. #include "llvm/ADT/DenseMap.h"
  23. #include "llvm/ADT/DenseMapInfo.h"
  24. #include "llvm/ADT/ilist.h"
  25. #include "llvm/ADT/ilist_node.h"
  26. #include "llvm/Analysis/MemoryLocation.h"
  27. #include "llvm/IR/Instruction.h"
  28. #include "llvm/IR/Metadata.h"
  29. #include "llvm/IR/PassManager.h"
  30. #include "llvm/IR/ValueHandle.h"
  31. #include "llvm/Support/Casting.h"
  32. #include <cassert>
  33. #include <cstddef>
  34. #include <cstdint>
  35. #include <iterator>
  36. #include <vector>
  37. namespace llvm {
  38. class AAResults;
  39. class AliasResult;
  40. class AliasSetTracker;
  41. class AnyMemSetInst;
  42. class AnyMemTransferInst;
  43. class BasicBlock;
  44. class LoadInst;
  45. class raw_ostream;
  46. class StoreInst;
  47. class VAArgInst;
  48. class Value;
  49. class AliasSet : public ilist_node<AliasSet> {
  50. friend class AliasSetTracker;
  51. class PointerRec {
  52. Value *Val; // The pointer this record corresponds to.
  53. PointerRec **PrevInList = nullptr;
  54. PointerRec *NextInList = nullptr;
  55. AliasSet *AS = nullptr;
  56. LocationSize Size = LocationSize::mapEmpty();
  57. AAMDNodes AAInfo;
  58. // Whether the size for this record has been set at all. This makes no
  59. // guarantees about the size being known.
  60. bool isSizeSet() const { return Size != LocationSize::mapEmpty(); }
  61. public:
  62. PointerRec(Value *V)
  63. : Val(V), AAInfo(DenseMapInfo<AAMDNodes>::getEmptyKey()) {}
  64. Value *getValue() const { return Val; }
  65. PointerRec *getNext() const { return NextInList; }
  66. bool hasAliasSet() const { return AS != nullptr; }
  67. PointerRec** setPrevInList(PointerRec **PIL) {
  68. PrevInList = PIL;
  69. return &NextInList;
  70. }
  71. bool updateSizeAndAAInfo(LocationSize NewSize, const AAMDNodes &NewAAInfo) {
  72. bool SizeChanged = false;
  73. if (NewSize != Size) {
  74. LocationSize OldSize = Size;
  75. Size = isSizeSet() ? Size.unionWith(NewSize) : NewSize;
  76. SizeChanged = OldSize != Size;
  77. }
  78. if (AAInfo == DenseMapInfo<AAMDNodes>::getEmptyKey())
  79. // We don't have a AAInfo yet. Set it to NewAAInfo.
  80. AAInfo = NewAAInfo;
  81. else {
  82. AAMDNodes Intersection(AAInfo.intersect(NewAAInfo));
  83. SizeChanged |= Intersection != AAInfo;
  84. AAInfo = Intersection;
  85. }
  86. return SizeChanged;
  87. }
  88. LocationSize getSize() const {
  89. assert(isSizeSet() && "Getting an unset size!");
  90. return Size;
  91. }
  92. /// Return the AAInfo, or null if there is no information or conflicting
  93. /// information.
  94. AAMDNodes getAAInfo() const {
  95. // If we have missing or conflicting AAInfo, return null.
  96. if (AAInfo == DenseMapInfo<AAMDNodes>::getEmptyKey() ||
  97. AAInfo == DenseMapInfo<AAMDNodes>::getTombstoneKey())
  98. return AAMDNodes();
  99. return AAInfo;
  100. }
  101. AliasSet *getAliasSet(AliasSetTracker &AST) {
  102. assert(AS && "No AliasSet yet!");
  103. if (AS->Forward) {
  104. AliasSet *OldAS = AS;
  105. AS = OldAS->getForwardedTarget(AST);
  106. AS->addRef();
  107. OldAS->dropRef(AST);
  108. }
  109. return AS;
  110. }
  111. void setAliasSet(AliasSet *as) {
  112. assert(!AS && "Already have an alias set!");
  113. AS = as;
  114. }
  115. void eraseFromList() {
  116. if (NextInList) NextInList->PrevInList = PrevInList;
  117. *PrevInList = NextInList;
  118. if (AS->PtrListEnd == &NextInList) {
  119. AS->PtrListEnd = PrevInList;
  120. assert(*AS->PtrListEnd == nullptr && "List not terminated right!");
  121. }
  122. delete this;
  123. }
  124. };
  125. // Doubly linked list of nodes.
  126. PointerRec *PtrList = nullptr;
  127. PointerRec **PtrListEnd;
  128. // Forwarding pointer.
  129. AliasSet *Forward = nullptr;
  130. /// All instructions without a specific address in this alias set.
  131. /// In rare cases this vector can have a null'ed out WeakVH
  132. /// instances (can happen if some other loop pass deletes an
  133. /// instruction in this list).
  134. std::vector<WeakVH> UnknownInsts;
  135. /// Number of nodes pointing to this AliasSet plus the number of AliasSets
  136. /// forwarding to it.
  137. unsigned RefCount : 27;
  138. // Signifies that this set should be considered to alias any pointer.
  139. // Use when the tracker holding this set is saturated.
  140. unsigned AliasAny : 1;
  141. /// The kinds of access this alias set models.
  142. ///
  143. /// We keep track of whether this alias set merely refers to the locations of
  144. /// memory (and not any particular access), whether it modifies or references
  145. /// the memory, or whether it does both. The lattice goes from "NoAccess" to
  146. /// either RefAccess or ModAccess, then to ModRefAccess as necessary.
  147. enum AccessLattice {
  148. NoAccess = 0,
  149. RefAccess = 1,
  150. ModAccess = 2,
  151. ModRefAccess = RefAccess | ModAccess
  152. };
  153. unsigned Access : 2;
  154. /// The kind of alias relationship between pointers of the set.
  155. ///
  156. /// These represent conservatively correct alias results between any members
  157. /// of the set. We represent these independently of the values of alias
  158. /// results in order to pack it into a single bit. Lattice goes from
  159. /// MustAlias to MayAlias.
  160. enum AliasLattice {
  161. SetMustAlias = 0, SetMayAlias = 1
  162. };
  163. unsigned Alias : 1;
  164. unsigned SetSize = 0;
  165. void addRef() { ++RefCount; }
  166. void dropRef(AliasSetTracker &AST) {
  167. assert(RefCount >= 1 && "Invalid reference count detected!");
  168. if (--RefCount == 0)
  169. removeFromTracker(AST);
  170. }
  171. Instruction *getUnknownInst(unsigned i) const {
  172. assert(i < UnknownInsts.size());
  173. return cast_or_null<Instruction>(UnknownInsts[i]);
  174. }
  175. public:
  176. AliasSet(const AliasSet &) = delete;
  177. AliasSet &operator=(const AliasSet &) = delete;
  178. /// Accessors...
  179. bool isRef() const { return Access & RefAccess; }
  180. bool isMod() const { return Access & ModAccess; }
  181. bool isMustAlias() const { return Alias == SetMustAlias; }
  182. bool isMayAlias() const { return Alias == SetMayAlias; }
  183. /// Return true if this alias set should be ignored as part of the
  184. /// AliasSetTracker object.
  185. bool isForwardingAliasSet() const { return Forward; }
  186. /// Merge the specified alias set into this alias set.
  187. void mergeSetIn(AliasSet &AS, AliasSetTracker &AST);
  188. // Alias Set iteration - Allow access to all of the pointers which are part of
  189. // this alias set.
  190. class iterator;
  191. iterator begin() const { return iterator(PtrList); }
  192. iterator end() const { return iterator(); }
  193. bool empty() const { return PtrList == nullptr; }
  194. // Unfortunately, ilist::size() is linear, so we have to add code to keep
  195. // track of the list's exact size.
  196. unsigned size() { return SetSize; }
  197. /// If this alias set is known to contain a single instruction and *only* a
  198. /// single unique instruction, return it. Otherwise, return nullptr.
  199. Instruction* getUniqueInstruction();
  200. void print(raw_ostream &OS) const;
  201. void dump() const;
  202. /// Define an iterator for alias sets... this is just a forward iterator.
  203. class iterator {
  204. PointerRec *CurNode;
  205. public:
  206. using iterator_category = std::forward_iterator_tag;
  207. using value_type = PointerRec;
  208. using difference_type = std::ptrdiff_t;
  209. using pointer = value_type *;
  210. using reference = value_type &;
  211. explicit iterator(PointerRec *CN = nullptr) : CurNode(CN) {}
  212. bool operator==(const iterator& x) const {
  213. return CurNode == x.CurNode;
  214. }
  215. bool operator!=(const iterator& x) const { return !operator==(x); }
  216. value_type &operator*() const {
  217. assert(CurNode && "Dereferencing AliasSet.end()!");
  218. return *CurNode;
  219. }
  220. value_type *operator->() const { return &operator*(); }
  221. Value *getPointer() const { return CurNode->getValue(); }
  222. LocationSize getSize() const { return CurNode->getSize(); }
  223. AAMDNodes getAAInfo() const { return CurNode->getAAInfo(); }
  224. iterator& operator++() { // Preincrement
  225. assert(CurNode && "Advancing past AliasSet.end()!");
  226. CurNode = CurNode->getNext();
  227. return *this;
  228. }
  229. iterator operator++(int) { // Postincrement
  230. iterator tmp = *this; ++*this; return tmp;
  231. }
  232. };
  233. private:
  234. // Can only be created by AliasSetTracker.
  235. AliasSet()
  236. : PtrListEnd(&PtrList), RefCount(0), AliasAny(false), Access(NoAccess),
  237. Alias(SetMustAlias) {}
  238. PointerRec *getSomePointer() const {
  239. return PtrList;
  240. }
  241. /// Return the real alias set this represents. If this has been merged with
  242. /// another set and is forwarding, return the ultimate destination set. This
  243. /// also implements the union-find collapsing as well.
  244. AliasSet *getForwardedTarget(AliasSetTracker &AST) {
  245. if (!Forward) return this;
  246. AliasSet *Dest = Forward->getForwardedTarget(AST);
  247. if (Dest != Forward) {
  248. Dest->addRef();
  249. Forward->dropRef(AST);
  250. Forward = Dest;
  251. }
  252. return Dest;
  253. }
  254. void removeFromTracker(AliasSetTracker &AST);
  255. void addPointer(AliasSetTracker &AST, PointerRec &Entry, LocationSize Size,
  256. const AAMDNodes &AAInfo, bool KnownMustAlias = false,
  257. bool SkipSizeUpdate = false);
  258. void addUnknownInst(Instruction *I, AAResults &AA);
  259. void removeUnknownInst(AliasSetTracker &AST, Instruction *I) {
  260. bool WasEmpty = UnknownInsts.empty();
  261. for (size_t i = 0, e = UnknownInsts.size(); i != e; ++i)
  262. if (UnknownInsts[i] == I) {
  263. UnknownInsts[i] = UnknownInsts.back();
  264. UnknownInsts.pop_back();
  265. --i; --e; // Revisit the moved entry.
  266. }
  267. if (!WasEmpty && UnknownInsts.empty())
  268. dropRef(AST);
  269. }
  270. public:
  271. /// If the specified pointer "may" (or must) alias one of the members in the
  272. /// set return the appropriate AliasResult. Otherwise return NoAlias.
  273. AliasResult aliasesPointer(const Value *Ptr, LocationSize Size,
  274. const AAMDNodes &AAInfo, AAResults &AA) const;
  275. bool aliasesUnknownInst(const Instruction *Inst, AAResults &AA) const;
  276. };
  277. inline raw_ostream& operator<<(raw_ostream &OS, const AliasSet &AS) {
  278. AS.print(OS);
  279. return OS;
  280. }
  281. class AliasSetTracker {
  282. /// A CallbackVH to arrange for AliasSetTracker to be notified whenever a
  283. /// Value is deleted.
  284. class ASTCallbackVH final : public CallbackVH {
  285. AliasSetTracker *AST;
  286. void deleted() override;
  287. void allUsesReplacedWith(Value *) override;
  288. public:
  289. ASTCallbackVH(Value *V, AliasSetTracker *AST = nullptr);
  290. ASTCallbackVH &operator=(Value *V);
  291. };
  292. /// Traits to tell DenseMap that tell us how to compare and hash the value
  293. /// handle.
  294. struct ASTCallbackVHDenseMapInfo : public DenseMapInfo<Value *> {};
  295. AAResults &AA;
  296. ilist<AliasSet> AliasSets;
  297. using PointerMapType = DenseMap<ASTCallbackVH, AliasSet::PointerRec *,
  298. ASTCallbackVHDenseMapInfo>;
  299. // Map from pointers to their node
  300. PointerMapType PointerMap;
  301. public:
  302. /// Create an empty collection of AliasSets, and use the specified alias
  303. /// analysis object to disambiguate load and store addresses.
  304. explicit AliasSetTracker(AAResults &AA) : AA(AA) {}
  305. ~AliasSetTracker() { clear(); }
  306. /// These methods are used to add different types of instructions to the alias
  307. /// sets. Adding a new instruction can result in one of three actions
  308. /// happening:
  309. ///
  310. /// 1. If the instruction doesn't alias any other sets, create a new set.
  311. /// 2. If the instruction aliases exactly one set, add it to the set
  312. /// 3. If the instruction aliases multiple sets, merge the sets, and add
  313. /// the instruction to the result.
  314. ///
  315. /// These methods return true if inserting the instruction resulted in the
  316. /// addition of a new alias set (i.e., the pointer did not alias anything).
  317. ///
  318. void add(Value *Ptr, LocationSize Size, const AAMDNodes &AAInfo); // Add a loc
  319. void add(LoadInst *LI);
  320. void add(StoreInst *SI);
  321. void add(VAArgInst *VAAI);
  322. void add(AnyMemSetInst *MSI);
  323. void add(AnyMemTransferInst *MTI);
  324. void add(Instruction *I); // Dispatch to one of the other add methods...
  325. void add(BasicBlock &BB); // Add all instructions in basic block
  326. void add(const AliasSetTracker &AST); // Add alias relations from another AST
  327. void addUnknown(Instruction *I);
  328. void clear();
  329. /// Return the alias sets that are active.
  330. const ilist<AliasSet> &getAliasSets() const { return AliasSets; }
  331. /// Return the alias set which contains the specified memory location. If
  332. /// the memory location aliases two or more existing alias sets, will have
  333. /// the effect of merging those alias sets before the single resulting alias
  334. /// set is returned.
  335. AliasSet &getAliasSetFor(const MemoryLocation &MemLoc);
  336. /// Return the underlying alias analysis object used by this tracker.
  337. AAResults &getAliasAnalysis() const { return AA; }
  338. /// This method is used to remove a pointer value from the AliasSetTracker
  339. /// entirely. It should be used when an instruction is deleted from the
  340. /// program to update the AST. If you don't use this, you would have dangling
  341. /// pointers to deleted instructions.
  342. void deleteValue(Value *PtrVal);
  343. /// This method should be used whenever a preexisting value in the program is
  344. /// copied or cloned, introducing a new value. Note that it is ok for clients
  345. /// that use this method to introduce the same value multiple times: if the
  346. /// tracker already knows about a value, it will ignore the request.
  347. void copyValue(Value *From, Value *To);
  348. using iterator = ilist<AliasSet>::iterator;
  349. using const_iterator = ilist<AliasSet>::const_iterator;
  350. const_iterator begin() const { return AliasSets.begin(); }
  351. const_iterator end() const { return AliasSets.end(); }
  352. iterator begin() { return AliasSets.begin(); }
  353. iterator end() { return AliasSets.end(); }
  354. void print(raw_ostream &OS) const;
  355. void dump() const;
  356. private:
  357. friend class AliasSet;
  358. // The total number of pointers contained in all "may" alias sets.
  359. unsigned TotalMayAliasSetSize = 0;
  360. // A non-null value signifies this AST is saturated. A saturated AST lumps
  361. // all pointers into a single "May" set.
  362. AliasSet *AliasAnyAS = nullptr;
  363. void removeAliasSet(AliasSet *AS);
  364. /// Just like operator[] on the map, except that it creates an entry for the
  365. /// pointer if it doesn't already exist.
  366. AliasSet::PointerRec &getEntryFor(Value *V) {
  367. AliasSet::PointerRec *&Entry = PointerMap[ASTCallbackVH(V, this)];
  368. if (!Entry)
  369. Entry = new AliasSet::PointerRec(V);
  370. return *Entry;
  371. }
  372. AliasSet &addPointer(MemoryLocation Loc, AliasSet::AccessLattice E);
  373. AliasSet *mergeAliasSetsForPointer(const Value *Ptr, LocationSize Size,
  374. const AAMDNodes &AAInfo,
  375. bool &MustAliasAll);
  376. /// Merge all alias sets into a single set that is considered to alias any
  377. /// pointer.
  378. AliasSet &mergeAllAliasSets();
  379. AliasSet *findAliasSetForUnknownInst(Instruction *Inst);
  380. };
  381. inline raw_ostream& operator<<(raw_ostream &OS, const AliasSetTracker &AST) {
  382. AST.print(OS);
  383. return OS;
  384. }
  385. class AliasSetsPrinterPass : public PassInfoMixin<AliasSetsPrinterPass> {
  386. raw_ostream &OS;
  387. public:
  388. explicit AliasSetsPrinterPass(raw_ostream &OS);
  389. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  390. };
  391. } // end namespace llvm
  392. #endif // LLVM_ANALYSIS_ALIASSETTRACKER_H
  393. #ifdef __GNUC__
  394. #pragma GCC diagnostic pop
  395. #endif