MemorySSA.h 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- MemorySSA.h - Build Memory SSA ---------------------------*- 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. /// \file
  15. /// This file exposes an interface to building/using memory SSA to
  16. /// walk memory instructions using a use/def graph.
  17. ///
  18. /// Memory SSA class builds an SSA form that links together memory access
  19. /// instructions such as loads, stores, atomics, and calls. Additionally, it
  20. /// does a trivial form of "heap versioning" Every time the memory state changes
  21. /// in the program, we generate a new heap version. It generates
  22. /// MemoryDef/Uses/Phis that are overlayed on top of the existing instructions.
  23. ///
  24. /// As a trivial example,
  25. /// define i32 @main() #0 {
  26. /// entry:
  27. /// %call = call noalias i8* @_Znwm(i64 4) #2
  28. /// %0 = bitcast i8* %call to i32*
  29. /// %call1 = call noalias i8* @_Znwm(i64 4) #2
  30. /// %1 = bitcast i8* %call1 to i32*
  31. /// store i32 5, i32* %0, align 4
  32. /// store i32 7, i32* %1, align 4
  33. /// %2 = load i32* %0, align 4
  34. /// %3 = load i32* %1, align 4
  35. /// %add = add nsw i32 %2, %3
  36. /// ret i32 %add
  37. /// }
  38. ///
  39. /// Will become
  40. /// define i32 @main() #0 {
  41. /// entry:
  42. /// ; 1 = MemoryDef(0)
  43. /// %call = call noalias i8* @_Znwm(i64 4) #3
  44. /// %2 = bitcast i8* %call to i32*
  45. /// ; 2 = MemoryDef(1)
  46. /// %call1 = call noalias i8* @_Znwm(i64 4) #3
  47. /// %4 = bitcast i8* %call1 to i32*
  48. /// ; 3 = MemoryDef(2)
  49. /// store i32 5, i32* %2, align 4
  50. /// ; 4 = MemoryDef(3)
  51. /// store i32 7, i32* %4, align 4
  52. /// ; MemoryUse(3)
  53. /// %7 = load i32* %2, align 4
  54. /// ; MemoryUse(4)
  55. /// %8 = load i32* %4, align 4
  56. /// %add = add nsw i32 %7, %8
  57. /// ret i32 %add
  58. /// }
  59. ///
  60. /// Given this form, all the stores that could ever effect the load at %8 can be
  61. /// gotten by using the MemoryUse associated with it, and walking from use to
  62. /// def until you hit the top of the function.
  63. ///
  64. /// Each def also has a list of users associated with it, so you can walk from
  65. /// both def to users, and users to defs. Note that we disambiguate MemoryUses,
  66. /// but not the RHS of MemoryDefs. You can see this above at %7, which would
  67. /// otherwise be a MemoryUse(4). Being disambiguated means that for a given
  68. /// store, all the MemoryUses on its use lists are may-aliases of that store
  69. /// (but the MemoryDefs on its use list may not be).
  70. ///
  71. /// MemoryDefs are not disambiguated because it would require multiple reaching
  72. /// definitions, which would require multiple phis, and multiple memoryaccesses
  73. /// per instruction.
  74. ///
  75. /// In addition to the def/use graph described above, MemoryDefs also contain
  76. /// an "optimized" definition use. The "optimized" use points to some def
  77. /// reachable through the memory def chain. The optimized def *may* (but is
  78. /// not required to) alias the original MemoryDef, but no def *closer* to the
  79. /// source def may alias it. As the name implies, the purpose of the optimized
  80. /// use is to allow caching of clobber searches for memory defs. The optimized
  81. /// def may be nullptr, in which case clients must walk the defining access
  82. /// chain.
  83. ///
  84. /// When iterating the uses of a MemoryDef, both defining uses and optimized
  85. /// uses will be encountered. If only one type is needed, the client must
  86. /// filter the use walk.
  87. //
  88. //===----------------------------------------------------------------------===//
  89. #ifndef LLVM_ANALYSIS_MEMORYSSA_H
  90. #define LLVM_ANALYSIS_MEMORYSSA_H
  91. #include "llvm/ADT/DenseMap.h"
  92. #include "llvm/ADT/SmallPtrSet.h"
  93. #include "llvm/ADT/SmallVector.h"
  94. #include "llvm/ADT/ilist_node.h"
  95. #include "llvm/ADT/iterator_range.h"
  96. #include "llvm/Analysis/AliasAnalysis.h"
  97. #include "llvm/Analysis/MemoryLocation.h"
  98. #include "llvm/Analysis/PHITransAddr.h"
  99. #include "llvm/IR/DerivedUser.h"
  100. #include "llvm/IR/Dominators.h"
  101. #include "llvm/IR/Type.h"
  102. #include "llvm/IR/User.h"
  103. #include "llvm/Pass.h"
  104. #include <algorithm>
  105. #include <cassert>
  106. #include <cstddef>
  107. #include <iterator>
  108. #include <memory>
  109. #include <utility>
  110. namespace llvm {
  111. template <class GraphType> struct GraphTraits;
  112. class BasicBlock;
  113. class Function;
  114. class Instruction;
  115. class LLVMContext;
  116. class MemoryAccess;
  117. class MemorySSAWalker;
  118. class Module;
  119. class Use;
  120. class Value;
  121. class raw_ostream;
  122. namespace MSSAHelpers {
  123. struct AllAccessTag {};
  124. struct DefsOnlyTag {};
  125. } // end namespace MSSAHelpers
  126. enum : unsigned {
  127. // Used to signify what the default invalid ID is for MemoryAccess's
  128. // getID()
  129. INVALID_MEMORYACCESS_ID = -1U
  130. };
  131. template <class T> class memoryaccess_def_iterator_base;
  132. using memoryaccess_def_iterator = memoryaccess_def_iterator_base<MemoryAccess>;
  133. using const_memoryaccess_def_iterator =
  134. memoryaccess_def_iterator_base<const MemoryAccess>;
  135. // The base for all memory accesses. All memory accesses in a block are
  136. // linked together using an intrusive list.
  137. class MemoryAccess
  138. : public DerivedUser,
  139. public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>,
  140. public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>> {
  141. public:
  142. using AllAccessType =
  143. ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>;
  144. using DefsOnlyType =
  145. ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>>;
  146. MemoryAccess(const MemoryAccess &) = delete;
  147. MemoryAccess &operator=(const MemoryAccess &) = delete;
  148. void *operator new(size_t) = delete;
  149. // Methods for support type inquiry through isa, cast, and
  150. // dyn_cast
  151. static bool classof(const Value *V) {
  152. unsigned ID = V->getValueID();
  153. return ID == MemoryUseVal || ID == MemoryPhiVal || ID == MemoryDefVal;
  154. }
  155. BasicBlock *getBlock() const { return Block; }
  156. void print(raw_ostream &OS) const;
  157. void dump() const;
  158. /// The user iterators for a memory access
  159. using iterator = user_iterator;
  160. using const_iterator = const_user_iterator;
  161. /// This iterator walks over all of the defs in a given
  162. /// MemoryAccess. For MemoryPhi nodes, this walks arguments. For
  163. /// MemoryUse/MemoryDef, this walks the defining access.
  164. memoryaccess_def_iterator defs_begin();
  165. const_memoryaccess_def_iterator defs_begin() const;
  166. memoryaccess_def_iterator defs_end();
  167. const_memoryaccess_def_iterator defs_end() const;
  168. /// Get the iterators for the all access list and the defs only list
  169. /// We default to the all access list.
  170. AllAccessType::self_iterator getIterator() {
  171. return this->AllAccessType::getIterator();
  172. }
  173. AllAccessType::const_self_iterator getIterator() const {
  174. return this->AllAccessType::getIterator();
  175. }
  176. AllAccessType::reverse_self_iterator getReverseIterator() {
  177. return this->AllAccessType::getReverseIterator();
  178. }
  179. AllAccessType::const_reverse_self_iterator getReverseIterator() const {
  180. return this->AllAccessType::getReverseIterator();
  181. }
  182. DefsOnlyType::self_iterator getDefsIterator() {
  183. return this->DefsOnlyType::getIterator();
  184. }
  185. DefsOnlyType::const_self_iterator getDefsIterator() const {
  186. return this->DefsOnlyType::getIterator();
  187. }
  188. DefsOnlyType::reverse_self_iterator getReverseDefsIterator() {
  189. return this->DefsOnlyType::getReverseIterator();
  190. }
  191. DefsOnlyType::const_reverse_self_iterator getReverseDefsIterator() const {
  192. return this->DefsOnlyType::getReverseIterator();
  193. }
  194. protected:
  195. friend class MemoryDef;
  196. friend class MemoryPhi;
  197. friend class MemorySSA;
  198. friend class MemoryUse;
  199. friend class MemoryUseOrDef;
  200. /// Used by MemorySSA to change the block of a MemoryAccess when it is
  201. /// moved.
  202. void setBlock(BasicBlock *BB) { Block = BB; }
  203. /// Used for debugging and tracking things about MemoryAccesses.
  204. /// Guaranteed unique among MemoryAccesses, no guarantees otherwise.
  205. inline unsigned getID() const;
  206. MemoryAccess(LLVMContext &C, unsigned Vty, DeleteValueTy DeleteValue,
  207. BasicBlock *BB, unsigned NumOperands)
  208. : DerivedUser(Type::getVoidTy(C), Vty, nullptr, NumOperands, DeleteValue),
  209. Block(BB) {}
  210. // Use deleteValue() to delete a generic MemoryAccess.
  211. ~MemoryAccess() = default;
  212. private:
  213. BasicBlock *Block;
  214. };
  215. template <>
  216. struct ilist_alloc_traits<MemoryAccess> {
  217. static void deleteNode(MemoryAccess *MA) { MA->deleteValue(); }
  218. };
  219. inline raw_ostream &operator<<(raw_ostream &OS, const MemoryAccess &MA) {
  220. MA.print(OS);
  221. return OS;
  222. }
  223. /// Class that has the common methods + fields of memory uses/defs. It's
  224. /// a little awkward to have, but there are many cases where we want either a
  225. /// use or def, and there are many cases where uses are needed (defs aren't
  226. /// acceptable), and vice-versa.
  227. ///
  228. /// This class should never be instantiated directly; make a MemoryUse or
  229. /// MemoryDef instead.
  230. class MemoryUseOrDef : public MemoryAccess {
  231. public:
  232. void *operator new(size_t) = delete;
  233. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
  234. /// Get the instruction that this MemoryUse represents.
  235. Instruction *getMemoryInst() const { return MemoryInstruction; }
  236. /// Get the access that produces the memory state used by this Use.
  237. MemoryAccess *getDefiningAccess() const { return getOperand(0); }
  238. static bool classof(const Value *MA) {
  239. return MA->getValueID() == MemoryUseVal || MA->getValueID() == MemoryDefVal;
  240. }
  241. /// Do we have an optimized use?
  242. inline bool isOptimized() const;
  243. /// Return the MemoryAccess associated with the optimized use, or nullptr.
  244. inline MemoryAccess *getOptimized() const;
  245. /// Sets the optimized use for a MemoryDef.
  246. inline void setOptimized(MemoryAccess *);
  247. /// Reset the ID of what this MemoryUse was optimized to, causing it to
  248. /// be rewalked by the walker if necessary.
  249. /// This really should only be called by tests.
  250. inline void resetOptimized();
  251. protected:
  252. friend class MemorySSA;
  253. friend class MemorySSAUpdater;
  254. MemoryUseOrDef(LLVMContext &C, MemoryAccess *DMA, unsigned Vty,
  255. DeleteValueTy DeleteValue, Instruction *MI, BasicBlock *BB,
  256. unsigned NumOperands)
  257. : MemoryAccess(C, Vty, DeleteValue, BB, NumOperands),
  258. MemoryInstruction(MI) {
  259. setDefiningAccess(DMA);
  260. }
  261. // Use deleteValue() to delete a generic MemoryUseOrDef.
  262. ~MemoryUseOrDef() = default;
  263. void setDefiningAccess(MemoryAccess *DMA, bool Optimized = false) {
  264. if (!Optimized) {
  265. setOperand(0, DMA);
  266. return;
  267. }
  268. setOptimized(DMA);
  269. }
  270. private:
  271. Instruction *MemoryInstruction;
  272. };
  273. /// Represents read-only accesses to memory
  274. ///
  275. /// In particular, the set of Instructions that will be represented by
  276. /// MemoryUse's is exactly the set of Instructions for which
  277. /// AliasAnalysis::getModRefInfo returns "Ref".
  278. class MemoryUse final : public MemoryUseOrDef {
  279. public:
  280. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
  281. MemoryUse(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB)
  282. : MemoryUseOrDef(C, DMA, MemoryUseVal, deleteMe, MI, BB,
  283. /*NumOperands=*/1) {}
  284. // allocate space for exactly one operand
  285. void *operator new(size_t S) { return User::operator new(S, 1); }
  286. void operator delete(void *Ptr) { User::operator delete(Ptr); }
  287. static bool classof(const Value *MA) {
  288. return MA->getValueID() == MemoryUseVal;
  289. }
  290. void print(raw_ostream &OS) const;
  291. void setOptimized(MemoryAccess *DMA) {
  292. OptimizedID = DMA->getID();
  293. setOperand(0, DMA);
  294. }
  295. /// Whether the MemoryUse is optimized. If ensureOptimizedUses() was called,
  296. /// uses will usually be optimized, but this is not guaranteed (e.g. due to
  297. /// invalidation and optimization limits.)
  298. bool isOptimized() const {
  299. return getDefiningAccess() && OptimizedID == getDefiningAccess()->getID();
  300. }
  301. MemoryAccess *getOptimized() const {
  302. return getDefiningAccess();
  303. }
  304. void resetOptimized() {
  305. OptimizedID = INVALID_MEMORYACCESS_ID;
  306. }
  307. protected:
  308. friend class MemorySSA;
  309. private:
  310. static void deleteMe(DerivedUser *Self);
  311. unsigned OptimizedID = INVALID_MEMORYACCESS_ID;
  312. };
  313. template <>
  314. struct OperandTraits<MemoryUse> : public FixedNumOperandTraits<MemoryUse, 1> {};
  315. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryUse, MemoryAccess)
  316. /// Represents a read-write access to memory, whether it is a must-alias,
  317. /// or a may-alias.
  318. ///
  319. /// In particular, the set of Instructions that will be represented by
  320. /// MemoryDef's is exactly the set of Instructions for which
  321. /// AliasAnalysis::getModRefInfo returns "Mod" or "ModRef".
  322. /// Note that, in order to provide def-def chains, all defs also have a use
  323. /// associated with them. This use points to the nearest reaching
  324. /// MemoryDef/MemoryPhi.
  325. class MemoryDef final : public MemoryUseOrDef {
  326. public:
  327. friend class MemorySSA;
  328. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
  329. MemoryDef(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB,
  330. unsigned Ver)
  331. : MemoryUseOrDef(C, DMA, MemoryDefVal, deleteMe, MI, BB,
  332. /*NumOperands=*/2),
  333. ID(Ver) {}
  334. // allocate space for exactly two operands
  335. void *operator new(size_t S) { return User::operator new(S, 2); }
  336. void operator delete(void *Ptr) { User::operator delete(Ptr); }
  337. static bool classof(const Value *MA) {
  338. return MA->getValueID() == MemoryDefVal;
  339. }
  340. void setOptimized(MemoryAccess *MA) {
  341. setOperand(1, MA);
  342. OptimizedID = MA->getID();
  343. }
  344. MemoryAccess *getOptimized() const {
  345. return cast_or_null<MemoryAccess>(getOperand(1));
  346. }
  347. bool isOptimized() const {
  348. return getOptimized() && OptimizedID == getOptimized()->getID();
  349. }
  350. void resetOptimized() {
  351. OptimizedID = INVALID_MEMORYACCESS_ID;
  352. setOperand(1, nullptr);
  353. }
  354. void print(raw_ostream &OS) const;
  355. unsigned getID() const { return ID; }
  356. private:
  357. static void deleteMe(DerivedUser *Self);
  358. const unsigned ID;
  359. unsigned OptimizedID = INVALID_MEMORYACCESS_ID;
  360. };
  361. template <>
  362. struct OperandTraits<MemoryDef> : public FixedNumOperandTraits<MemoryDef, 2> {};
  363. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryDef, MemoryAccess)
  364. template <>
  365. struct OperandTraits<MemoryUseOrDef> {
  366. static Use *op_begin(MemoryUseOrDef *MUD) {
  367. if (auto *MU = dyn_cast<MemoryUse>(MUD))
  368. return OperandTraits<MemoryUse>::op_begin(MU);
  369. return OperandTraits<MemoryDef>::op_begin(cast<MemoryDef>(MUD));
  370. }
  371. static Use *op_end(MemoryUseOrDef *MUD) {
  372. if (auto *MU = dyn_cast<MemoryUse>(MUD))
  373. return OperandTraits<MemoryUse>::op_end(MU);
  374. return OperandTraits<MemoryDef>::op_end(cast<MemoryDef>(MUD));
  375. }
  376. static unsigned operands(const MemoryUseOrDef *MUD) {
  377. if (const auto *MU = dyn_cast<MemoryUse>(MUD))
  378. return OperandTraits<MemoryUse>::operands(MU);
  379. return OperandTraits<MemoryDef>::operands(cast<MemoryDef>(MUD));
  380. }
  381. };
  382. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryUseOrDef, MemoryAccess)
  383. /// Represents phi nodes for memory accesses.
  384. ///
  385. /// These have the same semantic as regular phi nodes, with the exception that
  386. /// only one phi will ever exist in a given basic block.
  387. /// Guaranteeing one phi per block means guaranteeing there is only ever one
  388. /// valid reaching MemoryDef/MemoryPHI along each path to the phi node.
  389. /// This is ensured by not allowing disambiguation of the RHS of a MemoryDef or
  390. /// a MemoryPhi's operands.
  391. /// That is, given
  392. /// if (a) {
  393. /// store %a
  394. /// store %b
  395. /// }
  396. /// it *must* be transformed into
  397. /// if (a) {
  398. /// 1 = MemoryDef(liveOnEntry)
  399. /// store %a
  400. /// 2 = MemoryDef(1)
  401. /// store %b
  402. /// }
  403. /// and *not*
  404. /// if (a) {
  405. /// 1 = MemoryDef(liveOnEntry)
  406. /// store %a
  407. /// 2 = MemoryDef(liveOnEntry)
  408. /// store %b
  409. /// }
  410. /// even if the two stores do not conflict. Otherwise, both 1 and 2 reach the
  411. /// end of the branch, and if there are not two phi nodes, one will be
  412. /// disconnected completely from the SSA graph below that point.
  413. /// Because MemoryUse's do not generate new definitions, they do not have this
  414. /// issue.
  415. class MemoryPhi final : public MemoryAccess {
  416. // allocate space for exactly zero operands
  417. void *operator new(size_t S) { return User::operator new(S); }
  418. public:
  419. void operator delete(void *Ptr) { User::operator delete(Ptr); }
  420. /// Provide fast operand accessors
  421. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess);
  422. MemoryPhi(LLVMContext &C, BasicBlock *BB, unsigned Ver, unsigned NumPreds = 0)
  423. : MemoryAccess(C, MemoryPhiVal, deleteMe, BB, 0), ID(Ver),
  424. ReservedSpace(NumPreds) {
  425. allocHungoffUses(ReservedSpace);
  426. }
  427. // Block iterator interface. This provides access to the list of incoming
  428. // basic blocks, which parallels the list of incoming values.
  429. using block_iterator = BasicBlock **;
  430. using const_block_iterator = BasicBlock *const *;
  431. block_iterator block_begin() {
  432. return reinterpret_cast<block_iterator>(op_begin() + ReservedSpace);
  433. }
  434. const_block_iterator block_begin() const {
  435. return reinterpret_cast<const_block_iterator>(op_begin() + ReservedSpace);
  436. }
  437. block_iterator block_end() { return block_begin() + getNumOperands(); }
  438. const_block_iterator block_end() const {
  439. return block_begin() + getNumOperands();
  440. }
  441. iterator_range<block_iterator> blocks() {
  442. return make_range(block_begin(), block_end());
  443. }
  444. iterator_range<const_block_iterator> blocks() const {
  445. return make_range(block_begin(), block_end());
  446. }
  447. op_range incoming_values() { return operands(); }
  448. const_op_range incoming_values() const { return operands(); }
  449. /// Return the number of incoming edges
  450. unsigned getNumIncomingValues() const { return getNumOperands(); }
  451. /// Return incoming value number x
  452. MemoryAccess *getIncomingValue(unsigned I) const { return getOperand(I); }
  453. void setIncomingValue(unsigned I, MemoryAccess *V) {
  454. assert(V && "PHI node got a null value!");
  455. setOperand(I, V);
  456. }
  457. static unsigned getOperandNumForIncomingValue(unsigned I) { return I; }
  458. static unsigned getIncomingValueNumForOperand(unsigned I) { return I; }
  459. /// Return incoming basic block number @p i.
  460. BasicBlock *getIncomingBlock(unsigned I) const { return block_begin()[I]; }
  461. /// Return incoming basic block corresponding
  462. /// to an operand of the PHI.
  463. BasicBlock *getIncomingBlock(const Use &U) const {
  464. assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
  465. return getIncomingBlock(unsigned(&U - op_begin()));
  466. }
  467. /// Return incoming basic block corresponding
  468. /// to value use iterator.
  469. BasicBlock *getIncomingBlock(MemoryAccess::const_user_iterator I) const {
  470. return getIncomingBlock(I.getUse());
  471. }
  472. void setIncomingBlock(unsigned I, BasicBlock *BB) {
  473. assert(BB && "PHI node got a null basic block!");
  474. block_begin()[I] = BB;
  475. }
  476. /// Add an incoming value to the end of the PHI list
  477. void addIncoming(MemoryAccess *V, BasicBlock *BB) {
  478. if (getNumOperands() == ReservedSpace)
  479. growOperands(); // Get more space!
  480. // Initialize some new operands.
  481. setNumHungOffUseOperands(getNumOperands() + 1);
  482. setIncomingValue(getNumOperands() - 1, V);
  483. setIncomingBlock(getNumOperands() - 1, BB);
  484. }
  485. /// Return the first index of the specified basic
  486. /// block in the value list for this PHI. Returns -1 if no instance.
  487. int getBasicBlockIndex(const BasicBlock *BB) const {
  488. for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
  489. if (block_begin()[I] == BB)
  490. return I;
  491. return -1;
  492. }
  493. MemoryAccess *getIncomingValueForBlock(const BasicBlock *BB) const {
  494. int Idx = getBasicBlockIndex(BB);
  495. assert(Idx >= 0 && "Invalid basic block argument!");
  496. return getIncomingValue(Idx);
  497. }
  498. // After deleting incoming position I, the order of incoming may be changed.
  499. void unorderedDeleteIncoming(unsigned I) {
  500. unsigned E = getNumOperands();
  501. assert(I < E && "Cannot remove out of bounds Phi entry.");
  502. // MemoryPhi must have at least two incoming values, otherwise the MemoryPhi
  503. // itself should be deleted.
  504. assert(E >= 2 && "Cannot only remove incoming values in MemoryPhis with "
  505. "at least 2 values.");
  506. setIncomingValue(I, getIncomingValue(E - 1));
  507. setIncomingBlock(I, block_begin()[E - 1]);
  508. setOperand(E - 1, nullptr);
  509. block_begin()[E - 1] = nullptr;
  510. setNumHungOffUseOperands(getNumOperands() - 1);
  511. }
  512. // After deleting entries that satisfy Pred, remaining entries may have
  513. // changed order.
  514. template <typename Fn> void unorderedDeleteIncomingIf(Fn &&Pred) {
  515. for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
  516. if (Pred(getIncomingValue(I), getIncomingBlock(I))) {
  517. unorderedDeleteIncoming(I);
  518. E = getNumOperands();
  519. --I;
  520. }
  521. assert(getNumOperands() >= 1 &&
  522. "Cannot remove all incoming blocks in a MemoryPhi.");
  523. }
  524. // After deleting incoming block BB, the incoming blocks order may be changed.
  525. void unorderedDeleteIncomingBlock(const BasicBlock *BB) {
  526. unorderedDeleteIncomingIf(
  527. [&](const MemoryAccess *, const BasicBlock *B) { return BB == B; });
  528. }
  529. // After deleting incoming memory access MA, the incoming accesses order may
  530. // be changed.
  531. void unorderedDeleteIncomingValue(const MemoryAccess *MA) {
  532. unorderedDeleteIncomingIf(
  533. [&](const MemoryAccess *M, const BasicBlock *) { return MA == M; });
  534. }
  535. static bool classof(const Value *V) {
  536. return V->getValueID() == MemoryPhiVal;
  537. }
  538. void print(raw_ostream &OS) const;
  539. unsigned getID() const { return ID; }
  540. protected:
  541. friend class MemorySSA;
  542. /// this is more complicated than the generic
  543. /// User::allocHungoffUses, because we have to allocate Uses for the incoming
  544. /// values and pointers to the incoming blocks, all in one allocation.
  545. void allocHungoffUses(unsigned N) {
  546. User::allocHungoffUses(N, /* IsPhi */ true);
  547. }
  548. private:
  549. // For debugging only
  550. const unsigned ID;
  551. unsigned ReservedSpace;
  552. /// This grows the operand list in response to a push_back style of
  553. /// operation. This grows the number of ops by 1.5 times.
  554. void growOperands() {
  555. unsigned E = getNumOperands();
  556. // 2 op PHI nodes are VERY common, so reserve at least enough for that.
  557. ReservedSpace = std::max(E + E / 2, 2u);
  558. growHungoffUses(ReservedSpace, /* IsPhi */ true);
  559. }
  560. static void deleteMe(DerivedUser *Self);
  561. };
  562. inline unsigned MemoryAccess::getID() const {
  563. assert((isa<MemoryDef>(this) || isa<MemoryPhi>(this)) &&
  564. "only memory defs and phis have ids");
  565. if (const auto *MD = dyn_cast<MemoryDef>(this))
  566. return MD->getID();
  567. return cast<MemoryPhi>(this)->getID();
  568. }
  569. inline bool MemoryUseOrDef::isOptimized() const {
  570. if (const auto *MD = dyn_cast<MemoryDef>(this))
  571. return MD->isOptimized();
  572. return cast<MemoryUse>(this)->isOptimized();
  573. }
  574. inline MemoryAccess *MemoryUseOrDef::getOptimized() const {
  575. if (const auto *MD = dyn_cast<MemoryDef>(this))
  576. return MD->getOptimized();
  577. return cast<MemoryUse>(this)->getOptimized();
  578. }
  579. inline void MemoryUseOrDef::setOptimized(MemoryAccess *MA) {
  580. if (auto *MD = dyn_cast<MemoryDef>(this))
  581. MD->setOptimized(MA);
  582. else
  583. cast<MemoryUse>(this)->setOptimized(MA);
  584. }
  585. inline void MemoryUseOrDef::resetOptimized() {
  586. if (auto *MD = dyn_cast<MemoryDef>(this))
  587. MD->resetOptimized();
  588. else
  589. cast<MemoryUse>(this)->resetOptimized();
  590. }
  591. template <> struct OperandTraits<MemoryPhi> : public HungoffOperandTraits<2> {};
  592. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryPhi, MemoryAccess)
  593. /// Encapsulates MemorySSA, including all data associated with memory
  594. /// accesses.
  595. class MemorySSA {
  596. public:
  597. MemorySSA(Function &, AliasAnalysis *, DominatorTree *);
  598. // MemorySSA must remain where it's constructed; Walkers it creates store
  599. // pointers to it.
  600. MemorySSA(MemorySSA &&) = delete;
  601. ~MemorySSA();
  602. MemorySSAWalker *getWalker();
  603. MemorySSAWalker *getSkipSelfWalker();
  604. /// Given a memory Mod/Ref'ing instruction, get the MemorySSA
  605. /// access associated with it. If passed a basic block gets the memory phi
  606. /// node that exists for that block, if there is one. Otherwise, this will get
  607. /// a MemoryUseOrDef.
  608. MemoryUseOrDef *getMemoryAccess(const Instruction *I) const {
  609. return cast_or_null<MemoryUseOrDef>(ValueToMemoryAccess.lookup(I));
  610. }
  611. MemoryPhi *getMemoryAccess(const BasicBlock *BB) const {
  612. return cast_or_null<MemoryPhi>(ValueToMemoryAccess.lookup(cast<Value>(BB)));
  613. }
  614. DominatorTree &getDomTree() const { return *DT; }
  615. void dump() const;
  616. void print(raw_ostream &) const;
  617. /// Return true if \p MA represents the live on entry value
  618. ///
  619. /// Loads and stores from pointer arguments and other global values may be
  620. /// defined by memory operations that do not occur in the current function, so
  621. /// they may be live on entry to the function. MemorySSA represents such
  622. /// memory state by the live on entry definition, which is guaranteed to occur
  623. /// before any other memory access in the function.
  624. inline bool isLiveOnEntryDef(const MemoryAccess *MA) const {
  625. return MA == LiveOnEntryDef.get();
  626. }
  627. inline MemoryAccess *getLiveOnEntryDef() const {
  628. return LiveOnEntryDef.get();
  629. }
  630. // Sadly, iplists, by default, owns and deletes pointers added to the
  631. // list. It's not currently possible to have two iplists for the same type,
  632. // where one owns the pointers, and one does not. This is because the traits
  633. // are per-type, not per-tag. If this ever changes, we should make the
  634. // DefList an iplist.
  635. using AccessList = iplist<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>;
  636. using DefsList =
  637. simple_ilist<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>>;
  638. /// Return the list of MemoryAccess's for a given basic block.
  639. ///
  640. /// This list is not modifiable by the user.
  641. const AccessList *getBlockAccesses(const BasicBlock *BB) const {
  642. return getWritableBlockAccesses(BB);
  643. }
  644. /// Return the list of MemoryDef's and MemoryPhi's for a given basic
  645. /// block.
  646. ///
  647. /// This list is not modifiable by the user.
  648. const DefsList *getBlockDefs(const BasicBlock *BB) const {
  649. return getWritableBlockDefs(BB);
  650. }
  651. /// Given two memory accesses in the same basic block, determine
  652. /// whether MemoryAccess \p A dominates MemoryAccess \p B.
  653. bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const;
  654. /// Given two memory accesses in potentially different blocks,
  655. /// determine whether MemoryAccess \p A dominates MemoryAccess \p B.
  656. bool dominates(const MemoryAccess *A, const MemoryAccess *B) const;
  657. /// Given a MemoryAccess and a Use, determine whether MemoryAccess \p A
  658. /// dominates Use \p B.
  659. bool dominates(const MemoryAccess *A, const Use &B) const;
  660. enum class VerificationLevel { Fast, Full };
  661. /// Verify that MemorySSA is self consistent (IE definitions dominate
  662. /// all uses, uses appear in the right places). This is used by unit tests.
  663. void verifyMemorySSA(VerificationLevel = VerificationLevel::Fast) const;
  664. /// Used in various insertion functions to specify whether we are talking
  665. /// about the beginning or end of a block.
  666. enum InsertionPlace { Beginning, End, BeforeTerminator };
  667. /// By default, uses are *not* optimized during MemorySSA construction.
  668. /// Calling this method will attempt to optimize all MemoryUses, if this has
  669. /// not happened yet for this MemorySSA instance. This should be done if you
  670. /// plan to query the clobbering access for most uses, or if you walk the
  671. /// def-use chain of uses.
  672. void ensureOptimizedUses();
  673. AliasAnalysis &getAA() { return *AA; }
  674. protected:
  675. // Used by Memory SSA dumpers and wrapper pass
  676. friend class MemorySSAPrinterLegacyPass;
  677. friend class MemorySSAUpdater;
  678. void verifyOrderingDominationAndDefUses(
  679. Function &F, VerificationLevel = VerificationLevel::Fast) const;
  680. void verifyDominationNumbers(const Function &F) const;
  681. void verifyPrevDefInPhis(Function &F) const;
  682. // This is used by the use optimizer and updater.
  683. AccessList *getWritableBlockAccesses(const BasicBlock *BB) const {
  684. auto It = PerBlockAccesses.find(BB);
  685. return It == PerBlockAccesses.end() ? nullptr : It->second.get();
  686. }
  687. // This is used by the use optimizer and updater.
  688. DefsList *getWritableBlockDefs(const BasicBlock *BB) const {
  689. auto It = PerBlockDefs.find(BB);
  690. return It == PerBlockDefs.end() ? nullptr : It->second.get();
  691. }
  692. // These is used by the updater to perform various internal MemorySSA
  693. // machinsations. They do not always leave the IR in a correct state, and
  694. // relies on the updater to fixup what it breaks, so it is not public.
  695. void moveTo(MemoryUseOrDef *What, BasicBlock *BB, AccessList::iterator Where);
  696. void moveTo(MemoryAccess *What, BasicBlock *BB, InsertionPlace Point);
  697. // Rename the dominator tree branch rooted at BB.
  698. void renamePass(BasicBlock *BB, MemoryAccess *IncomingVal,
  699. SmallPtrSetImpl<BasicBlock *> &Visited) {
  700. renamePass(DT->getNode(BB), IncomingVal, Visited, true, true);
  701. }
  702. void removeFromLookups(MemoryAccess *);
  703. void removeFromLists(MemoryAccess *, bool ShouldDelete = true);
  704. void insertIntoListsForBlock(MemoryAccess *, const BasicBlock *,
  705. InsertionPlace);
  706. void insertIntoListsBefore(MemoryAccess *, const BasicBlock *,
  707. AccessList::iterator);
  708. MemoryUseOrDef *createDefinedAccess(Instruction *, MemoryAccess *,
  709. const MemoryUseOrDef *Template = nullptr,
  710. bool CreationMustSucceed = true);
  711. private:
  712. class ClobberWalkerBase;
  713. class CachingWalker;
  714. class SkipSelfWalker;
  715. class OptimizeUses;
  716. CachingWalker *getWalkerImpl();
  717. void buildMemorySSA(BatchAAResults &BAA);
  718. void prepareForMoveTo(MemoryAccess *, BasicBlock *);
  719. void verifyUseInDefs(MemoryAccess *, MemoryAccess *) const;
  720. using AccessMap = DenseMap<const BasicBlock *, std::unique_ptr<AccessList>>;
  721. using DefsMap = DenseMap<const BasicBlock *, std::unique_ptr<DefsList>>;
  722. void markUnreachableAsLiveOnEntry(BasicBlock *BB);
  723. MemoryPhi *createMemoryPhi(BasicBlock *BB);
  724. template <typename AliasAnalysisType>
  725. MemoryUseOrDef *createNewAccess(Instruction *, AliasAnalysisType *,
  726. const MemoryUseOrDef *Template = nullptr);
  727. void placePHINodes(const SmallPtrSetImpl<BasicBlock *> &);
  728. MemoryAccess *renameBlock(BasicBlock *, MemoryAccess *, bool);
  729. void renameSuccessorPhis(BasicBlock *, MemoryAccess *, bool);
  730. void renamePass(DomTreeNode *, MemoryAccess *IncomingVal,
  731. SmallPtrSetImpl<BasicBlock *> &Visited,
  732. bool SkipVisited = false, bool RenameAllUses = false);
  733. AccessList *getOrCreateAccessList(const BasicBlock *);
  734. DefsList *getOrCreateDefsList(const BasicBlock *);
  735. void renumberBlock(const BasicBlock *) const;
  736. AliasAnalysis *AA = nullptr;
  737. DominatorTree *DT;
  738. Function &F;
  739. // Memory SSA mappings
  740. DenseMap<const Value *, MemoryAccess *> ValueToMemoryAccess;
  741. // These two mappings contain the main block to access/def mappings for
  742. // MemorySSA. The list contained in PerBlockAccesses really owns all the
  743. // MemoryAccesses.
  744. // Both maps maintain the invariant that if a block is found in them, the
  745. // corresponding list is not empty, and if a block is not found in them, the
  746. // corresponding list is empty.
  747. AccessMap PerBlockAccesses;
  748. DefsMap PerBlockDefs;
  749. std::unique_ptr<MemoryAccess, ValueDeleter> LiveOnEntryDef;
  750. // Domination mappings
  751. // Note that the numbering is local to a block, even though the map is
  752. // global.
  753. mutable SmallPtrSet<const BasicBlock *, 16> BlockNumberingValid;
  754. mutable DenseMap<const MemoryAccess *, unsigned long> BlockNumbering;
  755. // Memory SSA building info
  756. std::unique_ptr<ClobberWalkerBase> WalkerBase;
  757. std::unique_ptr<CachingWalker> Walker;
  758. std::unique_ptr<SkipSelfWalker> SkipWalker;
  759. unsigned NextID = 0;
  760. bool IsOptimized = false;
  761. };
  762. /// Enables verification of MemorySSA.
  763. ///
  764. /// The checks which this flag enables is exensive and disabled by default
  765. /// unless `EXPENSIVE_CHECKS` is defined. The flag `-verify-memoryssa` can be
  766. /// used to selectively enable the verification without re-compilation.
  767. extern bool VerifyMemorySSA;
  768. // Internal MemorySSA utils, for use by MemorySSA classes and walkers
  769. class MemorySSAUtil {
  770. protected:
  771. friend class GVNHoist;
  772. friend class MemorySSAWalker;
  773. // This function should not be used by new passes.
  774. static bool defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
  775. AliasAnalysis &AA);
  776. };
  777. // This pass does eager building and then printing of MemorySSA. It is used by
  778. // the tests to be able to build, dump, and verify Memory SSA.
  779. class MemorySSAPrinterLegacyPass : public FunctionPass {
  780. public:
  781. MemorySSAPrinterLegacyPass();
  782. bool runOnFunction(Function &) override;
  783. void getAnalysisUsage(AnalysisUsage &AU) const override;
  784. static char ID;
  785. };
  786. /// An analysis that produces \c MemorySSA for a function.
  787. ///
  788. class MemorySSAAnalysis : public AnalysisInfoMixin<MemorySSAAnalysis> {
  789. friend AnalysisInfoMixin<MemorySSAAnalysis>;
  790. static AnalysisKey Key;
  791. public:
  792. // Wrap MemorySSA result to ensure address stability of internal MemorySSA
  793. // pointers after construction. Use a wrapper class instead of plain
  794. // unique_ptr<MemorySSA> to avoid build breakage on MSVC.
  795. struct Result {
  796. Result(std::unique_ptr<MemorySSA> &&MSSA) : MSSA(std::move(MSSA)) {}
  797. MemorySSA &getMSSA() { return *MSSA.get(); }
  798. std::unique_ptr<MemorySSA> MSSA;
  799. bool invalidate(Function &F, const PreservedAnalyses &PA,
  800. FunctionAnalysisManager::Invalidator &Inv);
  801. };
  802. Result run(Function &F, FunctionAnalysisManager &AM);
  803. };
  804. /// Printer pass for \c MemorySSA.
  805. class MemorySSAPrinterPass : public PassInfoMixin<MemorySSAPrinterPass> {
  806. raw_ostream &OS;
  807. public:
  808. explicit MemorySSAPrinterPass(raw_ostream &OS) : OS(OS) {}
  809. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  810. };
  811. /// Printer pass for \c MemorySSA via the walker.
  812. class MemorySSAWalkerPrinterPass
  813. : public PassInfoMixin<MemorySSAWalkerPrinterPass> {
  814. raw_ostream &OS;
  815. public:
  816. explicit MemorySSAWalkerPrinterPass(raw_ostream &OS) : OS(OS) {}
  817. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  818. };
  819. /// Verifier pass for \c MemorySSA.
  820. struct MemorySSAVerifierPass : PassInfoMixin<MemorySSAVerifierPass> {
  821. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  822. };
  823. /// Legacy analysis pass which computes \c MemorySSA.
  824. class MemorySSAWrapperPass : public FunctionPass {
  825. public:
  826. MemorySSAWrapperPass();
  827. static char ID;
  828. bool runOnFunction(Function &) override;
  829. void releaseMemory() override;
  830. MemorySSA &getMSSA() { return *MSSA; }
  831. const MemorySSA &getMSSA() const { return *MSSA; }
  832. void getAnalysisUsage(AnalysisUsage &AU) const override;
  833. void verifyAnalysis() const override;
  834. void print(raw_ostream &OS, const Module *M = nullptr) const override;
  835. private:
  836. std::unique_ptr<MemorySSA> MSSA;
  837. };
  838. /// This is the generic walker interface for walkers of MemorySSA.
  839. /// Walkers are used to be able to further disambiguate the def-use chains
  840. /// MemorySSA gives you, or otherwise produce better info than MemorySSA gives
  841. /// you.
  842. /// In particular, while the def-use chains provide basic information, and are
  843. /// guaranteed to give, for example, the nearest may-aliasing MemoryDef for a
  844. /// MemoryUse as AliasAnalysis considers it, a user mant want better or other
  845. /// information. In particular, they may want to use SCEV info to further
  846. /// disambiguate memory accesses, or they may want the nearest dominating
  847. /// may-aliasing MemoryDef for a call or a store. This API enables a
  848. /// standardized interface to getting and using that info.
  849. class MemorySSAWalker {
  850. public:
  851. MemorySSAWalker(MemorySSA *);
  852. virtual ~MemorySSAWalker() = default;
  853. using MemoryAccessSet = SmallVector<MemoryAccess *, 8>;
  854. /// Given a memory Mod/Ref/ModRef'ing instruction, calling this
  855. /// will give you the nearest dominating MemoryAccess that Mod's the location
  856. /// the instruction accesses (by skipping any def which AA can prove does not
  857. /// alias the location(s) accessed by the instruction given).
  858. ///
  859. /// Note that this will return a single access, and it must dominate the
  860. /// Instruction, so if an operand of a MemoryPhi node Mod's the instruction,
  861. /// this will return the MemoryPhi, not the operand. This means that
  862. /// given:
  863. /// if (a) {
  864. /// 1 = MemoryDef(liveOnEntry)
  865. /// store %a
  866. /// } else {
  867. /// 2 = MemoryDef(liveOnEntry)
  868. /// store %b
  869. /// }
  870. /// 3 = MemoryPhi(2, 1)
  871. /// MemoryUse(3)
  872. /// load %a
  873. ///
  874. /// calling this API on load(%a) will return the MemoryPhi, not the MemoryDef
  875. /// in the if (a) branch.
  876. MemoryAccess *getClobberingMemoryAccess(const Instruction *I,
  877. BatchAAResults &AA) {
  878. MemoryAccess *MA = MSSA->getMemoryAccess(I);
  879. assert(MA && "Handed an instruction that MemorySSA doesn't recognize?");
  880. return getClobberingMemoryAccess(MA, AA);
  881. }
  882. /// Does the same thing as getClobberingMemoryAccess(const Instruction *I),
  883. /// but takes a MemoryAccess instead of an Instruction.
  884. virtual MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
  885. BatchAAResults &AA) = 0;
  886. /// Given a potentially clobbering memory access and a new location,
  887. /// calling this will give you the nearest dominating clobbering MemoryAccess
  888. /// (by skipping non-aliasing def links).
  889. ///
  890. /// This version of the function is mainly used to disambiguate phi translated
  891. /// pointers, where the value of a pointer may have changed from the initial
  892. /// memory access. Note that this expects to be handed either a MemoryUse,
  893. /// or an already potentially clobbering access. Unlike the above API, if
  894. /// given a MemoryDef that clobbers the pointer as the starting access, it
  895. /// will return that MemoryDef, whereas the above would return the clobber
  896. /// starting from the use side of the memory def.
  897. virtual MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
  898. const MemoryLocation &,
  899. BatchAAResults &AA) = 0;
  900. MemoryAccess *getClobberingMemoryAccess(const Instruction *I) {
  901. BatchAAResults BAA(MSSA->getAA());
  902. return getClobberingMemoryAccess(I, BAA);
  903. }
  904. MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA) {
  905. BatchAAResults BAA(MSSA->getAA());
  906. return getClobberingMemoryAccess(MA, BAA);
  907. }
  908. MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
  909. const MemoryLocation &Loc) {
  910. BatchAAResults BAA(MSSA->getAA());
  911. return getClobberingMemoryAccess(MA, Loc, BAA);
  912. }
  913. /// Given a memory access, invalidate anything this walker knows about
  914. /// that access.
  915. /// This API is used by walkers that store information to perform basic cache
  916. /// invalidation. This will be called by MemorySSA at appropriate times for
  917. /// the walker it uses or returns.
  918. virtual void invalidateInfo(MemoryAccess *) {}
  919. protected:
  920. friend class MemorySSA; // For updating MSSA pointer in MemorySSA move
  921. // constructor.
  922. MemorySSA *MSSA;
  923. };
  924. /// A MemorySSAWalker that does no alias queries, or anything else. It
  925. /// simply returns the links as they were constructed by the builder.
  926. class DoNothingMemorySSAWalker final : public MemorySSAWalker {
  927. public:
  928. // Keep the overrides below from hiding the Instruction overload of
  929. // getClobberingMemoryAccess.
  930. using MemorySSAWalker::getClobberingMemoryAccess;
  931. MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
  932. BatchAAResults &) override;
  933. MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
  934. const MemoryLocation &,
  935. BatchAAResults &) override;
  936. };
  937. using MemoryAccessPair = std::pair<MemoryAccess *, MemoryLocation>;
  938. using ConstMemoryAccessPair = std::pair<const MemoryAccess *, MemoryLocation>;
  939. /// Iterator base class used to implement const and non-const iterators
  940. /// over the defining accesses of a MemoryAccess.
  941. template <class T>
  942. class memoryaccess_def_iterator_base
  943. : public iterator_facade_base<memoryaccess_def_iterator_base<T>,
  944. std::forward_iterator_tag, T, ptrdiff_t, T *,
  945. T *> {
  946. using BaseT = typename memoryaccess_def_iterator_base::iterator_facade_base;
  947. public:
  948. memoryaccess_def_iterator_base(T *Start) : Access(Start) {}
  949. memoryaccess_def_iterator_base() = default;
  950. bool operator==(const memoryaccess_def_iterator_base &Other) const {
  951. return Access == Other.Access && (!Access || ArgNo == Other.ArgNo);
  952. }
  953. // This is a bit ugly, but for MemoryPHI's, unlike PHINodes, you can't get the
  954. // block from the operand in constant time (In a PHINode, the uselist has
  955. // both, so it's just subtraction). We provide it as part of the
  956. // iterator to avoid callers having to linear walk to get the block.
  957. // If the operation becomes constant time on MemoryPHI's, this bit of
  958. // abstraction breaking should be removed.
  959. BasicBlock *getPhiArgBlock() const {
  960. MemoryPhi *MP = dyn_cast<MemoryPhi>(Access);
  961. assert(MP && "Tried to get phi arg block when not iterating over a PHI");
  962. return MP->getIncomingBlock(ArgNo);
  963. }
  964. typename std::iterator_traits<BaseT>::pointer operator*() const {
  965. assert(Access && "Tried to access past the end of our iterator");
  966. // Go to the first argument for phis, and the defining access for everything
  967. // else.
  968. if (const MemoryPhi *MP = dyn_cast<MemoryPhi>(Access))
  969. return MP->getIncomingValue(ArgNo);
  970. return cast<MemoryUseOrDef>(Access)->getDefiningAccess();
  971. }
  972. using BaseT::operator++;
  973. memoryaccess_def_iterator_base &operator++() {
  974. assert(Access && "Hit end of iterator");
  975. if (const MemoryPhi *MP = dyn_cast<MemoryPhi>(Access)) {
  976. if (++ArgNo >= MP->getNumIncomingValues()) {
  977. ArgNo = 0;
  978. Access = nullptr;
  979. }
  980. } else {
  981. Access = nullptr;
  982. }
  983. return *this;
  984. }
  985. private:
  986. T *Access = nullptr;
  987. unsigned ArgNo = 0;
  988. };
  989. inline memoryaccess_def_iterator MemoryAccess::defs_begin() {
  990. return memoryaccess_def_iterator(this);
  991. }
  992. inline const_memoryaccess_def_iterator MemoryAccess::defs_begin() const {
  993. return const_memoryaccess_def_iterator(this);
  994. }
  995. inline memoryaccess_def_iterator MemoryAccess::defs_end() {
  996. return memoryaccess_def_iterator();
  997. }
  998. inline const_memoryaccess_def_iterator MemoryAccess::defs_end() const {
  999. return const_memoryaccess_def_iterator();
  1000. }
  1001. /// GraphTraits for a MemoryAccess, which walks defs in the normal case,
  1002. /// and uses in the inverse case.
  1003. template <> struct GraphTraits<MemoryAccess *> {
  1004. using NodeRef = MemoryAccess *;
  1005. using ChildIteratorType = memoryaccess_def_iterator;
  1006. static NodeRef getEntryNode(NodeRef N) { return N; }
  1007. static ChildIteratorType child_begin(NodeRef N) { return N->defs_begin(); }
  1008. static ChildIteratorType child_end(NodeRef N) { return N->defs_end(); }
  1009. };
  1010. template <> struct GraphTraits<Inverse<MemoryAccess *>> {
  1011. using NodeRef = MemoryAccess *;
  1012. using ChildIteratorType = MemoryAccess::iterator;
  1013. static NodeRef getEntryNode(NodeRef N) { return N; }
  1014. static ChildIteratorType child_begin(NodeRef N) { return N->user_begin(); }
  1015. static ChildIteratorType child_end(NodeRef N) { return N->user_end(); }
  1016. };
  1017. /// Provide an iterator that walks defs, giving both the memory access,
  1018. /// and the current pointer location, updating the pointer location as it
  1019. /// changes due to phi node translation.
  1020. ///
  1021. /// This iterator, while somewhat specialized, is what most clients actually
  1022. /// want when walking upwards through MemorySSA def chains. It takes a pair of
  1023. /// <MemoryAccess,MemoryLocation>, and walks defs, properly translating the
  1024. /// memory location through phi nodes for the user.
  1025. class upward_defs_iterator
  1026. : public iterator_facade_base<upward_defs_iterator,
  1027. std::forward_iterator_tag,
  1028. const MemoryAccessPair> {
  1029. using BaseT = upward_defs_iterator::iterator_facade_base;
  1030. public:
  1031. upward_defs_iterator(const MemoryAccessPair &Info, DominatorTree *DT)
  1032. : DefIterator(Info.first), Location(Info.second),
  1033. OriginalAccess(Info.first), DT(DT) {
  1034. CurrentPair.first = nullptr;
  1035. WalkingPhi = Info.first && isa<MemoryPhi>(Info.first);
  1036. fillInCurrentPair();
  1037. }
  1038. upward_defs_iterator() { CurrentPair.first = nullptr; }
  1039. bool operator==(const upward_defs_iterator &Other) const {
  1040. return DefIterator == Other.DefIterator;
  1041. }
  1042. typename std::iterator_traits<BaseT>::reference operator*() const {
  1043. assert(DefIterator != OriginalAccess->defs_end() &&
  1044. "Tried to access past the end of our iterator");
  1045. return CurrentPair;
  1046. }
  1047. using BaseT::operator++;
  1048. upward_defs_iterator &operator++() {
  1049. assert(DefIterator != OriginalAccess->defs_end() &&
  1050. "Tried to access past the end of the iterator");
  1051. ++DefIterator;
  1052. if (DefIterator != OriginalAccess->defs_end())
  1053. fillInCurrentPair();
  1054. return *this;
  1055. }
  1056. BasicBlock *getPhiArgBlock() const { return DefIterator.getPhiArgBlock(); }
  1057. private:
  1058. /// Returns true if \p Ptr is guaranteed to be loop invariant for any possible
  1059. /// loop. In particular, this guarantees that it only references a single
  1060. /// MemoryLocation during execution of the containing function.
  1061. bool IsGuaranteedLoopInvariant(const Value *Ptr) const;
  1062. void fillInCurrentPair() {
  1063. CurrentPair.first = *DefIterator;
  1064. CurrentPair.second = Location;
  1065. if (WalkingPhi && Location.Ptr) {
  1066. PHITransAddr Translator(
  1067. const_cast<Value *>(Location.Ptr),
  1068. OriginalAccess->getBlock()->getModule()->getDataLayout(), nullptr);
  1069. if (!Translator.PHITranslateValue(OriginalAccess->getBlock(),
  1070. DefIterator.getPhiArgBlock(), DT, true))
  1071. if (Translator.getAddr() != CurrentPair.second.Ptr)
  1072. CurrentPair.second =
  1073. CurrentPair.second.getWithNewPtr(Translator.getAddr());
  1074. // Mark size as unknown, if the location is not guaranteed to be
  1075. // loop-invariant for any possible loop in the function. Setting the size
  1076. // to unknown guarantees that any memory accesses that access locations
  1077. // after the pointer are considered as clobbers, which is important to
  1078. // catch loop carried dependences.
  1079. if (!IsGuaranteedLoopInvariant(CurrentPair.second.Ptr))
  1080. CurrentPair.second = CurrentPair.second.getWithNewSize(
  1081. LocationSize::beforeOrAfterPointer());
  1082. }
  1083. }
  1084. MemoryAccessPair CurrentPair;
  1085. memoryaccess_def_iterator DefIterator;
  1086. MemoryLocation Location;
  1087. MemoryAccess *OriginalAccess = nullptr;
  1088. DominatorTree *DT = nullptr;
  1089. bool WalkingPhi = false;
  1090. };
  1091. inline upward_defs_iterator
  1092. upward_defs_begin(const MemoryAccessPair &Pair, DominatorTree &DT) {
  1093. return upward_defs_iterator(Pair, &DT);
  1094. }
  1095. inline upward_defs_iterator upward_defs_end() { return upward_defs_iterator(); }
  1096. inline iterator_range<upward_defs_iterator>
  1097. upward_defs(const MemoryAccessPair &Pair, DominatorTree &DT) {
  1098. return make_range(upward_defs_begin(Pair, DT), upward_defs_end());
  1099. }
  1100. /// Walks the defining accesses of MemoryDefs. Stops after we hit something that
  1101. /// has no defining use (e.g. a MemoryPhi or liveOnEntry). Note that, when
  1102. /// comparing against a null def_chain_iterator, this will compare equal only
  1103. /// after walking said Phi/liveOnEntry.
  1104. ///
  1105. /// The UseOptimizedChain flag specifies whether to walk the clobbering
  1106. /// access chain, or all the accesses.
  1107. ///
  1108. /// Normally, MemoryDef are all just def/use linked together, so a def_chain on
  1109. /// a MemoryDef will walk all MemoryDefs above it in the program until it hits
  1110. /// a phi node. The optimized chain walks the clobbering access of a store.
  1111. /// So if you are just trying to find, given a store, what the next
  1112. /// thing that would clobber the same memory is, you want the optimized chain.
  1113. template <class T, bool UseOptimizedChain = false>
  1114. struct def_chain_iterator
  1115. : public iterator_facade_base<def_chain_iterator<T, UseOptimizedChain>,
  1116. std::forward_iterator_tag, MemoryAccess *> {
  1117. def_chain_iterator() : MA(nullptr) {}
  1118. def_chain_iterator(T MA) : MA(MA) {}
  1119. T operator*() const { return MA; }
  1120. def_chain_iterator &operator++() {
  1121. // N.B. liveOnEntry has a null defining access.
  1122. if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
  1123. if (UseOptimizedChain && MUD->isOptimized())
  1124. MA = MUD->getOptimized();
  1125. else
  1126. MA = MUD->getDefiningAccess();
  1127. } else {
  1128. MA = nullptr;
  1129. }
  1130. return *this;
  1131. }
  1132. bool operator==(const def_chain_iterator &O) const { return MA == O.MA; }
  1133. private:
  1134. T MA;
  1135. };
  1136. template <class T>
  1137. inline iterator_range<def_chain_iterator<T>>
  1138. def_chain(T MA, MemoryAccess *UpTo = nullptr) {
  1139. #ifdef EXPENSIVE_CHECKS
  1140. assert((!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator<T>()) &&
  1141. "UpTo isn't in the def chain!");
  1142. #endif
  1143. return make_range(def_chain_iterator<T>(MA), def_chain_iterator<T>(UpTo));
  1144. }
  1145. template <class T>
  1146. inline iterator_range<def_chain_iterator<T, true>> optimized_def_chain(T MA) {
  1147. return make_range(def_chain_iterator<T, true>(MA),
  1148. def_chain_iterator<T, true>(nullptr));
  1149. }
  1150. } // end namespace llvm
  1151. #endif // LLVM_ANALYSIS_MEMORYSSA_H
  1152. #ifdef __GNUC__
  1153. #pragma GCC diagnostic pop
  1154. #endif