MemorySSAUpdater.h 15 KB

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