blob: a9553e008d077e18c095bcc20b09f5eeb1e49d36 [file] [log] [blame]
Daniel Berlinae6b8b62017-01-28 01:35:02 +00001//===-- MemorySSAUpdater.cpp - Memory SSA Updater--------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Daniel Berlinae6b8b62017-01-28 01:35:02 +00006//
7//===----------------------------------------------------------------===//
8//
9// This file implements the MemorySSAUpdater class.
10//
11//===----------------------------------------------------------------===//
Daniel Berlin554dcd82017-04-11 20:06:36 +000012#include "llvm/Analysis/MemorySSAUpdater.h"
Daniel Berlinae6b8b62017-01-28 01:35:02 +000013#include "llvm/ADT/STLExtras.h"
Alina Sbirlea79800992018-09-10 20:13:01 +000014#include "llvm/ADT/SetVector.h"
Daniel Berlinae6b8b62017-01-28 01:35:02 +000015#include "llvm/ADT/SmallPtrSet.h"
Alina Sbirlea79800992018-09-10 20:13:01 +000016#include "llvm/Analysis/IteratedDominanceFrontier.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000017#include "llvm/Analysis/MemorySSA.h"
Daniel Berlinae6b8b62017-01-28 01:35:02 +000018#include "llvm/IR/DataLayout.h"
19#include "llvm/IR/Dominators.h"
20#include "llvm/IR/GlobalVariable.h"
21#include "llvm/IR/IRBuilder.h"
Daniel Berlinae6b8b62017-01-28 01:35:02 +000022#include "llvm/IR/LLVMContext.h"
23#include "llvm/IR/Metadata.h"
24#include "llvm/IR/Module.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/FormattedStream.h"
Daniel Berlinae6b8b62017-01-28 01:35:02 +000027#include <algorithm>
28
29#define DEBUG_TYPE "memoryssa"
30using namespace llvm;
George Burgess IV56169ed2017-04-21 04:54:52 +000031
Daniel Berlinae6b8b62017-01-28 01:35:02 +000032// This is the marker algorithm from "Simple and Efficient Construction of
33// Static Single Assignment Form"
34// The simple, non-marker algorithm places phi nodes at any join
35// Here, we place markers, and only place phi nodes if they end up necessary.
36// They are only necessary if they break a cycle (IE we recursively visit
37// ourselves again), or we discover, while getting the value of the operands,
38// that there are two or more definitions needing to be merged.
39// This still will leave non-minimal form in the case of irreducible control
40// flow, where phi nodes may be in cycles with themselves, but unnecessary.
Eli Friedman88e2bac2018-03-26 19:52:54 +000041MemoryAccess *MemorySSAUpdater::getPreviousDefRecursive(
42 BasicBlock *BB,
43 DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> &CachedPreviousDef) {
44 // First, do a cache lookup. Without this cache, certain CFG structures
45 // (like a series of if statements) take exponential time to visit.
46 auto Cached = CachedPreviousDef.find(BB);
47 if (Cached != CachedPreviousDef.end()) {
48 return Cached->second;
George Burgess IV45f263d2018-05-26 02:28:55 +000049 }
50
51 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
Eli Friedman88e2bac2018-03-26 19:52:54 +000052 // Single predecessor case, just recurse, we can only have one definition.
53 MemoryAccess *Result = getPreviousDefFromEnd(Pred, CachedPreviousDef);
54 CachedPreviousDef.insert({BB, Result});
55 return Result;
George Burgess IV45f263d2018-05-26 02:28:55 +000056 }
57
58 if (VisitedBlocks.count(BB)) {
Daniel Berlinae6b8b62017-01-28 01:35:02 +000059 // We hit our node again, meaning we had a cycle, we must insert a phi
60 // node to break it so we have an operand. The only case this will
61 // insert useless phis is if we have irreducible control flow.
Eli Friedman88e2bac2018-03-26 19:52:54 +000062 MemoryAccess *Result = MSSA->createMemoryPhi(BB);
63 CachedPreviousDef.insert({BB, Result});
64 return Result;
George Burgess IV45f263d2018-05-26 02:28:55 +000065 }
66
67 if (VisitedBlocks.insert(BB).second) {
Daniel Berlinae6b8b62017-01-28 01:35:02 +000068 // Mark us visited so we can detect a cycle
Alexandros Lamprineasbf6009c2018-07-23 10:56:30 +000069 SmallVector<TrackingVH<MemoryAccess>, 8> PhiOps;
Daniel Berlinae6b8b62017-01-28 01:35:02 +000070
71 // Recurse to get the values in our predecessors for placement of a
72 // potential phi node. This will insert phi nodes if we cycle in order to
73 // break the cycle and have an operand.
74 for (auto *Pred : predecessors(BB))
Alina Sbirlea0363c3b2019-05-02 23:41:58 +000075 if (MSSA->DT->isReachableFromEntry(Pred))
76 PhiOps.push_back(getPreviousDefFromEnd(Pred, CachedPreviousDef));
77 else
78 PhiOps.push_back(MSSA->getLiveOnEntryDef());
Daniel Berlinae6b8b62017-01-28 01:35:02 +000079
80 // Now try to simplify the ops to avoid placing a phi.
81 // This may return null if we never created a phi yet, that's okay
82 MemoryPhi *Phi = dyn_cast_or_null<MemoryPhi>(MSSA->getMemoryAccess(BB));
Daniel Berlinae6b8b62017-01-28 01:35:02 +000083
84 // See if we can avoid the phi by simplifying it.
85 auto *Result = tryRemoveTrivialPhi(Phi, PhiOps);
86 // If we couldn't simplify, we may have to create a phi
87 if (Result == Phi) {
88 if (!Phi)
89 Phi = MSSA->createMemoryPhi(BB);
90
Alexandros Lamprineasbf6009c2018-07-23 10:56:30 +000091 // See if the existing phi operands match what we need.
92 // Unlike normal SSA, we only allow one phi node per block, so we can't just
93 // create a new one.
94 if (Phi->getNumOperands() != 0) {
95 // FIXME: Figure out whether this is dead code and if so remove it.
96 if (!std::equal(Phi->op_begin(), Phi->op_end(), PhiOps.begin())) {
97 // These will have been filled in by the recursive read we did above.
Fangrui Song75709322018-11-17 01:44:25 +000098 llvm::copy(PhiOps, Phi->op_begin());
Alexandros Lamprineasbf6009c2018-07-23 10:56:30 +000099 std::copy(pred_begin(BB), pred_end(BB), Phi->block_begin());
100 }
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000101 } else {
102 unsigned i = 0;
103 for (auto *Pred : predecessors(BB))
Alexandros Lamprineasbf6009c2018-07-23 10:56:30 +0000104 Phi->addIncoming(&*PhiOps[i++], Pred);
Daniel Berlin97f34e82017-09-27 05:35:19 +0000105 InsertedPHIs.push_back(Phi);
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000106 }
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000107 Result = Phi;
108 }
Daniel Berlin97f34e82017-09-27 05:35:19 +0000109
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000110 // Set ourselves up for the next variable by resetting visited state.
111 VisitedBlocks.erase(BB);
Eli Friedman88e2bac2018-03-26 19:52:54 +0000112 CachedPreviousDef.insert({BB, Result});
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000113 return Result;
114 }
115 llvm_unreachable("Should have hit one of the three cases above");
116}
117
118// This starts at the memory access, and goes backwards in the block to find the
119// previous definition. If a definition is not found the block of the access,
120// it continues globally, creating phi nodes to ensure we have a single
121// definition.
122MemoryAccess *MemorySSAUpdater::getPreviousDef(MemoryAccess *MA) {
Eli Friedman88e2bac2018-03-26 19:52:54 +0000123 if (auto *LocalResult = getPreviousDefInBlock(MA))
124 return LocalResult;
125 DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> CachedPreviousDef;
126 return getPreviousDefRecursive(MA->getBlock(), CachedPreviousDef);
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000127}
128
129// This starts at the memory access, and goes backwards in the block to the find
130// the previous definition. If the definition is not found in the block of the
131// access, it returns nullptr.
132MemoryAccess *MemorySSAUpdater::getPreviousDefInBlock(MemoryAccess *MA) {
133 auto *Defs = MSSA->getWritableBlockDefs(MA->getBlock());
134
135 // It's possible there are no defs, or we got handed the first def to start.
136 if (Defs) {
137 // If this is a def, we can just use the def iterators.
138 if (!isa<MemoryUse>(MA)) {
139 auto Iter = MA->getReverseDefsIterator();
140 ++Iter;
141 if (Iter != Defs->rend())
142 return &*Iter;
143 } else {
144 // Otherwise, have to walk the all access iterator.
Alina Sbirlea33e58722017-06-07 16:46:53 +0000145 auto End = MSSA->getWritableBlockAccesses(MA->getBlock())->rend();
146 for (auto &U : make_range(++MA->getReverseIterator(), End))
147 if (!isa<MemoryUse>(U))
148 return cast<MemoryAccess>(&U);
149 // Note that if MA comes before Defs->begin(), we won't hit a def.
150 return nullptr;
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000151 }
152 }
153 return nullptr;
154}
155
156// This starts at the end of block
Eli Friedman88e2bac2018-03-26 19:52:54 +0000157MemoryAccess *MemorySSAUpdater::getPreviousDefFromEnd(
158 BasicBlock *BB,
159 DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> &CachedPreviousDef) {
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000160 auto *Defs = MSSA->getWritableBlockDefs(BB);
161
Alina Sbirleaf9f073a2019-04-12 21:58:52 +0000162 if (Defs) {
163 CachedPreviousDef.insert({BB, &*Defs->rbegin()});
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000164 return &*Defs->rbegin();
Alina Sbirleaf9f073a2019-04-12 21:58:52 +0000165 }
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000166
Eli Friedman88e2bac2018-03-26 19:52:54 +0000167 return getPreviousDefRecursive(BB, CachedPreviousDef);
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000168}
169// Recurse over a set of phi uses to eliminate the trivial ones
170MemoryAccess *MemorySSAUpdater::recursePhi(MemoryAccess *Phi) {
171 if (!Phi)
172 return nullptr;
173 TrackingVH<MemoryAccess> Res(Phi);
174 SmallVector<TrackingVH<Value>, 8> Uses;
175 std::copy(Phi->user_begin(), Phi->user_end(), std::back_inserter(Uses));
176 for (auto &U : Uses) {
177 if (MemoryPhi *UsePhi = dyn_cast<MemoryPhi>(&*U)) {
178 auto OperRange = UsePhi->operands();
179 tryRemoveTrivialPhi(UsePhi, OperRange);
180 }
181 }
182 return Res;
183}
184
185// Eliminate trivial phis
186// Phis are trivial if they are defined either by themselves, or all the same
187// argument.
188// IE phi(a, a) or b = phi(a, b) or c = phi(a, a, c)
189// We recursively try to remove them.
190template <class RangeType>
191MemoryAccess *MemorySSAUpdater::tryRemoveTrivialPhi(MemoryPhi *Phi,
192 RangeType &Operands) {
Zhaoshi Zheng43af17b2018-04-09 20:55:37 +0000193 // Bail out on non-opt Phis.
194 if (NonOptPhis.count(Phi))
195 return Phi;
196
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000197 // Detect equal or self arguments
198 MemoryAccess *Same = nullptr;
199 for (auto &Op : Operands) {
200 // If the same or self, good so far
201 if (Op == Phi || Op == Same)
202 continue;
203 // not the same, return the phi since it's not eliminatable by us
204 if (Same)
205 return Phi;
Alexandros Lamprineasbf6009c2018-07-23 10:56:30 +0000206 Same = cast<MemoryAccess>(&*Op);
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000207 }
208 // Never found a non-self reference, the phi is undef
209 if (Same == nullptr)
210 return MSSA->getLiveOnEntryDef();
211 if (Phi) {
212 Phi->replaceAllUsesWith(Same);
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000213 removeMemoryAccess(Phi);
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000214 }
215
216 // We should only end up recursing in case we replaced something, in which
217 // case, we may have made other Phis trivial.
218 return recursePhi(Same);
219}
220
221void MemorySSAUpdater::insertUse(MemoryUse *MU) {
222 InsertedPHIs.clear();
223 MU->setDefiningAccess(getPreviousDef(MU));
224 // Unlike for defs, there is no extra work to do. Because uses do not create
225 // new may-defs, there are only two cases:
226 //
227 // 1. There was a def already below us, and therefore, we should not have
228 // created a phi node because it was already needed for the def.
229 //
230 // 2. There is no def below us, and therefore, there is no extra renaming work
231 // to do.
232}
233
Daniel Berlin9d8a3352017-01-30 11:35:39 +0000234// Set every incoming edge {BB, MP->getBlock()} of MemoryPhi MP to NewDef.
George Burgess IV56169ed2017-04-21 04:54:52 +0000235static void setMemoryPhiValueForBlock(MemoryPhi *MP, const BasicBlock *BB,
236 MemoryAccess *NewDef) {
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000237 // Replace any operand with us an incoming block with the new defining
238 // access.
239 int i = MP->getBasicBlockIndex(BB);
240 assert(i != -1 && "Should have found the basic block in the phi");
Daniel Berlin9d8a3352017-01-30 11:35:39 +0000241 // We can't just compare i against getNumOperands since one is signed and the
242 // other not. So use it to index into the block iterator.
243 for (auto BBIter = MP->block_begin() + i; BBIter != MP->block_end();
244 ++BBIter) {
245 if (*BBIter != BB)
246 break;
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000247 MP->setIncomingValue(i, NewDef);
248 ++i;
249 }
250}
251
252// A brief description of the algorithm:
253// First, we compute what should define the new def, using the SSA
254// construction algorithm.
255// Then, we update the defs below us (and any new phi nodes) in the graph to
256// point to the correct new defs, to ensure we only have one variable, and no
257// disconnected stores.
Daniel Berlin78cbd282017-02-20 22:26:03 +0000258void MemorySSAUpdater::insertDef(MemoryDef *MD, bool RenameUses) {
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000259 InsertedPHIs.clear();
260
261 // See if we had a local def, and if not, go hunting.
Eli Friedman88e2bac2018-03-26 19:52:54 +0000262 MemoryAccess *DefBefore = getPreviousDef(MD);
263 bool DefBeforeSameBlock = DefBefore->getBlock() == MD->getBlock();
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000264
265 // There is a def before us, which means we can replace any store/phi uses
266 // of that thing with us, since we are in the way of whatever was there
267 // before.
268 // We now define that def's memorydefs and memoryphis
Daniel Berlin9d8a3352017-01-30 11:35:39 +0000269 if (DefBeforeSameBlock) {
270 for (auto UI = DefBefore->use_begin(), UE = DefBefore->use_end();
271 UI != UE;) {
272 Use &U = *UI++;
Alexandros Lamprineas96762b32018-09-11 14:29:59 +0000273 // Leave the MemoryUses alone.
274 // Also make sure we skip ourselves to avoid self references.
275 if (isa<MemoryUse>(U.getUser()) || U.getUser() == MD)
Daniel Berlin9d8a3352017-01-30 11:35:39 +0000276 continue;
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000277 // Defs are automatically unoptimized when the user is set to MD below,
278 // because the isOptimized() call will fail to find the same ID.
Daniel Berlin9d8a3352017-01-30 11:35:39 +0000279 U.set(MD);
280 }
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000281 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +0000282
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000283 // and that def is now our defining access.
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000284 MD->setDefiningAccess(DefBefore);
285
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000286 // Remember the index where we may insert new phis below.
287 unsigned NewPhiIndex = InsertedPHIs.size();
288
Alexandros Lamprineasf854ce82018-07-16 07:51:27 +0000289 SmallVector<WeakVH, 8> FixupList(InsertedPHIs.begin(), InsertedPHIs.end());
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000290 if (!DefBeforeSameBlock) {
291 // If there was a local def before us, we must have the same effect it
292 // did. Because every may-def is the same, any phis/etc we would create, it
293 // would also have created. If there was no local def before us, we
294 // performed a global update, and have to search all successors and make
295 // sure we update the first def in each of them (following all paths until
296 // we hit the first def along each path). This may also insert phi nodes.
297 // TODO: There are other cases we can skip this work, such as when we have a
298 // single successor, and only used a straight line of single pred blocks
299 // backwards to find the def. To make that work, we'd have to track whether
300 // getDefRecursive only ever used the single predecessor case. These types
301 // of paths also only exist in between CFG simplifications.
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000302
303 // If this is the first def in the block and this insert is in an arbitrary
304 // place, compute IDF and place phis.
305 auto Iter = MD->getDefsIterator();
306 ++Iter;
307 auto IterEnd = MSSA->getBlockDefs(MD->getBlock())->end();
308 if (Iter == IterEnd) {
309 ForwardIDFCalculator IDFs(*MSSA->DT);
310 SmallVector<BasicBlock *, 32> IDFBlocks;
311 SmallPtrSet<BasicBlock *, 2> DefiningBlocks;
312 DefiningBlocks.insert(MD->getBlock());
313 IDFs.setDefiningBlocks(DefiningBlocks);
314 IDFs.calculate(IDFBlocks);
315 SmallVector<AssertingVH<MemoryPhi>, 4> NewInsertedPHIs;
316 for (auto *BBIDF : IDFBlocks)
Alina Sbirleae5890672019-03-29 21:16:31 +0000317 if (!MSSA->getMemoryAccess(BBIDF)) {
318 auto *MPhi = MSSA->createMemoryPhi(BBIDF);
319 NewInsertedPHIs.push_back(MPhi);
320 // Add the phis created into the IDF blocks to NonOptPhis, so they are
321 // not optimized out as trivial by the call to getPreviousDefFromEnd
322 // below. Once they are complete, all these Phis are added to the
323 // FixupList, and removed from NonOptPhis inside fixupDefs().
324 NonOptPhis.insert(MPhi);
325 }
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000326
327 for (auto &MPhi : NewInsertedPHIs) {
328 auto *BBIDF = MPhi->getBlock();
329 for (auto *Pred : predecessors(BBIDF)) {
330 DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> CachedPreviousDef;
331 MPhi->addIncoming(getPreviousDefFromEnd(Pred, CachedPreviousDef),
332 Pred);
333 }
334 }
335
336 // Re-take the index where we're adding the new phis, because the above
337 // call to getPreviousDefFromEnd, may have inserted into InsertedPHIs.
338 NewPhiIndex = InsertedPHIs.size();
339 for (auto &MPhi : NewInsertedPHIs) {
340 InsertedPHIs.push_back(&*MPhi);
341 FixupList.push_back(&*MPhi);
342 }
343 }
344
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000345 FixupList.push_back(MD);
346 }
347
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000348 // Remember the index where we stopped inserting new phis above, since the
349 // fixupDefs call in the loop below may insert more, that are already minimal.
350 unsigned NewPhiIndexEnd = InsertedPHIs.size();
351
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000352 while (!FixupList.empty()) {
353 unsigned StartingPHISize = InsertedPHIs.size();
354 fixupDefs(FixupList);
355 FixupList.clear();
356 // Put any new phis on the fixup list, and process them
Alexandros Lamprineasf854ce82018-07-16 07:51:27 +0000357 FixupList.append(InsertedPHIs.begin() + StartingPHISize, InsertedPHIs.end());
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000358 }
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000359
360 // Optimize potentially non-minimal phis added in this method.
Alina Sbirlea151ab482019-05-02 23:12:49 +0000361 unsigned NewPhiSize = NewPhiIndexEnd - NewPhiIndex;
362 if (NewPhiSize)
363 tryRemoveTrivialPhis(ArrayRef<WeakVH>(&InsertedPHIs[NewPhiIndex], NewPhiSize));
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000364
Daniel Berlin78cbd282017-02-20 22:26:03 +0000365 // Now that all fixups are done, rename all uses if we are asked.
366 if (RenameUses) {
367 SmallPtrSet<BasicBlock *, 16> Visited;
368 BasicBlock *StartBlock = MD->getBlock();
369 // We are guaranteed there is a def in the block, because we just got it
370 // handed to us in this function.
371 MemoryAccess *FirstDef = &*MSSA->getWritableBlockDefs(StartBlock)->begin();
372 // Convert to incoming value if it's a memorydef. A phi *is* already an
373 // incoming value.
374 if (auto *MD = dyn_cast<MemoryDef>(FirstDef))
375 FirstDef = MD->getDefiningAccess();
376
377 MSSA->renamePass(MD->getBlock(), FirstDef, Visited);
378 // We just inserted a phi into this block, so the incoming value will become
379 // the phi anyway, so it does not matter what we pass.
Alexandros Lamprineasf854ce82018-07-16 07:51:27 +0000380 for (auto &MP : InsertedPHIs) {
381 MemoryPhi *Phi = dyn_cast_or_null<MemoryPhi>(MP);
382 if (Phi)
383 MSSA->renamePass(Phi->getBlock(), nullptr, Visited);
384 }
Daniel Berlin78cbd282017-02-20 22:26:03 +0000385 }
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000386}
387
Alexandros Lamprineasf854ce82018-07-16 07:51:27 +0000388void MemorySSAUpdater::fixupDefs(const SmallVectorImpl<WeakVH> &Vars) {
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000389 SmallPtrSet<const BasicBlock *, 8> Seen;
390 SmallVector<const BasicBlock *, 16> Worklist;
Alexandros Lamprineasf854ce82018-07-16 07:51:27 +0000391 for (auto &Var : Vars) {
392 MemoryAccess *NewDef = dyn_cast_or_null<MemoryAccess>(Var);
393 if (!NewDef)
394 continue;
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000395 // First, see if there is a local def after the operand.
396 auto *Defs = MSSA->getWritableBlockDefs(NewDef->getBlock());
397 auto DefIter = NewDef->getDefsIterator();
398
Zhaoshi Zheng43af17b2018-04-09 20:55:37 +0000399 // The temporary Phi is being fixed, unmark it for not to optimize.
George Burgess IVe7cdb7e2018-07-12 21:56:31 +0000400 if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(NewDef))
Zhaoshi Zheng43af17b2018-04-09 20:55:37 +0000401 NonOptPhis.erase(Phi);
402
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000403 // If there is a local def after us, we only have to rename that.
404 if (++DefIter != Defs->end()) {
405 cast<MemoryDef>(DefIter)->setDefiningAccess(NewDef);
406 continue;
407 }
408
409 // Otherwise, we need to search down through the CFG.
410 // For each of our successors, handle it directly if their is a phi, or
411 // place on the fixup worklist.
412 for (const auto *S : successors(NewDef->getBlock())) {
413 if (auto *MP = MSSA->getMemoryAccess(S))
414 setMemoryPhiValueForBlock(MP, NewDef->getBlock(), NewDef);
415 else
416 Worklist.push_back(S);
417 }
418
419 while (!Worklist.empty()) {
420 const BasicBlock *FixupBlock = Worklist.back();
421 Worklist.pop_back();
422
423 // Get the first def in the block that isn't a phi node.
424 if (auto *Defs = MSSA->getWritableBlockDefs(FixupBlock)) {
425 auto *FirstDef = &*Defs->begin();
426 // The loop above and below should have taken care of phi nodes
427 assert(!isa<MemoryPhi>(FirstDef) &&
428 "Should have already handled phi nodes!");
429 // We are now this def's defining access, make sure we actually dominate
430 // it
431 assert(MSSA->dominates(NewDef, FirstDef) &&
432 "Should have dominated the new access");
433
434 // This may insert new phi nodes, because we are not guaranteed the
435 // block we are processing has a single pred, and depending where the
436 // store was inserted, it may require phi nodes below it.
437 cast<MemoryDef>(FirstDef)->setDefiningAccess(getPreviousDef(FirstDef));
438 return;
439 }
440 // We didn't find a def, so we must continue.
441 for (const auto *S : successors(FixupBlock)) {
442 // If there is a phi node, handle it.
443 // Otherwise, put the block on the worklist
444 if (auto *MP = MSSA->getMemoryAccess(S))
445 setMemoryPhiValueForBlock(MP, FixupBlock, NewDef);
446 else {
447 // If we cycle, we should have ended up at a phi node that we already
448 // processed. FIXME: Double check this
449 if (!Seen.insert(S).second)
450 continue;
451 Worklist.push_back(S);
452 }
453 }
454 }
455 }
456}
457
Alina Sbirlea79800992018-09-10 20:13:01 +0000458void MemorySSAUpdater::removeEdge(BasicBlock *From, BasicBlock *To) {
459 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(To)) {
460 MPhi->unorderedDeleteIncomingBlock(From);
461 if (MPhi->getNumIncomingValues() == 1)
462 removeMemoryAccess(MPhi);
463 }
464}
465
Alina Sbirleaf31eba62019-05-08 17:05:36 +0000466void MemorySSAUpdater::removeDuplicatePhiEdgesBetween(const BasicBlock *From,
467 const BasicBlock *To) {
Alina Sbirlea79800992018-09-10 20:13:01 +0000468 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(To)) {
469 bool Found = false;
470 MPhi->unorderedDeleteIncomingIf([&](const MemoryAccess *, BasicBlock *B) {
471 if (From != B)
472 return false;
473 if (Found)
474 return true;
475 Found = true;
476 return false;
477 });
478 if (MPhi->getNumIncomingValues() == 1)
479 removeMemoryAccess(MPhi);
480 }
481}
482
483void MemorySSAUpdater::cloneUsesAndDefs(BasicBlock *BB, BasicBlock *NewBB,
484 const ValueToValueMapTy &VMap,
485 PhiToDefMap &MPhiMap) {
486 auto GetNewDefiningAccess = [&](MemoryAccess *MA) -> MemoryAccess * {
487 MemoryAccess *InsnDefining = MA;
488 if (MemoryUseOrDef *DefMUD = dyn_cast<MemoryUseOrDef>(InsnDefining)) {
489 if (!MSSA->isLiveOnEntryDef(DefMUD)) {
490 Instruction *DefMUDI = DefMUD->getMemoryInst();
491 assert(DefMUDI && "Found MemoryUseOrDef with no Instruction.");
492 if (Instruction *NewDefMUDI =
493 cast_or_null<Instruction>(VMap.lookup(DefMUDI)))
494 InsnDefining = MSSA->getMemoryAccess(NewDefMUDI);
495 }
496 } else {
497 MemoryPhi *DefPhi = cast<MemoryPhi>(InsnDefining);
498 if (MemoryAccess *NewDefPhi = MPhiMap.lookup(DefPhi))
499 InsnDefining = NewDefPhi;
500 }
501 assert(InsnDefining && "Defining instruction cannot be nullptr.");
502 return InsnDefining;
503 };
504
505 const MemorySSA::AccessList *Acc = MSSA->getBlockAccesses(BB);
506 if (!Acc)
507 return;
508 for (const MemoryAccess &MA : *Acc) {
509 if (const MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&MA)) {
510 Instruction *Insn = MUD->getMemoryInst();
511 // Entry does not exist if the clone of the block did not clone all
512 // instructions. This occurs in LoopRotate when cloning instructions
513 // from the old header to the old preheader. The cloned instruction may
514 // also be a simplified Value, not an Instruction (see LoopRotate).
515 if (Instruction *NewInsn =
516 dyn_cast_or_null<Instruction>(VMap.lookup(Insn))) {
517 MemoryAccess *NewUseOrDef = MSSA->createDefinedAccess(
518 NewInsn, GetNewDefiningAccess(MUD->getDefiningAccess()), MUD);
519 MSSA->insertIntoListsForBlock(NewUseOrDef, NewBB, MemorySSA::End);
520 }
521 }
522 }
523}
524
Alina Sbirleaf31eba62019-05-08 17:05:36 +0000525void MemorySSAUpdater::updatePhisWhenInsertingUniqueBackedgeBlock(
526 BasicBlock *Header, BasicBlock *Preheader, BasicBlock *BEBlock) {
527 auto *MPhi = MSSA->getMemoryAccess(Header);
528 if (!MPhi)
529 return;
530
531 // Create phi node in the backedge block and populate it with the same
532 // incoming values as MPhi. Skip incoming values coming from Preheader.
533 auto *NewMPhi = MSSA->createMemoryPhi(BEBlock);
534 bool HasUniqueIncomingValue = true;
535 MemoryAccess *UniqueValue = nullptr;
536 for (unsigned I = 0, E = MPhi->getNumIncomingValues(); I != E; ++I) {
537 BasicBlock *IBB = MPhi->getIncomingBlock(I);
538 MemoryAccess *IV = MPhi->getIncomingValue(I);
539 if (IBB != Preheader) {
540 NewMPhi->addIncoming(IV, IBB);
541 if (HasUniqueIncomingValue) {
542 if (!UniqueValue)
543 UniqueValue = IV;
544 else if (UniqueValue != IV)
545 HasUniqueIncomingValue = false;
546 }
547 }
548 }
549
550 // Update incoming edges into MPhi. Remove all but the incoming edge from
551 // Preheader. Add an edge from NewMPhi
552 auto *AccFromPreheader = MPhi->getIncomingValueForBlock(Preheader);
553 MPhi->setIncomingValue(0, AccFromPreheader);
554 MPhi->setIncomingBlock(0, Preheader);
555 for (unsigned I = MPhi->getNumIncomingValues() - 1; I >= 1; --I)
556 MPhi->unorderedDeleteIncoming(I);
557 MPhi->addIncoming(NewMPhi, BEBlock);
558
559 // If NewMPhi is a trivial phi, remove it. Its use in the header MPhi will be
560 // replaced with the unique value.
561 if (HasUniqueIncomingValue)
562 removeMemoryAccess(NewMPhi);
563}
564
Alina Sbirlea79800992018-09-10 20:13:01 +0000565void MemorySSAUpdater::updateForClonedLoop(const LoopBlocksRPO &LoopBlocks,
566 ArrayRef<BasicBlock *> ExitBlocks,
567 const ValueToValueMapTy &VMap,
568 bool IgnoreIncomingWithNoClones) {
569 PhiToDefMap MPhiMap;
570
571 auto FixPhiIncomingValues = [&](MemoryPhi *Phi, MemoryPhi *NewPhi) {
572 assert(Phi && NewPhi && "Invalid Phi nodes.");
573 BasicBlock *NewPhiBB = NewPhi->getBlock();
574 SmallPtrSet<BasicBlock *, 4> NewPhiBBPreds(pred_begin(NewPhiBB),
575 pred_end(NewPhiBB));
576 for (unsigned It = 0, E = Phi->getNumIncomingValues(); It < E; ++It) {
577 MemoryAccess *IncomingAccess = Phi->getIncomingValue(It);
578 BasicBlock *IncBB = Phi->getIncomingBlock(It);
579
580 if (BasicBlock *NewIncBB = cast_or_null<BasicBlock>(VMap.lookup(IncBB)))
581 IncBB = NewIncBB;
582 else if (IgnoreIncomingWithNoClones)
583 continue;
584
585 // Now we have IncBB, and will need to add incoming from it to NewPhi.
586
587 // If IncBB is not a predecessor of NewPhiBB, then do not add it.
588 // NewPhiBB was cloned without that edge.
589 if (!NewPhiBBPreds.count(IncBB))
590 continue;
591
592 // Determine incoming value and add it as incoming from IncBB.
593 if (MemoryUseOrDef *IncMUD = dyn_cast<MemoryUseOrDef>(IncomingAccess)) {
594 if (!MSSA->isLiveOnEntryDef(IncMUD)) {
595 Instruction *IncI = IncMUD->getMemoryInst();
596 assert(IncI && "Found MemoryUseOrDef with no Instruction.");
597 if (Instruction *NewIncI =
598 cast_or_null<Instruction>(VMap.lookup(IncI))) {
599 IncMUD = MSSA->getMemoryAccess(NewIncI);
600 assert(IncMUD &&
601 "MemoryUseOrDef cannot be null, all preds processed.");
602 }
603 }
604 NewPhi->addIncoming(IncMUD, IncBB);
605 } else {
606 MemoryPhi *IncPhi = cast<MemoryPhi>(IncomingAccess);
607 if (MemoryAccess *NewDefPhi = MPhiMap.lookup(IncPhi))
608 NewPhi->addIncoming(NewDefPhi, IncBB);
609 else
610 NewPhi->addIncoming(IncPhi, IncBB);
611 }
612 }
613 };
614
615 auto ProcessBlock = [&](BasicBlock *BB) {
616 BasicBlock *NewBlock = cast_or_null<BasicBlock>(VMap.lookup(BB));
617 if (!NewBlock)
618 return;
619
620 assert(!MSSA->getWritableBlockAccesses(NewBlock) &&
621 "Cloned block should have no accesses");
622
623 // Add MemoryPhi.
624 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(BB)) {
625 MemoryPhi *NewPhi = MSSA->createMemoryPhi(NewBlock);
626 MPhiMap[MPhi] = NewPhi;
627 }
628 // Update Uses and Defs.
629 cloneUsesAndDefs(BB, NewBlock, VMap, MPhiMap);
630 };
631
632 for (auto BB : llvm::concat<BasicBlock *const>(LoopBlocks, ExitBlocks))
633 ProcessBlock(BB);
634
635 for (auto BB : llvm::concat<BasicBlock *const>(LoopBlocks, ExitBlocks))
636 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(BB))
637 if (MemoryAccess *NewPhi = MPhiMap.lookup(MPhi))
638 FixPhiIncomingValues(MPhi, cast<MemoryPhi>(NewPhi));
639}
640
641void MemorySSAUpdater::updateForClonedBlockIntoPred(
642 BasicBlock *BB, BasicBlock *P1, const ValueToValueMapTy &VM) {
643 // All defs/phis from outside BB that are used in BB, are valid uses in P1.
644 // Since those defs/phis must have dominated BB, and also dominate P1.
645 // Defs from BB being used in BB will be replaced with the cloned defs from
646 // VM. The uses of BB's Phi (if it exists) in BB will be replaced by the
647 // incoming def into the Phi from P1.
648 PhiToDefMap MPhiMap;
649 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(BB))
650 MPhiMap[MPhi] = MPhi->getIncomingValueForBlock(P1);
651 cloneUsesAndDefs(BB, P1, VM, MPhiMap);
652}
653
654template <typename Iter>
655void MemorySSAUpdater::privateUpdateExitBlocksForClonedLoop(
656 ArrayRef<BasicBlock *> ExitBlocks, Iter ValuesBegin, Iter ValuesEnd,
657 DominatorTree &DT) {
658 SmallVector<CFGUpdate, 4> Updates;
659 // Update/insert phis in all successors of exit blocks.
660 for (auto *Exit : ExitBlocks)
661 for (const ValueToValueMapTy *VMap : make_range(ValuesBegin, ValuesEnd))
662 if (BasicBlock *NewExit = cast_or_null<BasicBlock>(VMap->lookup(Exit))) {
663 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
664 Updates.push_back({DT.Insert, NewExit, ExitSucc});
665 }
666 applyInsertUpdates(Updates, DT);
667}
668
669void MemorySSAUpdater::updateExitBlocksForClonedLoop(
670 ArrayRef<BasicBlock *> ExitBlocks, const ValueToValueMapTy &VMap,
671 DominatorTree &DT) {
672 const ValueToValueMapTy *const Arr[] = {&VMap};
673 privateUpdateExitBlocksForClonedLoop(ExitBlocks, std::begin(Arr),
674 std::end(Arr), DT);
675}
676
677void MemorySSAUpdater::updateExitBlocksForClonedLoop(
678 ArrayRef<BasicBlock *> ExitBlocks,
679 ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps, DominatorTree &DT) {
680 auto GetPtr = [&](const std::unique_ptr<ValueToValueMapTy> &I) {
681 return I.get();
682 };
683 using MappedIteratorType =
684 mapped_iterator<const std::unique_ptr<ValueToValueMapTy> *,
685 decltype(GetPtr)>;
686 auto MapBegin = MappedIteratorType(VMaps.begin(), GetPtr);
687 auto MapEnd = MappedIteratorType(VMaps.end(), GetPtr);
688 privateUpdateExitBlocksForClonedLoop(ExitBlocks, MapBegin, MapEnd, DT);
689}
690
691void MemorySSAUpdater::applyUpdates(ArrayRef<CFGUpdate> Updates,
692 DominatorTree &DT) {
693 SmallVector<CFGUpdate, 4> RevDeleteUpdates;
694 SmallVector<CFGUpdate, 4> InsertUpdates;
695 for (auto &Update : Updates) {
696 if (Update.getKind() == DT.Insert)
697 InsertUpdates.push_back({DT.Insert, Update.getFrom(), Update.getTo()});
698 else
699 RevDeleteUpdates.push_back({DT.Insert, Update.getFrom(), Update.getTo()});
700 }
701
702 if (!RevDeleteUpdates.empty()) {
703 // Update for inserted edges: use newDT and snapshot CFG as if deletes had
Hiroshi Inoue02a2bb22019-02-05 08:30:48 +0000704 // not occurred.
Alina Sbirlea79800992018-09-10 20:13:01 +0000705 // FIXME: This creates a new DT, so it's more expensive to do mix
706 // delete/inserts vs just inserts. We can do an incremental update on the DT
707 // to revert deletes, than re-delete the edges. Teaching DT to do this, is
708 // part of a pending cleanup.
709 DominatorTree NewDT(DT, RevDeleteUpdates);
710 GraphDiff<BasicBlock *> GD(RevDeleteUpdates);
711 applyInsertUpdates(InsertUpdates, NewDT, &GD);
712 } else {
713 GraphDiff<BasicBlock *> GD;
714 applyInsertUpdates(InsertUpdates, DT, &GD);
715 }
716
717 // Update for deleted edges
718 for (auto &Update : RevDeleteUpdates)
719 removeEdge(Update.getFrom(), Update.getTo());
720}
721
722void MemorySSAUpdater::applyInsertUpdates(ArrayRef<CFGUpdate> Updates,
723 DominatorTree &DT) {
724 GraphDiff<BasicBlock *> GD;
725 applyInsertUpdates(Updates, DT, &GD);
726}
727
728void MemorySSAUpdater::applyInsertUpdates(ArrayRef<CFGUpdate> Updates,
729 DominatorTree &DT,
730 const GraphDiff<BasicBlock *> *GD) {
731 // Get recursive last Def, assuming well formed MSSA and updated DT.
732 auto GetLastDef = [&](BasicBlock *BB) -> MemoryAccess * {
733 while (true) {
734 MemorySSA::DefsList *Defs = MSSA->getWritableBlockDefs(BB);
735 // Return last Def or Phi in BB, if it exists.
736 if (Defs)
737 return &*(--Defs->end());
738
739 // Check number of predecessors, we only care if there's more than one.
740 unsigned Count = 0;
741 BasicBlock *Pred = nullptr;
742 for (auto &Pair : children<GraphDiffInvBBPair>({GD, BB})) {
743 Pred = Pair.second;
744 Count++;
745 if (Count == 2)
746 break;
747 }
748
749 // If BB has multiple predecessors, get last definition from IDom.
750 if (Count != 1) {
751 // [SimpleLoopUnswitch] If BB is a dead block, about to be deleted, its
752 // DT is invalidated. Return LoE as its last def. This will be added to
753 // MemoryPhi node, and later deleted when the block is deleted.
754 if (!DT.getNode(BB))
755 return MSSA->getLiveOnEntryDef();
756 if (auto *IDom = DT.getNode(BB)->getIDom())
757 if (IDom->getBlock() != BB) {
758 BB = IDom->getBlock();
759 continue;
760 }
761 return MSSA->getLiveOnEntryDef();
762 } else {
763 // Single predecessor, BB cannot be dead. GetLastDef of Pred.
764 assert(Count == 1 && Pred && "Single predecessor expected.");
765 BB = Pred;
766 }
767 };
768 llvm_unreachable("Unable to get last definition.");
769 };
770
771 // Get nearest IDom given a set of blocks.
772 // TODO: this can be optimized by starting the search at the node with the
773 // lowest level (highest in the tree).
774 auto FindNearestCommonDominator =
775 [&](const SmallSetVector<BasicBlock *, 2> &BBSet) -> BasicBlock * {
776 BasicBlock *PrevIDom = *BBSet.begin();
777 for (auto *BB : BBSet)
778 PrevIDom = DT.findNearestCommonDominator(PrevIDom, BB);
779 return PrevIDom;
780 };
781
782 // Get all blocks that dominate PrevIDom, stop when reaching CurrIDom. Do not
783 // include CurrIDom.
784 auto GetNoLongerDomBlocks =
785 [&](BasicBlock *PrevIDom, BasicBlock *CurrIDom,
786 SmallVectorImpl<BasicBlock *> &BlocksPrevDom) {
787 if (PrevIDom == CurrIDom)
788 return;
789 BlocksPrevDom.push_back(PrevIDom);
790 BasicBlock *NextIDom = PrevIDom;
791 while (BasicBlock *UpIDom =
792 DT.getNode(NextIDom)->getIDom()->getBlock()) {
793 if (UpIDom == CurrIDom)
794 break;
795 BlocksPrevDom.push_back(UpIDom);
796 NextIDom = UpIDom;
797 }
798 };
799
800 // Map a BB to its predecessors: added + previously existing. To get a
801 // deterministic order, store predecessors as SetVectors. The order in each
Hiroshi Inoue02a2bb22019-02-05 08:30:48 +0000802 // will be defined by the order in Updates (fixed) and the order given by
Alina Sbirlea79800992018-09-10 20:13:01 +0000803 // children<> (also fixed). Since we further iterate over these ordered sets,
804 // we lose the information of multiple edges possibly existing between two
805 // blocks, so we'll keep and EdgeCount map for that.
806 // An alternate implementation could keep unordered set for the predecessors,
807 // traverse either Updates or children<> each time to get the deterministic
808 // order, and drop the usage of EdgeCount. This alternate approach would still
809 // require querying the maps for each predecessor, and children<> call has
810 // additional computation inside for creating the snapshot-graph predecessors.
811 // As such, we favor using a little additional storage and less compute time.
812 // This decision can be revisited if we find the alternative more favorable.
813
814 struct PredInfo {
815 SmallSetVector<BasicBlock *, 2> Added;
816 SmallSetVector<BasicBlock *, 2> Prev;
817 };
818 SmallDenseMap<BasicBlock *, PredInfo> PredMap;
819
820 for (auto &Edge : Updates) {
821 BasicBlock *BB = Edge.getTo();
822 auto &AddedBlockSet = PredMap[BB].Added;
823 AddedBlockSet.insert(Edge.getFrom());
824 }
825
826 // Store all existing predecessor for each BB, at least one must exist.
827 SmallDenseMap<std::pair<BasicBlock *, BasicBlock *>, int> EdgeCountMap;
828 SmallPtrSet<BasicBlock *, 2> NewBlocks;
829 for (auto &BBPredPair : PredMap) {
830 auto *BB = BBPredPair.first;
831 const auto &AddedBlockSet = BBPredPair.second.Added;
832 auto &PrevBlockSet = BBPredPair.second.Prev;
833 for (auto &Pair : children<GraphDiffInvBBPair>({GD, BB})) {
834 BasicBlock *Pi = Pair.second;
835 if (!AddedBlockSet.count(Pi))
836 PrevBlockSet.insert(Pi);
837 EdgeCountMap[{Pi, BB}]++;
838 }
839
840 if (PrevBlockSet.empty()) {
841 assert(pred_size(BB) == AddedBlockSet.size() && "Duplicate edges added.");
842 LLVM_DEBUG(
843 dbgs()
844 << "Adding a predecessor to a block with no predecessors. "
845 "This must be an edge added to a new, likely cloned, block. "
846 "Its memory accesses must be already correct, assuming completed "
847 "via the updateExitBlocksForClonedLoop API. "
848 "Assert a single such edge is added so no phi addition or "
849 "additional processing is required.\n");
850 assert(AddedBlockSet.size() == 1 &&
851 "Can only handle adding one predecessor to a new block.");
852 // Need to remove new blocks from PredMap. Remove below to not invalidate
853 // iterator here.
854 NewBlocks.insert(BB);
855 }
856 }
857 // Nothing to process for new/cloned blocks.
858 for (auto *BB : NewBlocks)
859 PredMap.erase(BB);
860
861 SmallVector<BasicBlock *, 8> BlocksToProcess;
862 SmallVector<BasicBlock *, 16> BlocksWithDefsToReplace;
Alina Sbirleacb4ed8a2019-06-11 19:09:34 +0000863 SmallVector<WeakVH, 8> InsertedPhis;
Alina Sbirlea79800992018-09-10 20:13:01 +0000864
865 // First create MemoryPhis in all blocks that don't have one. Create in the
866 // order found in Updates, not in PredMap, to get deterministic numbering.
867 for (auto &Edge : Updates) {
868 BasicBlock *BB = Edge.getTo();
869 if (PredMap.count(BB) && !MSSA->getMemoryAccess(BB))
Alina Sbirleacb4ed8a2019-06-11 19:09:34 +0000870 InsertedPhis.push_back(MSSA->createMemoryPhi(BB));
Alina Sbirlea79800992018-09-10 20:13:01 +0000871 }
872
873 // Now we'll fill in the MemoryPhis with the right incoming values.
874 for (auto &BBPredPair : PredMap) {
875 auto *BB = BBPredPair.first;
876 const auto &PrevBlockSet = BBPredPair.second.Prev;
877 const auto &AddedBlockSet = BBPredPair.second.Added;
878 assert(!PrevBlockSet.empty() &&
879 "At least one previous predecessor must exist.");
880
881 // TODO: if this becomes a bottleneck, we can save on GetLastDef calls by
882 // keeping this map before the loop. We can reuse already populated entries
883 // if an edge is added from the same predecessor to two different blocks,
884 // and this does happen in rotate. Note that the map needs to be updated
885 // when deleting non-necessary phis below, if the phi is in the map by
886 // replacing the value with DefP1.
887 SmallDenseMap<BasicBlock *, MemoryAccess *> LastDefAddedPred;
888 for (auto *AddedPred : AddedBlockSet) {
889 auto *DefPn = GetLastDef(AddedPred);
890 assert(DefPn != nullptr && "Unable to find last definition.");
891 LastDefAddedPred[AddedPred] = DefPn;
892 }
893
894 MemoryPhi *NewPhi = MSSA->getMemoryAccess(BB);
895 // If Phi is not empty, add an incoming edge from each added pred. Must
896 // still compute blocks with defs to replace for this block below.
897 if (NewPhi->getNumOperands()) {
898 for (auto *Pred : AddedBlockSet) {
899 auto *LastDefForPred = LastDefAddedPred[Pred];
900 for (int I = 0, E = EdgeCountMap[{Pred, BB}]; I < E; ++I)
901 NewPhi->addIncoming(LastDefForPred, Pred);
902 }
903 } else {
904 // Pick any existing predecessor and get its definition. All other
905 // existing predecessors should have the same one, since no phi existed.
906 auto *P1 = *PrevBlockSet.begin();
907 MemoryAccess *DefP1 = GetLastDef(P1);
908
909 // Check DefP1 against all Defs in LastDefPredPair. If all the same,
910 // nothing to add.
911 bool InsertPhi = false;
912 for (auto LastDefPredPair : LastDefAddedPred)
913 if (DefP1 != LastDefPredPair.second) {
914 InsertPhi = true;
915 break;
916 }
917 if (!InsertPhi) {
918 // Since NewPhi may be used in other newly added Phis, replace all uses
919 // of NewPhi with the definition coming from all predecessors (DefP1),
920 // before deleting it.
921 NewPhi->replaceAllUsesWith(DefP1);
922 removeMemoryAccess(NewPhi);
923 continue;
924 }
925
926 // Update Phi with new values for new predecessors and old value for all
927 // other predecessors. Since AddedBlockSet and PrevBlockSet are ordered
928 // sets, the order of entries in NewPhi is deterministic.
929 for (auto *Pred : AddedBlockSet) {
930 auto *LastDefForPred = LastDefAddedPred[Pred];
931 for (int I = 0, E = EdgeCountMap[{Pred, BB}]; I < E; ++I)
932 NewPhi->addIncoming(LastDefForPred, Pred);
933 }
934 for (auto *Pred : PrevBlockSet)
935 for (int I = 0, E = EdgeCountMap[{Pred, BB}]; I < E; ++I)
936 NewPhi->addIncoming(DefP1, Pred);
937
938 // Insert BB in the set of blocks that now have definition. We'll use this
939 // to compute IDF and add Phis there next.
940 BlocksToProcess.push_back(BB);
941 }
942
943 // Get all blocks that used to dominate BB and no longer do after adding
944 // AddedBlockSet, where PrevBlockSet are the previously known predecessors.
945 assert(DT.getNode(BB)->getIDom() && "BB does not have valid idom");
946 BasicBlock *PrevIDom = FindNearestCommonDominator(PrevBlockSet);
947 assert(PrevIDom && "Previous IDom should exists");
948 BasicBlock *NewIDom = DT.getNode(BB)->getIDom()->getBlock();
949 assert(NewIDom && "BB should have a new valid idom");
950 assert(DT.dominates(NewIDom, PrevIDom) &&
951 "New idom should dominate old idom");
952 GetNoLongerDomBlocks(PrevIDom, NewIDom, BlocksWithDefsToReplace);
953 }
954
955 // Compute IDF and add Phis in all IDF blocks that do not have one.
956 SmallVector<BasicBlock *, 32> IDFBlocks;
957 if (!BlocksToProcess.empty()) {
958 ForwardIDFCalculator IDFs(DT);
959 SmallPtrSet<BasicBlock *, 16> DefiningBlocks(BlocksToProcess.begin(),
960 BlocksToProcess.end());
961 IDFs.setDefiningBlocks(DefiningBlocks);
962 IDFs.calculate(IDFBlocks);
Alina Sbirlea05f77802019-06-17 18:16:53 +0000963
964 SmallSetVector<MemoryPhi *, 4> PhisToFill;
965 // First create all needed Phis.
966 for (auto *BBIDF : IDFBlocks)
967 if (!MSSA->getMemoryAccess(BBIDF)) {
968 auto *IDFPhi = MSSA->createMemoryPhi(BBIDF);
969 InsertedPhis.push_back(IDFPhi);
970 PhisToFill.insert(IDFPhi);
971 }
972 // Then update or insert their correct incoming values.
Alina Sbirlea79800992018-09-10 20:13:01 +0000973 for (auto *BBIDF : IDFBlocks) {
Alina Sbirlea05f77802019-06-17 18:16:53 +0000974 auto *IDFPhi = MSSA->getMemoryAccess(BBIDF);
975 assert(IDFPhi && "Phi must exist");
976 if (!PhisToFill.count(IDFPhi)) {
Alina Sbirlea79800992018-09-10 20:13:01 +0000977 // Update existing Phi.
978 // FIXME: some updates may be redundant, try to optimize and skip some.
979 for (unsigned I = 0, E = IDFPhi->getNumIncomingValues(); I < E; ++I)
980 IDFPhi->setIncomingValue(I, GetLastDef(IDFPhi->getIncomingBlock(I)));
981 } else {
Alina Sbirlea79800992018-09-10 20:13:01 +0000982 for (auto &Pair : children<GraphDiffInvBBPair>({GD, BBIDF})) {
983 BasicBlock *Pi = Pair.second;
984 IDFPhi->addIncoming(GetLastDef(Pi), Pi);
985 }
986 }
987 }
988 }
989
990 // Now for all defs in BlocksWithDefsToReplace, if there are uses they no
991 // longer dominate, replace those with the closest dominating def.
992 // This will also update optimized accesses, as they're also uses.
993 for (auto *BlockWithDefsToReplace : BlocksWithDefsToReplace) {
994 if (auto DefsList = MSSA->getWritableBlockDefs(BlockWithDefsToReplace)) {
995 for (auto &DefToReplaceUses : *DefsList) {
996 BasicBlock *DominatingBlock = DefToReplaceUses.getBlock();
997 Value::use_iterator UI = DefToReplaceUses.use_begin(),
998 E = DefToReplaceUses.use_end();
999 for (; UI != E;) {
1000 Use &U = *UI;
1001 ++UI;
1002 MemoryAccess *Usr = dyn_cast<MemoryAccess>(U.getUser());
1003 if (MemoryPhi *UsrPhi = dyn_cast<MemoryPhi>(Usr)) {
1004 BasicBlock *DominatedBlock = UsrPhi->getIncomingBlock(U);
1005 if (!DT.dominates(DominatingBlock, DominatedBlock))
1006 U.set(GetLastDef(DominatedBlock));
1007 } else {
1008 BasicBlock *DominatedBlock = Usr->getBlock();
1009 if (!DT.dominates(DominatingBlock, DominatedBlock)) {
1010 if (auto *DomBlPhi = MSSA->getMemoryAccess(DominatedBlock))
1011 U.set(DomBlPhi);
1012 else {
1013 auto *IDom = DT.getNode(DominatedBlock)->getIDom();
1014 assert(IDom && "Block must have a valid IDom.");
1015 U.set(GetLastDef(IDom->getBlock()));
1016 }
1017 cast<MemoryUseOrDef>(Usr)->resetOptimized();
1018 }
1019 }
1020 }
1021 }
1022 }
1023 }
Alina Sbirleacb4ed8a2019-06-11 19:09:34 +00001024 tryRemoveTrivialPhis(InsertedPhis);
Alina Sbirlea79800992018-09-10 20:13:01 +00001025}
1026
Daniel Berlinae6b8b62017-01-28 01:35:02 +00001027// Move What before Where in the MemorySSA IR.
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001028template <class WhereType>
Daniel Berlinae6b8b62017-01-28 01:35:02 +00001029void MemorySSAUpdater::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001030 WhereType Where) {
Zhaoshi Zheng43af17b2018-04-09 20:55:37 +00001031 // Mark MemoryPhi users of What not to be optimized.
1032 for (auto *U : What->users())
George Burgess IVe7cdb7e2018-07-12 21:56:31 +00001033 if (MemoryPhi *PhiUser = dyn_cast<MemoryPhi>(U))
Zhaoshi Zheng43af17b2018-04-09 20:55:37 +00001034 NonOptPhis.insert(PhiUser);
1035
Daniel Berlinae6b8b62017-01-28 01:35:02 +00001036 // Replace all our users with our defining access.
1037 What->replaceAllUsesWith(What->getDefiningAccess());
1038
1039 // Let MemorySSA take care of moving it around in the lists.
1040 MSSA->moveTo(What, BB, Where);
1041
1042 // Now reinsert it into the IR and do whatever fixups needed.
1043 if (auto *MD = dyn_cast<MemoryDef>(What))
1044 insertDef(MD);
1045 else
1046 insertUse(cast<MemoryUse>(What));
Zhaoshi Zheng43af17b2018-04-09 20:55:37 +00001047
1048 // Clear dangling pointers. We added all MemoryPhi users, but not all
1049 // of them are removed by fixupDefs().
1050 NonOptPhis.clear();
Daniel Berlinae6b8b62017-01-28 01:35:02 +00001051}
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001052
Daniel Berlinae6b8b62017-01-28 01:35:02 +00001053// Move What before Where in the MemorySSA IR.
1054void MemorySSAUpdater::moveBefore(MemoryUseOrDef *What, MemoryUseOrDef *Where) {
1055 moveTo(What, Where->getBlock(), Where->getIterator());
1056}
1057
1058// Move What after Where in the MemorySSA IR.
1059void MemorySSAUpdater::moveAfter(MemoryUseOrDef *What, MemoryUseOrDef *Where) {
1060 moveTo(What, Where->getBlock(), ++Where->getIterator());
1061}
1062
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001063void MemorySSAUpdater::moveToPlace(MemoryUseOrDef *What, BasicBlock *BB,
1064 MemorySSA::InsertionPlace Where) {
1065 return moveTo(What, BB, Where);
1066}
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001067
Alina Sbirlea0f533552018-07-11 22:11:46 +00001068// All accesses in To used to be in From. Move to end and update access lists.
1069void MemorySSAUpdater::moveAllAccesses(BasicBlock *From, BasicBlock *To,
1070 Instruction *Start) {
1071
1072 MemorySSA::AccessList *Accs = MSSA->getWritableBlockAccesses(From);
1073 if (!Accs)
1074 return;
1075
1076 MemoryAccess *FirstInNew = nullptr;
1077 for (Instruction &I : make_range(Start->getIterator(), To->end()))
1078 if ((FirstInNew = MSSA->getMemoryAccess(&I)))
1079 break;
1080 if (!FirstInNew)
1081 return;
1082
1083 auto *MUD = cast<MemoryUseOrDef>(FirstInNew);
1084 do {
1085 auto NextIt = ++MUD->getIterator();
1086 MemoryUseOrDef *NextMUD = (!Accs || NextIt == Accs->end())
1087 ? nullptr
1088 : cast<MemoryUseOrDef>(&*NextIt);
1089 MSSA->moveTo(MUD, To, MemorySSA::End);
1090 // Moving MUD from Accs in the moveTo above, may delete Accs, so we need to
1091 // retrieve it again.
1092 Accs = MSSA->getWritableBlockAccesses(From);
1093 MUD = NextMUD;
1094 } while (MUD);
1095}
1096
1097void MemorySSAUpdater::moveAllAfterSpliceBlocks(BasicBlock *From,
1098 BasicBlock *To,
1099 Instruction *Start) {
1100 assert(MSSA->getBlockAccesses(To) == nullptr &&
1101 "To block is expected to be free of MemoryAccesses.");
1102 moveAllAccesses(From, To, Start);
1103 for (BasicBlock *Succ : successors(To))
1104 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(Succ))
1105 MPhi->setIncomingBlock(MPhi->getBasicBlockIndex(From), To);
1106}
1107
1108void MemorySSAUpdater::moveAllAfterMergeBlocks(BasicBlock *From, BasicBlock *To,
1109 Instruction *Start) {
1110 assert(From->getSinglePredecessor() == To &&
1111 "From block is expected to have a single predecessor (To).");
1112 moveAllAccesses(From, To, Start);
1113 for (BasicBlock *Succ : successors(From))
1114 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(Succ))
1115 MPhi->setIncomingBlock(MPhi->getBasicBlockIndex(From), To);
1116}
1117
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001118/// If all arguments of a MemoryPHI are defined by the same incoming
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001119/// argument, return that argument.
1120static MemoryAccess *onlySingleValue(MemoryPhi *MP) {
1121 MemoryAccess *MA = nullptr;
1122
1123 for (auto &Arg : MP->operands()) {
1124 if (!MA)
1125 MA = cast<MemoryAccess>(Arg);
1126 else if (MA != Arg)
1127 return nullptr;
1128 }
1129 return MA;
1130}
George Burgess IV56169ed2017-04-21 04:54:52 +00001131
Alina Sbirlea20c29622018-07-20 17:13:05 +00001132void MemorySSAUpdater::wireOldPredecessorsToNewImmediatePredecessor(
Alina Sbirleaf98c2c52018-09-07 21:14:48 +00001133 BasicBlock *Old, BasicBlock *New, ArrayRef<BasicBlock *> Preds,
1134 bool IdenticalEdgesWereMerged) {
Alina Sbirlea20c29622018-07-20 17:13:05 +00001135 assert(!MSSA->getWritableBlockAccesses(New) &&
1136 "Access list should be null for a new block.");
1137 MemoryPhi *Phi = MSSA->getMemoryAccess(Old);
1138 if (!Phi)
1139 return;
Vedant Kumar4de31bb2018-11-19 19:54:27 +00001140 if (Old->hasNPredecessors(1)) {
Alina Sbirlea20c29622018-07-20 17:13:05 +00001141 assert(pred_size(New) == Preds.size() &&
1142 "Should have moved all predecessors.");
1143 MSSA->moveTo(Phi, New, MemorySSA::Beginning);
1144 } else {
1145 assert(!Preds.empty() && "Must be moving at least one predecessor to the "
1146 "new immediate predecessor.");
1147 MemoryPhi *NewPhi = MSSA->createMemoryPhi(New);
1148 SmallPtrSet<BasicBlock *, 16> PredsSet(Preds.begin(), Preds.end());
Alina Sbirleaf98c2c52018-09-07 21:14:48 +00001149 // Currently only support the case of removing a single incoming edge when
1150 // identical edges were not merged.
1151 if (!IdenticalEdgesWereMerged)
1152 assert(PredsSet.size() == Preds.size() &&
1153 "If identical edges were not merged, we cannot have duplicate "
1154 "blocks in the predecessors");
Alina Sbirlea20c29622018-07-20 17:13:05 +00001155 Phi->unorderedDeleteIncomingIf([&](MemoryAccess *MA, BasicBlock *B) {
1156 if (PredsSet.count(B)) {
1157 NewPhi->addIncoming(MA, B);
Alina Sbirleaf98c2c52018-09-07 21:14:48 +00001158 if (!IdenticalEdgesWereMerged)
1159 PredsSet.erase(B);
Alina Sbirlea20c29622018-07-20 17:13:05 +00001160 return true;
1161 }
1162 return false;
1163 });
1164 Phi->addIncoming(NewPhi, New);
1165 if (onlySingleValue(NewPhi))
1166 removeMemoryAccess(NewPhi);
1167 }
1168}
1169
Alina Sbirlea240a90a2019-01-31 20:13:47 +00001170void MemorySSAUpdater::removeMemoryAccess(MemoryAccess *MA, bool OptimizePhis) {
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001171 assert(!MSSA->isLiveOnEntryDef(MA) &&
1172 "Trying to remove the live on entry def");
1173 // We can only delete phi nodes if they have no uses, or we can replace all
1174 // uses with a single definition.
1175 MemoryAccess *NewDefTarget = nullptr;
1176 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) {
1177 // Note that it is sufficient to know that all edges of the phi node have
1178 // the same argument. If they do, by the definition of dominance frontiers
1179 // (which we used to place this phi), that argument must dominate this phi,
1180 // and thus, must dominate the phi's uses, and so we will not hit the assert
1181 // below.
1182 NewDefTarget = onlySingleValue(MP);
1183 assert((NewDefTarget || MP->use_empty()) &&
1184 "We can't delete this memory phi");
1185 } else {
1186 NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess();
1187 }
1188
Alina Sbirlea240a90a2019-01-31 20:13:47 +00001189 SmallSetVector<MemoryPhi *, 4> PhisToCheck;
1190
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001191 // Re-point the uses at our defining access
1192 if (!isa<MemoryUse>(MA) && !MA->use_empty()) {
1193 // Reset optimized on users of this store, and reset the uses.
1194 // A few notes:
1195 // 1. This is a slightly modified version of RAUW to avoid walking the
1196 // uses twice here.
1197 // 2. If we wanted to be complete, we would have to reset the optimized
1198 // flags on users of phi nodes if doing the below makes a phi node have all
1199 // the same arguments. Instead, we prefer users to removeMemoryAccess those
1200 // phi nodes, because doing it here would be N^3.
1201 if (MA->hasValueHandle())
1202 ValueHandleBase::ValueIsRAUWd(MA, NewDefTarget);
1203 // Note: We assume MemorySSA is not used in metadata since it's not really
1204 // part of the IR.
1205
1206 while (!MA->use_empty()) {
1207 Use &U = *MA->use_begin();
Daniel Berline33bc312017-04-04 23:43:10 +00001208 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U.getUser()))
1209 MUD->resetOptimized();
Alina Sbirlea240a90a2019-01-31 20:13:47 +00001210 if (OptimizePhis)
1211 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(U.getUser()))
1212 PhisToCheck.insert(MP);
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001213 U.set(NewDefTarget);
1214 }
1215 }
1216
1217 // The call below to erase will destroy MA, so we can't change the order we
1218 // are doing things here
1219 MSSA->removeFromLookups(MA);
1220 MSSA->removeFromLists(MA);
Alina Sbirlea240a90a2019-01-31 20:13:47 +00001221
1222 // Optionally optimize Phi uses. This will recursively remove trivial phis.
1223 if (!PhisToCheck.empty()) {
1224 SmallVector<WeakVH, 16> PhisToOptimize{PhisToCheck.begin(),
1225 PhisToCheck.end()};
1226 PhisToCheck.clear();
1227
1228 unsigned PhisSize = PhisToOptimize.size();
1229 while (PhisSize-- > 0)
1230 if (MemoryPhi *MP =
1231 cast_or_null<MemoryPhi>(PhisToOptimize.pop_back_val())) {
1232 auto OperRange = MP->operands();
1233 tryRemoveTrivialPhi(MP, OperRange);
1234 }
1235 }
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001236}
1237
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001238void MemorySSAUpdater::removeBlocks(
1239 const SmallPtrSetImpl<BasicBlock *> &DeadBlocks) {
1240 // First delete all uses of BB in MemoryPhis.
1241 for (BasicBlock *BB : DeadBlocks) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00001242 Instruction *TI = BB->getTerminator();
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001243 assert(TI && "Basic block expected to have a terminator instruction");
Chandler Carruth96fc1de2018-08-26 08:41:15 +00001244 for (BasicBlock *Succ : successors(TI))
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001245 if (!DeadBlocks.count(Succ))
1246 if (MemoryPhi *MP = MSSA->getMemoryAccess(Succ)) {
1247 MP->unorderedDeleteIncomingBlock(BB);
1248 if (MP->getNumIncomingValues() == 1)
1249 removeMemoryAccess(MP);
1250 }
1251 // Drop all references of all accesses in BB
1252 if (MemorySSA::AccessList *Acc = MSSA->getWritableBlockAccesses(BB))
1253 for (MemoryAccess &MA : *Acc)
1254 MA.dropAllReferences();
1255 }
1256
1257 // Next, delete all memory accesses in each block
1258 for (BasicBlock *BB : DeadBlocks) {
1259 MemorySSA::AccessList *Acc = MSSA->getWritableBlockAccesses(BB);
1260 if (!Acc)
1261 continue;
1262 for (auto AB = Acc->begin(), AE = Acc->end(); AB != AE;) {
1263 MemoryAccess *MA = &*AB;
1264 ++AB;
1265 MSSA->removeFromLookups(MA);
1266 MSSA->removeFromLists(MA);
1267 }
1268 }
1269}
1270
Alina Sbirlea151ab482019-05-02 23:12:49 +00001271void MemorySSAUpdater::tryRemoveTrivialPhis(ArrayRef<WeakVH> UpdatedPHIs) {
1272 for (auto &VH : UpdatedPHIs)
1273 if (auto *MPhi = cast_or_null<MemoryPhi>(VH)) {
1274 auto OperRange = MPhi->operands();
1275 tryRemoveTrivialPhi(MPhi, OperRange);
1276 }
1277}
1278
Alina Sbirleaf31eba62019-05-08 17:05:36 +00001279void MemorySSAUpdater::changeToUnreachable(const Instruction *I) {
1280 const BasicBlock *BB = I->getParent();
1281 // Remove memory accesses in BB for I and all following instructions.
1282 auto BBI = I->getIterator(), BBE = BB->end();
1283 // FIXME: If this becomes too expensive, iterate until the first instruction
1284 // with a memory access, then iterate over MemoryAccesses.
1285 while (BBI != BBE)
1286 removeMemoryAccess(&*(BBI++));
1287 // Update phis in BB's successors to remove BB.
1288 SmallVector<WeakVH, 16> UpdatedPHIs;
1289 for (const BasicBlock *Successor : successors(BB)) {
1290 removeDuplicatePhiEdgesBetween(BB, Successor);
1291 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(Successor)) {
1292 MPhi->unorderedDeleteIncomingBlock(BB);
1293 UpdatedPHIs.push_back(MPhi);
1294 }
1295 }
1296 // Optimize trivial phis.
1297 tryRemoveTrivialPhis(UpdatedPHIs);
1298}
1299
1300void MemorySSAUpdater::changeCondBranchToUnconditionalTo(const BranchInst *BI,
1301 const BasicBlock *To) {
1302 const BasicBlock *BB = BI->getParent();
1303 SmallVector<WeakVH, 16> UpdatedPHIs;
1304 for (const BasicBlock *Succ : successors(BB)) {
1305 removeDuplicatePhiEdgesBetween(BB, Succ);
1306 if (Succ != To)
1307 if (auto *MPhi = MSSA->getMemoryAccess(Succ)) {
1308 MPhi->unorderedDeleteIncomingBlock(BB);
1309 UpdatedPHIs.push_back(MPhi);
1310 }
1311 }
1312 // Optimize trivial phis.
1313 tryRemoveTrivialPhis(UpdatedPHIs);
1314}
1315
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001316MemoryAccess *MemorySSAUpdater::createMemoryAccessInBB(
1317 Instruction *I, MemoryAccess *Definition, const BasicBlock *BB,
1318 MemorySSA::InsertionPlace Point) {
1319 MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition);
1320 MSSA->insertIntoListsForBlock(NewAccess, BB, Point);
1321 return NewAccess;
1322}
1323
1324MemoryUseOrDef *MemorySSAUpdater::createMemoryAccessBefore(
1325 Instruction *I, MemoryAccess *Definition, MemoryUseOrDef *InsertPt) {
1326 assert(I->getParent() == InsertPt->getBlock() &&
1327 "New and old access must be in the same block");
1328 MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition);
1329 MSSA->insertIntoListsBefore(NewAccess, InsertPt->getBlock(),
1330 InsertPt->getIterator());
1331 return NewAccess;
1332}
1333
1334MemoryUseOrDef *MemorySSAUpdater::createMemoryAccessAfter(
1335 Instruction *I, MemoryAccess *Definition, MemoryAccess *InsertPt) {
1336 assert(I->getParent() == InsertPt->getBlock() &&
1337 "New and old access must be in the same block");
1338 MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition);
1339 MSSA->insertIntoListsBefore(NewAccess, InsertPt->getBlock(),
1340 ++InsertPt->getIterator());
1341 return NewAccess;
1342}