LLVM  9.0.0svn
MemorySSAUpdater.h
Go to the documentation of this file.
1 //===- MemorySSAUpdater.h - Memory SSA Updater-------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // \file
10 // An automatic updater for MemorySSA that handles arbitrary insertion,
11 // deletion, and moves. It performs phi insertion where necessary, and
12 // automatically updates the MemorySSA IR to be correct.
13 // While updating loads or removing instructions is often easy enough to not
14 // need this, updating stores should generally not be attemped outside this
15 // API.
16 //
17 // Basic API usage:
18 // Create the memory access you want for the instruction (this is mainly so
19 // we know where it is, without having to duplicate the entire set of create
20 // functions MemorySSA supports).
21 // Call insertDef or insertUse depending on whether it's a MemoryUse or a
22 // MemoryDef.
23 // That's it.
24 //
25 // For moving, first, move the instruction itself using the normal SSA
26 // instruction moving API, then just call moveBefore, moveAfter,or moveTo with
27 // the right arguments.
28 //
29 //===----------------------------------------------------------------------===//
30 
31 #ifndef LLVM_ANALYSIS_MEMORYSSAUPDATER_H
32 #define LLVM_ANALYSIS_MEMORYSSAUPDATER_H
33 
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/Analysis/LoopInfo.h"
40 #include "llvm/IR/BasicBlock.h"
41 #include "llvm/IR/CFGDiff.h"
42 #include "llvm/IR/Dominators.h"
43 #include "llvm/IR/Module.h"
44 #include "llvm/IR/OperandTraits.h"
45 #include "llvm/IR/Type.h"
46 #include "llvm/IR/Use.h"
47 #include "llvm/IR/User.h"
48 #include "llvm/IR/Value.h"
49 #include "llvm/IR/ValueHandle.h"
50 #include "llvm/IR/ValueMap.h"
51 #include "llvm/Pass.h"
52 #include "llvm/Support/Casting.h"
54 
55 namespace llvm {
56 
57 class Function;
58 class Instruction;
59 class MemoryAccess;
60 class LLVMContext;
61 class raw_ostream;
62 
66 using GraphDiffInvBBPair =
67  std::pair<const GraphDiff<BasicBlock *> *, Inverse<BasicBlock *>>;
68 
70 private:
71  MemorySSA *MSSA;
72 
73  /// We use WeakVH rather than a costly deletion to deal with dangling pointers.
74  /// MemoryPhis are created eagerly and sometimes get zapped shortly afterwards.
75  SmallVector<WeakVH, 16> InsertedPHIs;
76 
77  SmallPtrSet<BasicBlock *, 8> VisitedBlocks;
78  SmallSet<AssertingVH<MemoryPhi>, 8> NonOptPhis;
79 
80 public:
81  MemorySSAUpdater(MemorySSA *MSSA) : MSSA(MSSA) {}
82 
83  /// Insert a definition into the MemorySSA IR. RenameUses will rename any use
84  /// below the new def block (and any inserted phis). RenameUses should be set
85  /// to true if the definition may cause new aliases for loads below it. This
86  /// is not the case for hoisting or sinking or other forms of code *movement*.
87  /// It *is* the case for straight code insertion.
88  /// For example:
89  /// store a
90  /// if (foo) { }
91  /// load a
92  ///
93  /// Moving the store into the if block, and calling insertDef, does not
94  /// require RenameUses.
95  /// However, changing it to:
96  /// store a
97  /// if (foo) { store b }
98  /// load a
99  /// Where a mayalias b, *does* require RenameUses be set to true.
100  void insertDef(MemoryDef *Def, bool RenameUses = false);
101  void insertUse(MemoryUse *Use);
102  /// Update the MemoryPhi in `To` following an edge deletion between `From` and
103  /// `To`. If `To` becomes unreachable, a call to removeBlocks should be made.
104  void removeEdge(BasicBlock *From, BasicBlock *To);
105  /// Update the MemoryPhi in `To` to have a single incoming edge from `From`,
106  /// following a CFG change that replaced multiple edges (switch) with a direct
107  /// branch.
109  const BasicBlock *To);
110  /// Update MemorySSA when inserting a unique backedge block for a loop.
112  BasicBlock *LoopPreheader,
113  BasicBlock *BackedgeBlock);
114  /// Update MemorySSA after a loop was cloned, given the blocks in RPO order,
115  /// the exit blocks and a 1:1 mapping of all blocks and instructions
116  /// cloned. This involves duplicating all defs and uses in the cloned blocks
117  /// Updating phi nodes in exit block successors is done separately.
118  void updateForClonedLoop(const LoopBlocksRPO &LoopBlocks,
119  ArrayRef<BasicBlock *> ExitBlocks,
120  const ValueToValueMapTy &VM,
121  bool IgnoreIncomingWithNoClones = false);
122  // Block BB was fully or partially cloned into its predecessor P1. Map
123  // contains the 1:1 mapping of instructions cloned and VM[BB]=P1.
125  const ValueToValueMapTy &VM);
126  /// Update phi nodes in exit block successors following cloning. Exit blocks
127  /// that were not cloned don't have additional predecessors added.
129  const ValueToValueMapTy &VMap,
130  DominatorTree &DT);
132  ArrayRef<BasicBlock *> ExitBlocks,
133  ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps, DominatorTree &DT);
134 
135  /// Apply CFG updates, analogous with the DT edge updates.
137  /// Apply CFG insert updates, analogous with the DT edge updates.
139 
140  void moveBefore(MemoryUseOrDef *What, MemoryUseOrDef *Where);
141  void moveAfter(MemoryUseOrDef *What, MemoryUseOrDef *Where);
142  void moveToPlace(MemoryUseOrDef *What, BasicBlock *BB,
144  /// `From` block was spliced into `From` and `To`. There is a CFG edge from
145  /// `From` to `To`. Move all accesses from `From` to `To` starting at
146  /// instruction `Start`. `To` is newly created BB, so empty of
147  /// MemorySSA::MemoryAccesses. Edges are already updated, so successors of
148  /// `To` with MPhi nodes need to update incoming block.
149  /// |------| |------|
150  /// | From | | From |
151  /// | | |------|
152  /// | | ||
153  /// | | => \/
154  /// | | |------| <- Start
155  /// | | | To |
156  /// |------| |------|
158  Instruction *Start);
159  /// `From` block was merged into `To`. There is a CFG edge from `To` to
160  /// `From`.`To` still branches to `From`, but all instructions were moved and
161  /// `From` is now an empty block; `From` is about to be deleted. Move all
162  /// accesses from `From` to `To` starting at instruction `Start`. `To` may
163  /// have multiple successors, `From` has a single predecessor. `From` may have
164  /// successors with MPhi nodes, replace their incoming block with `To`.
165  /// |------| |------|
166  /// | To | | To |
167  /// |------| | |
168  /// || => | |
169  /// \/ | |
170  /// |------| | | <- Start
171  /// | From | | |
172  /// |------| |------|
174  Instruction *Start);
175  /// A new empty BasicBlock (New) now branches directly to Old. Some of
176  /// Old's predecessors (Preds) are now branching to New instead of Old.
177  /// If New is the only predecessor, move Old's Phi, if present, to New.
178  /// Otherwise, add a new Phi in New with appropriate incoming values, and
179  /// update the incoming values in Old's Phi node too, if present.
181  BasicBlock *Old, BasicBlock *New, ArrayRef<BasicBlock *> Preds,
182  bool IdenticalEdgesWereMerged = true);
183  // The below are utility functions. Other than creation of accesses to pass
184  // to insertDef, and removeAccess to remove accesses, you should generally
185  // not attempt to update memoryssa yourself. It is very non-trivial to get
186  // the edge cases right, and the above calls already operate in near-optimal
187  // time bounds.
188 
189  /// Create a MemoryAccess in MemorySSA at a specified point in a block,
190  /// with a specified clobbering definition.
191  ///
192  /// Returns the new MemoryAccess.
193  /// This should be called when a memory instruction is created that is being
194  /// used to replace an existing memory instruction. It will *not* create PHI
195  /// nodes, or verify the clobbering definition. The insertion place is used
196  /// solely to determine where in the memoryssa access lists the instruction
197  /// will be placed. The caller is expected to keep ordering the same as
198  /// instructions.
199  /// It will return the new MemoryAccess.
200  /// Note: If a MemoryAccess already exists for I, this function will make it
201  /// inaccessible and it *must* have removeMemoryAccess called on it.
203  const BasicBlock *BB,
205 
206  /// Create a MemoryAccess in MemorySSA before or after an existing
207  /// MemoryAccess.
208  ///
209  /// Returns the new MemoryAccess.
210  /// This should be called when a memory instruction is created that is being
211  /// used to replace an existing memory instruction. It will *not* create PHI
212  /// nodes, or verify the clobbering definition.
213  ///
214  /// Note: If a MemoryAccess already exists for I, this function will make it
215  /// inaccessible and it *must* have removeMemoryAccess called on it.
217  MemoryAccess *Definition,
218  MemoryUseOrDef *InsertPt);
220  MemoryAccess *Definition,
221  MemoryAccess *InsertPt);
222 
223  /// Remove a MemoryAccess from MemorySSA, including updating all
224  /// definitions and uses.
225  /// This should be called when a memory instruction that has a MemoryAccess
226  /// associated with it is erased from the program. For example, if a store or
227  /// load is simply erased (not replaced), removeMemoryAccess should be called
228  /// on the MemoryAccess for that store/load.
229  void removeMemoryAccess(MemoryAccess *, bool OptimizePhis = false);
230 
231  /// Remove MemoryAccess for a given instruction, if a MemoryAccess exists.
232  /// This should be called when an instruction (load/store) is deleted from
233  /// the program.
234  void removeMemoryAccess(const Instruction *I, bool OptimizePhis = false) {
235  if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
236  removeMemoryAccess(MA, OptimizePhis);
237  }
238 
239  /// Remove all MemoryAcceses in a set of BasicBlocks about to be deleted.
240  /// Assumption we make here: all uses of deleted defs and phi must either
241  /// occur in blocks about to be deleted (thus will be deleted as well), or
242  /// they occur in phis that will simply lose an incoming value.
243  /// Deleted blocks still have successor info, but their predecessor edges and
244  /// Phi nodes may already be updated. Instructions in DeadBlocks should be
245  /// deleted after this call.
246  void removeBlocks(const SmallPtrSetImpl<BasicBlock *> &DeadBlocks);
247 
248  /// Instruction I will be changed to an unreachable. Remove all accesses in
249  /// I's block that follow I (inclusive), and update the Phis in the blocks'
250  /// successors.
251  void changeToUnreachable(const Instruction *I);
252 
253  /// Conditional branch BI is changed or replaced with an unconditional branch
254  /// to `To`. Update Phis in BI's successors to remove BI's BB.
256  const BasicBlock *To);
257 
258  /// Get handle on MemorySSA.
259  MemorySSA* getMemorySSA() const { return MSSA; }
260 
261 private:
262  // Move What before Where in the MemorySSA IR.
263  template <class WhereType>
264  void moveTo(MemoryUseOrDef *What, BasicBlock *BB, WhereType Where);
265  // Move all memory accesses from `From` to `To` starting at `Start`.
266  // Restrictions apply, see public wrappers of this method.
267  void moveAllAccesses(BasicBlock *From, BasicBlock *To, Instruction *Start);
268  MemoryAccess *getPreviousDef(MemoryAccess *);
269  MemoryAccess *getPreviousDefInBlock(MemoryAccess *);
270  MemoryAccess *
271  getPreviousDefFromEnd(BasicBlock *,
273  MemoryAccess *
274  getPreviousDefRecursive(BasicBlock *,
276  MemoryAccess *recursePhi(MemoryAccess *Phi);
277  template <class RangeType>
278  MemoryAccess *tryRemoveTrivialPhi(MemoryPhi *Phi, RangeType &Operands);
279  void tryRemoveTrivialPhis(ArrayRef<WeakVH> UpdatedPHIs);
280  void fixupDefs(const SmallVectorImpl<WeakVH> &);
281  // Clone all uses and defs from BB to NewBB given a 1:1 map of all
282  // instructions and blocks cloned, and a map of MemoryPhi : Definition
283  // (MemoryAccess Phi or Def). VMap maps old instructions to cloned
284  // instructions and old blocks to cloned blocks. MPhiMap, is created in the
285  // caller of this private method, and maps existing MemoryPhis to new
286  // definitions that new MemoryAccesses must point to. These definitions may
287  // not necessarily be MemoryPhis themselves, they may be MemoryDefs. As such,
288  // the map is between MemoryPhis and MemoryAccesses, where the MemoryAccesses
289  // may be MemoryPhis or MemoryDefs and not MemoryUses.
290  // If CloneWasSimplified = true, the clone was exact. Otherwise, assume that
291  // the clone involved simplifications that may have: (1) turned a MemoryUse
292  // into an instruction that MemorySSA has no representation for, or (2) turned
293  // a MemoryDef into a MemoryUse or an instruction that MemorySSA has no
294  // representation for. No other cases are supported.
295  void cloneUsesAndDefs(BasicBlock *BB, BasicBlock *NewBB,
296  const ValueToValueMapTy &VMap, PhiToDefMap &MPhiMap,
297  bool CloneWasSimplified = false);
298  template <typename Iter>
299  void privateUpdateExitBlocksForClonedLoop(ArrayRef<BasicBlock *> ExitBlocks,
300  Iter ValuesBegin, Iter ValuesEnd,
301  DominatorTree &DT);
303  const GraphDiff<BasicBlock *> *GD);
304 };
305 } // end namespace llvm
306 
307 #endif // LLVM_ANALYSIS_MEMORYSSAUPDATER_H
This class represents lattice values for constants.
Definition: AllocatorList.h:23
void updateExitBlocksForClonedLoop(ArrayRef< BasicBlock *> ExitBlocks, const ValueToValueMapTy &VMap, DominatorTree &DT)
Update phi nodes in exit block successors following cloning.
void applyInsertUpdates(ArrayRef< CFGUpdate > Updates, DominatorTree &DT)
Apply CFG insert updates, analogous with the DT edge updates.
void changeToUnreachable(const Instruction *I)
Instruction I will be changed to an unreachable.
void removeBlocks(const SmallPtrSetImpl< BasicBlock *> &DeadBlocks)
Remove all MemoryAcceses in a set of BasicBlocks about to be deleted.
void moveAfter(MemoryUseOrDef *What, MemoryUseOrDef *Where)
Represents a read-write access to memory, whether it is a must-alias, or a may-alias.
Definition: MemorySSA.h:375
void insertUse(MemoryUse *Use)
std::pair< const GraphDiff< BasicBlock * > *, Inverse< BasicBlock * > > GraphDiffInvBBPair
This defines the Use class.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:343
Represents read-only accesses to memory.
Definition: MemorySSA.h:319
void removeEdge(BasicBlock *From, BasicBlock *To)
Update the MemoryPhi in To following an edge deletion between From and To.
MemorySSA * getMemorySSA() const
Get handle on MemorySSA.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:55
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:41
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition: MemorySSA.h:703
void applyUpdates(ArrayRef< CFGUpdate > Updates, DominatorTree &DT)
Apply CFG updates, analogous with the DT edge updates.
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref&#39;ing instruction, get the MemorySSA access associated with it.
Definition: MemorySSA.h:720
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
MemoryUseOrDef * createMemoryAccessBefore(Instruction *I, MemoryAccess *Definition, MemoryUseOrDef *InsertPt)
Create a MemoryAccess in MemorySSA before or after an existing MemoryAccess.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:144
void updatePhisWhenInsertingUniqueBackedgeBlock(BasicBlock *LoopHeader, BasicBlock *LoopPreheader, BasicBlock *BackedgeBlock)
Update MemorySSA when inserting a unique backedge block for a loop.
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
Conditional or Unconditional Branch instruction.
Value handle that tracks a Value across RAUW.
Definition: ValueHandle.h:327
void removeDuplicatePhiEdgesBetween(const BasicBlock *From, const BasicBlock *To)
Update the MemoryPhi in To to have a single incoming edge from From, following a CFG change that repl...
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:134
InsertionPlace
Used in various insertion functions to specify whether we are talking about the beginning or end of a...
Definition: MemorySSA.h:788
void moveAllAfterSpliceBlocks(BasicBlock *From, BasicBlock *To, Instruction *Start)
From block was spliced into From and To.
void removeMemoryAccess(const Instruction *I, bool OptimizePhis=false)
Remove MemoryAccess for a given instruction, if a MemoryAccess exists.
void updateForClonedLoop(const LoopBlocksRPO &LoopBlocks, ArrayRef< BasicBlock *> ExitBlocks, const ValueToValueMapTy &VM, bool IgnoreIncomingWithNoClones=false)
Update MemorySSA after a loop was cloned, given the blocks in RPO order, the exit blocks and a 1:1 ma...
MemoryAccess * createMemoryAccessInBB(Instruction *I, MemoryAccess *Definition, const BasicBlock *BB, MemorySSA::InsertionPlace Point)
Create a MemoryAccess in MemorySSA at a specified point in a block, with a specified clobbering defin...
void moveToPlace(MemoryUseOrDef *What, BasicBlock *BB, MemorySSA::InsertionPlace Where)
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:417
BlockVerifier::State From
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
Module.h This file contains the declarations for the Module class.
void wireOldPredecessorsToNewImmediatePredecessor(BasicBlock *Old, BasicBlock *New, ArrayRef< BasicBlock *> Preds, bool IdenticalEdgesWereMerged=true)
A new empty BasicBlock (New) now branches directly to Old.
Class that has the common methods + fields of memory uses/defs.
Definition: MemorySSA.h:247
#define I(x, y, z)
Definition: MD5.cpp:58
MemoryUseOrDef * createMemoryAccessAfter(Instruction *I, MemoryAccess *Definition, MemoryAccess *InsertPt)
void moveAllAfterMergeBlocks(BasicBlock *From, BasicBlock *To, Instruction *Start)
From block was merged into To.
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
Definition: LoopIterator.h:172
void removeMemoryAccess(MemoryAccess *, bool OptimizePhis=false)
Remove a MemoryAccess from MemorySSA, including updating all definitions and uses.
void insertDef(MemoryDef *Def, bool RenameUses=false)
Insert a definition into the MemorySSA IR.
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
MemorySSAUpdater(MemorySSA *MSSA)
Represents phi nodes for memory accesses.
Definition: MemorySSA.h:481
void moveBefore(MemoryUseOrDef *What, MemoryUseOrDef *Where)
void updateForClonedBlockIntoPred(BasicBlock *BB, BasicBlock *P1, const ValueToValueMapTy &VM)
void changeCondBranchToUnconditionalTo(const BranchInst *BI, const BasicBlock *To)
Conditional branch BI is changed or replaced with an unconditional branch to To.