MemorySSAUpdater.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- MemorySSAUpdater.h - Memory SSA Updater-------------------*- 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. // An automatic updater for MemorySSA that handles arbitrary insertion,
  16. // deletion, and moves. It performs phi insertion where necessary, and
  17. // automatically updates the MemorySSA IR to be correct.
  18. // While updating loads or removing instructions is often easy enough to not
  19. // need this, updating stores should generally not be attemped outside this
  20. // API.
  21. //
  22. // Basic API usage:
  23. // Create the memory access you want for the instruction (this is mainly so
  24. // we know where it is, without having to duplicate the entire set of create
  25. // functions MemorySSA supports).
  26. // Call insertDef or insertUse depending on whether it's a MemoryUse or a
  27. // MemoryDef.
  28. // That's it.
  29. //
  30. // For moving, first, move the instruction itself using the normal SSA
  31. // instruction moving API, then just call moveBefore, moveAfter,or moveTo with
  32. // the right arguments.
  33. //
  34. //===----------------------------------------------------------------------===//
  35. #ifndef LLVM_ANALYSIS_MEMORYSSAUPDATER_H
  36. #define LLVM_ANALYSIS_MEMORYSSAUPDATER_H
  37. #include "llvm/ADT/SmallPtrSet.h"
  38. #include "llvm/ADT/SmallSet.h"
  39. #include "llvm/ADT/SmallVector.h"
  40. #include "llvm/Analysis/MemorySSA.h"
  41. #include "llvm/IR/ValueHandle.h"
  42. #include "llvm/IR/ValueMap.h"
  43. #include "llvm/Support/CFGDiff.h"
  44. namespace llvm {
  45. class BasicBlock;
  46. class DominatorTree;
  47. class Instruction;
  48. class LoopBlocksRPO;
  49. template <typename T, unsigned int N> class SmallSetVector;
  50. using ValueToValueMapTy = ValueMap<const Value *, WeakTrackingVH>;
  51. using PhiToDefMap = SmallDenseMap<MemoryPhi *, MemoryAccess *>;
  52. using CFGUpdate = cfg::Update<BasicBlock *>;
  53. class MemorySSAUpdater {
  54. private:
  55. MemorySSA *MSSA;
  56. /// We use WeakVH rather than a costly deletion to deal with dangling pointers.
  57. /// MemoryPhis are created eagerly and sometimes get zapped shortly afterwards.
  58. SmallVector<WeakVH, 16> InsertedPHIs;
  59. SmallPtrSet<BasicBlock *, 8> VisitedBlocks;
  60. SmallSet<AssertingVH<MemoryPhi>, 8> NonOptPhis;
  61. public:
  62. MemorySSAUpdater(MemorySSA *MSSA) : MSSA(MSSA) {}
  63. /// Insert a definition into the MemorySSA IR. RenameUses will rename any use
  64. /// below the new def block (and any inserted phis). RenameUses should be set
  65. /// to true if the definition may cause new aliases for loads below it. This
  66. /// is not the case for hoisting or sinking or other forms of code *movement*.
  67. /// It *is* the case for straight code insertion.
  68. /// For example:
  69. /// store a
  70. /// if (foo) { }
  71. /// load a
  72. ///
  73. /// Moving the store into the if block, and calling insertDef, does not
  74. /// require RenameUses.
  75. /// However, changing it to:
  76. /// store a
  77. /// if (foo) { store b }
  78. /// load a
  79. /// Where a mayalias b, *does* require RenameUses be set to true.
  80. void insertDef(MemoryDef *Def, bool RenameUses = false);
  81. void insertUse(MemoryUse *Use, bool RenameUses = false);
  82. /// Update the MemoryPhi in `To` following an edge deletion between `From` and
  83. /// `To`. If `To` becomes unreachable, a call to removeBlocks should be made.
  84. void removeEdge(BasicBlock *From, BasicBlock *To);
  85. /// Update the MemoryPhi in `To` to have a single incoming edge from `From`,
  86. /// following a CFG change that replaced multiple edges (switch) with a direct
  87. /// branch.
  88. void removeDuplicatePhiEdgesBetween(const BasicBlock *From,
  89. const BasicBlock *To);
  90. /// Update MemorySSA when inserting a unique backedge block for a loop.
  91. void updatePhisWhenInsertingUniqueBackedgeBlock(BasicBlock *LoopHeader,
  92. BasicBlock *LoopPreheader,
  93. BasicBlock *BackedgeBlock);
  94. /// Update MemorySSA after a loop was cloned, given the blocks in RPO order,
  95. /// the exit blocks and a 1:1 mapping of all blocks and instructions
  96. /// cloned. This involves duplicating all defs and uses in the cloned blocks
  97. /// Updating phi nodes in exit block successors is done separately.
  98. void updateForClonedLoop(const LoopBlocksRPO &LoopBlocks,
  99. ArrayRef<BasicBlock *> ExitBlocks,
  100. const ValueToValueMapTy &VM,
  101. bool IgnoreIncomingWithNoClones = false);
  102. // Block BB was fully or partially cloned into its predecessor P1. Map
  103. // contains the 1:1 mapping of instructions cloned and VM[BB]=P1.
  104. void updateForClonedBlockIntoPred(BasicBlock *BB, BasicBlock *P1,
  105. const ValueToValueMapTy &VM);
  106. /// Update phi nodes in exit block successors following cloning. Exit blocks
  107. /// that were not cloned don't have additional predecessors added.
  108. void updateExitBlocksForClonedLoop(ArrayRef<BasicBlock *> ExitBlocks,
  109. const ValueToValueMapTy &VMap,
  110. DominatorTree &DT);
  111. void updateExitBlocksForClonedLoop(
  112. ArrayRef<BasicBlock *> ExitBlocks,
  113. ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps, DominatorTree &DT);
  114. /// Apply CFG updates, analogous with the DT edge updates. By default, the
  115. /// DT is assumed to be already up to date. If UpdateDTFirst is true, first
  116. /// update the DT with the same updates.
  117. void applyUpdates(ArrayRef<CFGUpdate> Updates, DominatorTree &DT,
  118. bool UpdateDTFirst = false);
  119. /// Apply CFG insert updates, analogous with the DT edge updates.
  120. void applyInsertUpdates(ArrayRef<CFGUpdate> Updates, DominatorTree &DT);
  121. void moveBefore(MemoryUseOrDef *What, MemoryUseOrDef *Where);
  122. void moveAfter(MemoryUseOrDef *What, MemoryUseOrDef *Where);
  123. void moveToPlace(MemoryUseOrDef *What, BasicBlock *BB,
  124. MemorySSA::InsertionPlace Where);
  125. /// `From` block was spliced into `From` and `To`. There is a CFG edge from
  126. /// `From` to `To`. Move all accesses from `From` to `To` starting at
  127. /// instruction `Start`. `To` is newly created BB, so empty of
  128. /// MemorySSA::MemoryAccesses. Edges are already updated, so successors of
  129. /// `To` with MPhi nodes need to update incoming block.
  130. /// |------| |------|
  131. /// | From | | From |
  132. /// | | |------|
  133. /// | | ||
  134. /// | | => \/
  135. /// | | |------| <- Start
  136. /// | | | To |
  137. /// |------| |------|
  138. void moveAllAfterSpliceBlocks(BasicBlock *From, BasicBlock *To,
  139. Instruction *Start);
  140. /// `From` block was merged into `To`. There is a CFG edge from `To` to
  141. /// `From`.`To` still branches to `From`, but all instructions were moved and
  142. /// `From` is now an empty block; `From` is about to be deleted. Move all
  143. /// accesses from `From` to `To` starting at instruction `Start`. `To` may
  144. /// have multiple successors, `From` has a single predecessor. `From` may have
  145. /// successors with MPhi nodes, replace their incoming block with `To`.
  146. /// |------| |------|
  147. /// | To | | To |
  148. /// |------| | |
  149. /// || => | |
  150. /// \/ | |
  151. /// |------| | | <- Start
  152. /// | From | | |
  153. /// |------| |------|
  154. void moveAllAfterMergeBlocks(BasicBlock *From, BasicBlock *To,
  155. Instruction *Start);
  156. /// A new empty BasicBlock (New) now branches directly to Old. Some of
  157. /// Old's predecessors (Preds) are now branching to New instead of Old.
  158. /// If New is the only predecessor, move Old's Phi, if present, to New.
  159. /// Otherwise, add a new Phi in New with appropriate incoming values, and
  160. /// update the incoming values in Old's Phi node too, if present.
  161. void wireOldPredecessorsToNewImmediatePredecessor(
  162. BasicBlock *Old, BasicBlock *New, ArrayRef<BasicBlock *> Preds,
  163. bool IdenticalEdgesWereMerged = true);
  164. // The below are utility functions. Other than creation of accesses to pass
  165. // to insertDef, and removeAccess to remove accesses, you should generally
  166. // not attempt to update memoryssa yourself. It is very non-trivial to get
  167. // the edge cases right, and the above calls already operate in near-optimal
  168. // time bounds.
  169. /// Create a MemoryAccess in MemorySSA at a specified point in a block,
  170. /// with a specified clobbering definition.
  171. ///
  172. /// Returns the new MemoryAccess.
  173. /// This should be called when a memory instruction is created that is being
  174. /// used to replace an existing memory instruction. It will *not* create PHI
  175. /// nodes, or verify the clobbering definition. The insertion place is used
  176. /// solely to determine where in the memoryssa access lists the instruction
  177. /// will be placed. The caller is expected to keep ordering the same as
  178. /// instructions.
  179. /// It will return the new MemoryAccess.
  180. /// Note: If a MemoryAccess already exists for I, this function will make it
  181. /// inaccessible and it *must* have removeMemoryAccess called on it.
  182. MemoryAccess *createMemoryAccessInBB(Instruction *I, MemoryAccess *Definition,
  183. const BasicBlock *BB,
  184. MemorySSA::InsertionPlace Point);
  185. /// Create a MemoryAccess in MemorySSA before or after an existing
  186. /// MemoryAccess.
  187. ///
  188. /// Returns the new MemoryAccess.
  189. /// This should be called when a memory instruction is created that is being
  190. /// used to replace an existing memory instruction. It will *not* create PHI
  191. /// nodes, or verify the clobbering definition.
  192. ///
  193. /// Note: If a MemoryAccess already exists for I, this function will make it
  194. /// inaccessible and it *must* have removeMemoryAccess called on it.
  195. MemoryUseOrDef *createMemoryAccessBefore(Instruction *I,
  196. MemoryAccess *Definition,
  197. MemoryUseOrDef *InsertPt);
  198. MemoryUseOrDef *createMemoryAccessAfter(Instruction *I,
  199. MemoryAccess *Definition,
  200. MemoryAccess *InsertPt);
  201. /// Remove a MemoryAccess from MemorySSA, including updating all
  202. /// definitions and uses.
  203. /// This should be called when a memory instruction that has a MemoryAccess
  204. /// associated with it is erased from the program. For example, if a store or
  205. /// load is simply erased (not replaced), removeMemoryAccess should be called
  206. /// on the MemoryAccess for that store/load.
  207. void removeMemoryAccess(MemoryAccess *, bool OptimizePhis = false);
  208. /// Remove MemoryAccess for a given instruction, if a MemoryAccess exists.
  209. /// This should be called when an instruction (load/store) is deleted from
  210. /// the program.
  211. void removeMemoryAccess(const Instruction *I, bool OptimizePhis = false) {
  212. if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
  213. removeMemoryAccess(MA, OptimizePhis);
  214. }
  215. /// Remove all MemoryAcceses in a set of BasicBlocks about to be deleted.
  216. /// Assumption we make here: all uses of deleted defs and phi must either
  217. /// occur in blocks about to be deleted (thus will be deleted as well), or
  218. /// they occur in phis that will simply lose an incoming value.
  219. /// Deleted blocks still have successor info, but their predecessor edges and
  220. /// Phi nodes may already be updated. Instructions in DeadBlocks should be
  221. /// deleted after this call.
  222. void removeBlocks(const SmallSetVector<BasicBlock *, 8> &DeadBlocks);
  223. /// Instruction I will be changed to an unreachable. Remove all accesses in
  224. /// I's block that follow I (inclusive), and update the Phis in the blocks'
  225. /// successors.
  226. void changeToUnreachable(const Instruction *I);
  227. /// Get handle on MemorySSA.
  228. MemorySSA* getMemorySSA() const { return MSSA; }
  229. private:
  230. // Move What before Where in the MemorySSA IR.
  231. template <class WhereType>
  232. void moveTo(MemoryUseOrDef *What, BasicBlock *BB, WhereType Where);
  233. // Move all memory accesses from `From` to `To` starting at `Start`.
  234. // Restrictions apply, see public wrappers of this method.
  235. void moveAllAccesses(BasicBlock *From, BasicBlock *To, Instruction *Start);
  236. MemoryAccess *getPreviousDef(MemoryAccess *);
  237. MemoryAccess *getPreviousDefInBlock(MemoryAccess *);
  238. MemoryAccess *
  239. getPreviousDefFromEnd(BasicBlock *,
  240. DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> &);
  241. MemoryAccess *
  242. getPreviousDefRecursive(BasicBlock *,
  243. DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> &);
  244. MemoryAccess *recursePhi(MemoryAccess *Phi);
  245. MemoryAccess *tryRemoveTrivialPhi(MemoryPhi *Phi);
  246. template <class RangeType>
  247. MemoryAccess *tryRemoveTrivialPhi(MemoryPhi *Phi, RangeType &Operands);
  248. void tryRemoveTrivialPhis(ArrayRef<WeakVH> UpdatedPHIs);
  249. void fixupDefs(const SmallVectorImpl<WeakVH> &);
  250. // Clone all uses and defs from BB to NewBB given a 1:1 map of all
  251. // instructions and blocks cloned, and a map of MemoryPhi : Definition
  252. // (MemoryAccess Phi or Def). VMap maps old instructions to cloned
  253. // instructions and old blocks to cloned blocks. MPhiMap, is created in the
  254. // caller of this private method, and maps existing MemoryPhis to new
  255. // definitions that new MemoryAccesses must point to. These definitions may
  256. // not necessarily be MemoryPhis themselves, they may be MemoryDefs. As such,
  257. // the map is between MemoryPhis and MemoryAccesses, where the MemoryAccesses
  258. // may be MemoryPhis or MemoryDefs and not MemoryUses.
  259. // If CloneWasSimplified = true, the clone was exact. Otherwise, assume that
  260. // the clone involved simplifications that may have: (1) turned a MemoryUse
  261. // into an instruction that MemorySSA has no representation for, or (2) turned
  262. // a MemoryDef into a MemoryUse or an instruction that MemorySSA has no
  263. // representation for. No other cases are supported.
  264. void cloneUsesAndDefs(BasicBlock *BB, BasicBlock *NewBB,
  265. const ValueToValueMapTy &VMap, PhiToDefMap &MPhiMap,
  266. bool CloneWasSimplified = false);
  267. template <typename Iter>
  268. void privateUpdateExitBlocksForClonedLoop(ArrayRef<BasicBlock *> ExitBlocks,
  269. Iter ValuesBegin, Iter ValuesEnd,
  270. DominatorTree &DT);
  271. void applyInsertUpdates(ArrayRef<CFGUpdate>, DominatorTree &DT,
  272. const GraphDiff<BasicBlock *> *GD);
  273. };
  274. } // end namespace llvm
  275. #endif // LLVM_ANALYSIS_MEMORYSSAUPDATER_H
  276. #ifdef __GNUC__
  277. #pragma GCC diagnostic pop
  278. #endif