blob: 78e197aad5545b6eace86ad3de21489fd875283b [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.
Alina Sbirlea6720ed82019-09-25 23:24:39 +000074 bool UniqueIncomingAccess = true;
75 MemoryAccess *SingleAccess = nullptr;
76 for (auto *Pred : predecessors(BB)) {
77 if (MSSA->DT->isReachableFromEntry(Pred)) {
78 auto *IncomingAccess = getPreviousDefFromEnd(Pred, CachedPreviousDef);
79 if (!SingleAccess)
80 SingleAccess = IncomingAccess;
81 else if (IncomingAccess != SingleAccess)
82 UniqueIncomingAccess = false;
83 PhiOps.push_back(IncomingAccess);
84 } else
Alina Sbirlea0363c3b2019-05-02 23:41:58 +000085 PhiOps.push_back(MSSA->getLiveOnEntryDef());
Alina Sbirlea6720ed82019-09-25 23:24:39 +000086 }
Daniel Berlinae6b8b62017-01-28 01:35:02 +000087
88 // Now try to simplify the ops to avoid placing a phi.
89 // This may return null if we never created a phi yet, that's okay
90 MemoryPhi *Phi = dyn_cast_or_null<MemoryPhi>(MSSA->getMemoryAccess(BB));
Daniel Berlinae6b8b62017-01-28 01:35:02 +000091
92 // See if we can avoid the phi by simplifying it.
93 auto *Result = tryRemoveTrivialPhi(Phi, PhiOps);
94 // If we couldn't simplify, we may have to create a phi
Alina Sbirlea6720ed82019-09-25 23:24:39 +000095 if (Result == Phi && UniqueIncomingAccess && SingleAccess)
96 Result = SingleAccess;
97 else if (Result == Phi && !(UniqueIncomingAccess && SingleAccess)) {
Daniel Berlinae6b8b62017-01-28 01:35:02 +000098 if (!Phi)
99 Phi = MSSA->createMemoryPhi(BB);
100
Alexandros Lamprineasbf6009c2018-07-23 10:56:30 +0000101 // See if the existing phi operands match what we need.
102 // Unlike normal SSA, we only allow one phi node per block, so we can't just
103 // create a new one.
104 if (Phi->getNumOperands() != 0) {
105 // FIXME: Figure out whether this is dead code and if so remove it.
106 if (!std::equal(Phi->op_begin(), Phi->op_end(), PhiOps.begin())) {
107 // These will have been filled in by the recursive read we did above.
Fangrui Song75709322018-11-17 01:44:25 +0000108 llvm::copy(PhiOps, Phi->op_begin());
Alexandros Lamprineasbf6009c2018-07-23 10:56:30 +0000109 std::copy(pred_begin(BB), pred_end(BB), Phi->block_begin());
110 }
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000111 } else {
112 unsigned i = 0;
113 for (auto *Pred : predecessors(BB))
Alexandros Lamprineasbf6009c2018-07-23 10:56:30 +0000114 Phi->addIncoming(&*PhiOps[i++], Pred);
Daniel Berlin97f34e82017-09-27 05:35:19 +0000115 InsertedPHIs.push_back(Phi);
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000116 }
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000117 Result = Phi;
118 }
Daniel Berlin97f34e82017-09-27 05:35:19 +0000119
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000120 // Set ourselves up for the next variable by resetting visited state.
121 VisitedBlocks.erase(BB);
Eli Friedman88e2bac2018-03-26 19:52:54 +0000122 CachedPreviousDef.insert({BB, Result});
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000123 return Result;
124 }
125 llvm_unreachable("Should have hit one of the three cases above");
126}
127
128// This starts at the memory access, and goes backwards in the block to find the
129// previous definition. If a definition is not found the block of the access,
130// it continues globally, creating phi nodes to ensure we have a single
131// definition.
132MemoryAccess *MemorySSAUpdater::getPreviousDef(MemoryAccess *MA) {
Eli Friedman88e2bac2018-03-26 19:52:54 +0000133 if (auto *LocalResult = getPreviousDefInBlock(MA))
134 return LocalResult;
135 DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> CachedPreviousDef;
136 return getPreviousDefRecursive(MA->getBlock(), CachedPreviousDef);
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000137}
138
139// This starts at the memory access, and goes backwards in the block to the find
140// the previous definition. If the definition is not found in the block of the
141// access, it returns nullptr.
142MemoryAccess *MemorySSAUpdater::getPreviousDefInBlock(MemoryAccess *MA) {
143 auto *Defs = MSSA->getWritableBlockDefs(MA->getBlock());
144
145 // It's possible there are no defs, or we got handed the first def to start.
146 if (Defs) {
147 // If this is a def, we can just use the def iterators.
148 if (!isa<MemoryUse>(MA)) {
149 auto Iter = MA->getReverseDefsIterator();
150 ++Iter;
151 if (Iter != Defs->rend())
152 return &*Iter;
153 } else {
154 // Otherwise, have to walk the all access iterator.
Alina Sbirlea33e58722017-06-07 16:46:53 +0000155 auto End = MSSA->getWritableBlockAccesses(MA->getBlock())->rend();
156 for (auto &U : make_range(++MA->getReverseIterator(), End))
157 if (!isa<MemoryUse>(U))
158 return cast<MemoryAccess>(&U);
159 // Note that if MA comes before Defs->begin(), we won't hit a def.
160 return nullptr;
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000161 }
162 }
163 return nullptr;
164}
165
166// This starts at the end of block
Eli Friedman88e2bac2018-03-26 19:52:54 +0000167MemoryAccess *MemorySSAUpdater::getPreviousDefFromEnd(
168 BasicBlock *BB,
169 DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> &CachedPreviousDef) {
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000170 auto *Defs = MSSA->getWritableBlockDefs(BB);
171
Alina Sbirleaf9f073a2019-04-12 21:58:52 +0000172 if (Defs) {
173 CachedPreviousDef.insert({BB, &*Defs->rbegin()});
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000174 return &*Defs->rbegin();
Alina Sbirleaf9f073a2019-04-12 21:58:52 +0000175 }
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000176
Eli Friedman88e2bac2018-03-26 19:52:54 +0000177 return getPreviousDefRecursive(BB, CachedPreviousDef);
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000178}
179// Recurse over a set of phi uses to eliminate the trivial ones
180MemoryAccess *MemorySSAUpdater::recursePhi(MemoryAccess *Phi) {
181 if (!Phi)
182 return nullptr;
183 TrackingVH<MemoryAccess> Res(Phi);
184 SmallVector<TrackingVH<Value>, 8> Uses;
185 std::copy(Phi->user_begin(), Phi->user_end(), std::back_inserter(Uses));
Alina Sbirlea28637212019-08-20 22:47:58 +0000186 for (auto &U : Uses)
187 if (MemoryPhi *UsePhi = dyn_cast<MemoryPhi>(&*U))
188 tryRemoveTrivialPhi(UsePhi);
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000189 return Res;
190}
191
192// Eliminate trivial phis
193// Phis are trivial if they are defined either by themselves, or all the same
194// argument.
195// IE phi(a, a) or b = phi(a, b) or c = phi(a, a, c)
196// We recursively try to remove them.
Alina Sbirlea28637212019-08-20 22:47:58 +0000197MemoryAccess *MemorySSAUpdater::tryRemoveTrivialPhi(MemoryPhi *Phi) {
198 assert(Phi && "Can only remove concrete Phi.");
199 auto OperRange = Phi->operands();
200 return tryRemoveTrivialPhi(Phi, OperRange);
201}
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000202template <class RangeType>
203MemoryAccess *MemorySSAUpdater::tryRemoveTrivialPhi(MemoryPhi *Phi,
204 RangeType &Operands) {
Zhaoshi Zheng43af17b2018-04-09 20:55:37 +0000205 // Bail out on non-opt Phis.
206 if (NonOptPhis.count(Phi))
207 return Phi;
208
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000209 // Detect equal or self arguments
210 MemoryAccess *Same = nullptr;
211 for (auto &Op : Operands) {
212 // If the same or self, good so far
213 if (Op == Phi || Op == Same)
214 continue;
215 // not the same, return the phi since it's not eliminatable by us
216 if (Same)
217 return Phi;
Alexandros Lamprineasbf6009c2018-07-23 10:56:30 +0000218 Same = cast<MemoryAccess>(&*Op);
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000219 }
220 // Never found a non-self reference, the phi is undef
221 if (Same == nullptr)
222 return MSSA->getLiveOnEntryDef();
223 if (Phi) {
224 Phi->replaceAllUsesWith(Same);
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000225 removeMemoryAccess(Phi);
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000226 }
227
228 // We should only end up recursing in case we replaced something, in which
229 // case, we may have made other Phis trivial.
230 return recursePhi(Same);
231}
232
Alina Sbirlea1a3fdaf2019-08-19 18:57:40 +0000233void MemorySSAUpdater::insertUse(MemoryUse *MU, bool RenameUses) {
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000234 InsertedPHIs.clear();
235 MU->setDefiningAccess(getPreviousDef(MU));
Alina Sbirlea1a3fdaf2019-08-19 18:57:40 +0000236 // In cases without unreachable blocks, because uses do not create new
237 // may-defs, there are only two cases:
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000238 // 1. There was a def already below us, and therefore, we should not have
239 // created a phi node because it was already needed for the def.
240 //
241 // 2. There is no def below us, and therefore, there is no extra renaming work
242 // to do.
Alina Sbirlea1a3fdaf2019-08-19 18:57:40 +0000243
244 // In cases with unreachable blocks, where the unnecessary Phis were
245 // optimized out, adding the Use may re-insert those Phis. Hence, when
246 // inserting Uses outside of the MSSA creation process, and new Phis were
247 // added, rename all uses if we are asked.
248
249 if (!RenameUses && !InsertedPHIs.empty()) {
250 auto *Defs = MSSA->getBlockDefs(MU->getBlock());
251 (void)Defs;
252 assert((!Defs || (++Defs->begin() == Defs->end())) &&
253 "Block may have only a Phi or no defs");
254 }
255
256 if (RenameUses && InsertedPHIs.size()) {
257 SmallPtrSet<BasicBlock *, 16> Visited;
258 BasicBlock *StartBlock = MU->getBlock();
259
260 if (auto *Defs = MSSA->getWritableBlockDefs(StartBlock)) {
261 MemoryAccess *FirstDef = &*Defs->begin();
262 // Convert to incoming value if it's a memorydef. A phi *is* already an
263 // incoming value.
264 if (auto *MD = dyn_cast<MemoryDef>(FirstDef))
265 FirstDef = MD->getDefiningAccess();
266
267 MSSA->renamePass(MU->getBlock(), FirstDef, Visited);
Alina Sbirlea1a3fdaf2019-08-19 18:57:40 +0000268 }
Alina Sbirlea228ffac2019-08-27 00:34:47 +0000269 // We just inserted a phi into this block, so the incoming value will
270 // become the phi anyway, so it does not matter what we pass.
271 for (auto &MP : InsertedPHIs)
272 if (MemoryPhi *Phi = cast_or_null<MemoryPhi>(MP))
273 MSSA->renamePass(Phi->getBlock(), nullptr, Visited);
Alina Sbirlea1a3fdaf2019-08-19 18:57:40 +0000274 }
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000275}
276
Daniel Berlin9d8a3352017-01-30 11:35:39 +0000277// Set every incoming edge {BB, MP->getBlock()} of MemoryPhi MP to NewDef.
George Burgess IV56169ed2017-04-21 04:54:52 +0000278static void setMemoryPhiValueForBlock(MemoryPhi *MP, const BasicBlock *BB,
279 MemoryAccess *NewDef) {
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000280 // Replace any operand with us an incoming block with the new defining
281 // access.
282 int i = MP->getBasicBlockIndex(BB);
283 assert(i != -1 && "Should have found the basic block in the phi");
Daniel Berlin9d8a3352017-01-30 11:35:39 +0000284 // We can't just compare i against getNumOperands since one is signed and the
285 // other not. So use it to index into the block iterator.
286 for (auto BBIter = MP->block_begin() + i; BBIter != MP->block_end();
287 ++BBIter) {
288 if (*BBIter != BB)
289 break;
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000290 MP->setIncomingValue(i, NewDef);
291 ++i;
292 }
293}
294
295// A brief description of the algorithm:
296// First, we compute what should define the new def, using the SSA
297// construction algorithm.
298// Then, we update the defs below us (and any new phi nodes) in the graph to
299// point to the correct new defs, to ensure we only have one variable, and no
300// disconnected stores.
Daniel Berlin78cbd282017-02-20 22:26:03 +0000301void MemorySSAUpdater::insertDef(MemoryDef *MD, bool RenameUses) {
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000302 InsertedPHIs.clear();
303
304 // See if we had a local def, and if not, go hunting.
Eli Friedman88e2bac2018-03-26 19:52:54 +0000305 MemoryAccess *DefBefore = getPreviousDef(MD);
Alina Sbirleaae40dfc2019-10-01 18:34:39 +0000306 bool DefBeforeSameBlock = false;
307 if (DefBefore->getBlock() == MD->getBlock() &&
308 !(isa<MemoryPhi>(DefBefore) &&
309 std::find(InsertedPHIs.begin(), InsertedPHIs.end(), DefBefore) !=
310 InsertedPHIs.end()))
311 DefBeforeSameBlock = true;
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000312
313 // There is a def before us, which means we can replace any store/phi uses
314 // of that thing with us, since we are in the way of whatever was there
315 // before.
316 // We now define that def's memorydefs and memoryphis
Daniel Berlin9d8a3352017-01-30 11:35:39 +0000317 if (DefBeforeSameBlock) {
Roman Lebedev081e9902019-08-01 12:32:08 +0000318 DefBefore->replaceUsesWithIf(MD, [MD](Use &U) {
Alexandros Lamprineas96762b32018-09-11 14:29:59 +0000319 // Leave the MemoryUses alone.
320 // Also make sure we skip ourselves to avoid self references.
Roman Lebedev081e9902019-08-01 12:32:08 +0000321 User *Usr = U.getUser();
322 return !isa<MemoryUse>(Usr) && Usr != MD;
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000323 // Defs are automatically unoptimized when the user is set to MD below,
324 // because the isOptimized() call will fail to find the same ID.
Roman Lebedev081e9902019-08-01 12:32:08 +0000325 });
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000326 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +0000327
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000328 // and that def is now our defining access.
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000329 MD->setDefiningAccess(DefBefore);
330
Alexandros Lamprineasf854ce82018-07-16 07:51:27 +0000331 SmallVector<WeakVH, 8> FixupList(InsertedPHIs.begin(), InsertedPHIs.end());
Alina Sbirlea2c5e6642019-09-23 23:50:16 +0000332
Alina Sbirlea6720ed82019-09-25 23:24:39 +0000333 // Remember the index where we may insert new phis.
334 unsigned NewPhiIndex = InsertedPHIs.size();
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000335 if (!DefBeforeSameBlock) {
336 // If there was a local def before us, we must have the same effect it
337 // did. Because every may-def is the same, any phis/etc we would create, it
338 // would also have created. If there was no local def before us, we
339 // performed a global update, and have to search all successors and make
340 // sure we update the first def in each of them (following all paths until
341 // we hit the first def along each path). This may also insert phi nodes.
342 // TODO: There are other cases we can skip this work, such as when we have a
343 // single successor, and only used a straight line of single pred blocks
344 // backwards to find the def. To make that work, we'd have to track whether
345 // getDefRecursive only ever used the single predecessor case. These types
346 // of paths also only exist in between CFG simplifications.
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000347
348 // If this is the first def in the block and this insert is in an arbitrary
349 // place, compute IDF and place phis.
Alina Sbirlea24ae5ce2019-10-02 18:42:33 +0000350 SmallPtrSet<BasicBlock *, 2> DefiningBlocks;
351
352 // If this is the last Def in the block, also compute IDF based on MD, since
353 // this may a new Def added, and we may need additional Phis.
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000354 auto Iter = MD->getDefsIterator();
355 ++Iter;
356 auto IterEnd = MSSA->getBlockDefs(MD->getBlock())->end();
Alina Sbirlea24ae5ce2019-10-02 18:42:33 +0000357 if (Iter == IterEnd)
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000358 DefiningBlocks.insert(MD->getBlock());
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000359
Alina Sbirlea24ae5ce2019-10-02 18:42:33 +0000360 for (const auto &VH : InsertedPHIs)
361 if (const auto *RealPHI = cast_or_null<MemoryPhi>(VH))
362 DefiningBlocks.insert(RealPHI->getBlock());
363 ForwardIDFCalculator IDFs(*MSSA->DT);
364 SmallVector<BasicBlock *, 32> IDFBlocks;
365 IDFs.setDefiningBlocks(DefiningBlocks);
366 IDFs.calculate(IDFBlocks);
367 SmallVector<AssertingVH<MemoryPhi>, 4> NewInsertedPHIs;
368 for (auto *BBIDF : IDFBlocks) {
369 auto *MPhi = MSSA->getMemoryAccess(BBIDF);
370 if (!MPhi) {
371 MPhi = MSSA->createMemoryPhi(BBIDF);
372 NewInsertedPHIs.push_back(MPhi);
373 }
374 // Add the phis created into the IDF blocks to NonOptPhis, so they are not
375 // optimized out as trivial by the call to getPreviousDefFromEnd below.
376 // Once they are complete, all these Phis are added to the FixupList, and
377 // removed from NonOptPhis inside fixupDefs(). Existing Phis in IDF may
378 // need fixing as well, and potentially be trivial before this insertion,
379 // hence add all IDF Phis. See PR43044.
380 NonOptPhis.insert(MPhi);
381 }
382 for (auto &MPhi : NewInsertedPHIs) {
383 auto *BBIDF = MPhi->getBlock();
384 for (auto *Pred : predecessors(BBIDF)) {
385 DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> CachedPreviousDef;
386 MPhi->addIncoming(getPreviousDefFromEnd(Pred, CachedPreviousDef), Pred);
Alina Sbirlea6720ed82019-09-25 23:24:39 +0000387 }
388 }
Alina Sbirlea24ae5ce2019-10-02 18:42:33 +0000389
390 // Re-take the index where we're adding the new phis, because the above call
391 // to getPreviousDefFromEnd, may have inserted into InsertedPHIs.
392 NewPhiIndex = InsertedPHIs.size();
393 for (auto &MPhi : NewInsertedPHIs) {
394 InsertedPHIs.push_back(&*MPhi);
395 FixupList.push_back(&*MPhi);
396 }
397
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000398 FixupList.push_back(MD);
399 }
400
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000401 // Remember the index where we stopped inserting new phis above, since the
402 // fixupDefs call in the loop below may insert more, that are already minimal.
403 unsigned NewPhiIndexEnd = InsertedPHIs.size();
404
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000405 while (!FixupList.empty()) {
406 unsigned StartingPHISize = InsertedPHIs.size();
407 fixupDefs(FixupList);
408 FixupList.clear();
409 // Put any new phis on the fixup list, and process them
Alexandros Lamprineasf854ce82018-07-16 07:51:27 +0000410 FixupList.append(InsertedPHIs.begin() + StartingPHISize, InsertedPHIs.end());
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000411 }
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000412
413 // Optimize potentially non-minimal phis added in this method.
Alina Sbirlea151ab482019-05-02 23:12:49 +0000414 unsigned NewPhiSize = NewPhiIndexEnd - NewPhiIndex;
415 if (NewPhiSize)
416 tryRemoveTrivialPhis(ArrayRef<WeakVH>(&InsertedPHIs[NewPhiIndex], NewPhiSize));
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000417
Daniel Berlin78cbd282017-02-20 22:26:03 +0000418 // Now that all fixups are done, rename all uses if we are asked.
419 if (RenameUses) {
420 SmallPtrSet<BasicBlock *, 16> Visited;
421 BasicBlock *StartBlock = MD->getBlock();
422 // We are guaranteed there is a def in the block, because we just got it
423 // handed to us in this function.
424 MemoryAccess *FirstDef = &*MSSA->getWritableBlockDefs(StartBlock)->begin();
425 // Convert to incoming value if it's a memorydef. A phi *is* already an
426 // incoming value.
427 if (auto *MD = dyn_cast<MemoryDef>(FirstDef))
428 FirstDef = MD->getDefiningAccess();
429
430 MSSA->renamePass(MD->getBlock(), FirstDef, Visited);
431 // We just inserted a phi into this block, so the incoming value will become
432 // the phi anyway, so it does not matter what we pass.
Alexandros Lamprineasf854ce82018-07-16 07:51:27 +0000433 for (auto &MP : InsertedPHIs) {
434 MemoryPhi *Phi = dyn_cast_or_null<MemoryPhi>(MP);
435 if (Phi)
436 MSSA->renamePass(Phi->getBlock(), nullptr, Visited);
437 }
Daniel Berlin78cbd282017-02-20 22:26:03 +0000438 }
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000439}
440
Alexandros Lamprineasf854ce82018-07-16 07:51:27 +0000441void MemorySSAUpdater::fixupDefs(const SmallVectorImpl<WeakVH> &Vars) {
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000442 SmallPtrSet<const BasicBlock *, 8> Seen;
443 SmallVector<const BasicBlock *, 16> Worklist;
Alexandros Lamprineasf854ce82018-07-16 07:51:27 +0000444 for (auto &Var : Vars) {
445 MemoryAccess *NewDef = dyn_cast_or_null<MemoryAccess>(Var);
446 if (!NewDef)
447 continue;
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000448 // First, see if there is a local def after the operand.
449 auto *Defs = MSSA->getWritableBlockDefs(NewDef->getBlock());
450 auto DefIter = NewDef->getDefsIterator();
451
Zhaoshi Zheng43af17b2018-04-09 20:55:37 +0000452 // The temporary Phi is being fixed, unmark it for not to optimize.
George Burgess IVe7cdb7e2018-07-12 21:56:31 +0000453 if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(NewDef))
Zhaoshi Zheng43af17b2018-04-09 20:55:37 +0000454 NonOptPhis.erase(Phi);
455
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000456 // If there is a local def after us, we only have to rename that.
457 if (++DefIter != Defs->end()) {
458 cast<MemoryDef>(DefIter)->setDefiningAccess(NewDef);
459 continue;
460 }
461
462 // Otherwise, we need to search down through the CFG.
463 // For each of our successors, handle it directly if their is a phi, or
464 // place on the fixup worklist.
465 for (const auto *S : successors(NewDef->getBlock())) {
466 if (auto *MP = MSSA->getMemoryAccess(S))
467 setMemoryPhiValueForBlock(MP, NewDef->getBlock(), NewDef);
468 else
469 Worklist.push_back(S);
470 }
471
472 while (!Worklist.empty()) {
473 const BasicBlock *FixupBlock = Worklist.back();
474 Worklist.pop_back();
475
476 // Get the first def in the block that isn't a phi node.
477 if (auto *Defs = MSSA->getWritableBlockDefs(FixupBlock)) {
478 auto *FirstDef = &*Defs->begin();
479 // The loop above and below should have taken care of phi nodes
480 assert(!isa<MemoryPhi>(FirstDef) &&
481 "Should have already handled phi nodes!");
482 // We are now this def's defining access, make sure we actually dominate
483 // it
484 assert(MSSA->dominates(NewDef, FirstDef) &&
485 "Should have dominated the new access");
486
487 // This may insert new phi nodes, because we are not guaranteed the
488 // block we are processing has a single pred, and depending where the
489 // store was inserted, it may require phi nodes below it.
490 cast<MemoryDef>(FirstDef)->setDefiningAccess(getPreviousDef(FirstDef));
491 return;
492 }
493 // We didn't find a def, so we must continue.
494 for (const auto *S : successors(FixupBlock)) {
495 // If there is a phi node, handle it.
496 // Otherwise, put the block on the worklist
497 if (auto *MP = MSSA->getMemoryAccess(S))
498 setMemoryPhiValueForBlock(MP, FixupBlock, NewDef);
499 else {
500 // If we cycle, we should have ended up at a phi node that we already
501 // processed. FIXME: Double check this
502 if (!Seen.insert(S).second)
503 continue;
504 Worklist.push_back(S);
505 }
506 }
507 }
508 }
509}
510
Alina Sbirlea79800992018-09-10 20:13:01 +0000511void MemorySSAUpdater::removeEdge(BasicBlock *From, BasicBlock *To) {
512 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(To)) {
513 MPhi->unorderedDeleteIncomingBlock(From);
Alina Sbirlea28637212019-08-20 22:47:58 +0000514 tryRemoveTrivialPhi(MPhi);
Alina Sbirlea79800992018-09-10 20:13:01 +0000515 }
516}
517
Alina Sbirleaf31eba62019-05-08 17:05:36 +0000518void MemorySSAUpdater::removeDuplicatePhiEdgesBetween(const BasicBlock *From,
519 const BasicBlock *To) {
Alina Sbirlea79800992018-09-10 20:13:01 +0000520 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(To)) {
521 bool Found = false;
522 MPhi->unorderedDeleteIncomingIf([&](const MemoryAccess *, BasicBlock *B) {
523 if (From != B)
524 return false;
525 if (Found)
526 return true;
527 Found = true;
528 return false;
529 });
Alina Sbirlea28637212019-08-20 22:47:58 +0000530 tryRemoveTrivialPhi(MPhi);
Alina Sbirlea79800992018-09-10 20:13:01 +0000531 }
532}
533
Alina Sbirlea4bc625c2019-07-30 20:10:33 +0000534static MemoryAccess *getNewDefiningAccessForClone(MemoryAccess *MA,
535 const ValueToValueMapTy &VMap,
536 PhiToDefMap &MPhiMap,
537 bool CloneWasSimplified,
538 MemorySSA *MSSA) {
539 MemoryAccess *InsnDefining = MA;
540 if (MemoryDef *DefMUD = dyn_cast<MemoryDef>(InsnDefining)) {
541 if (!MSSA->isLiveOnEntryDef(DefMUD)) {
542 Instruction *DefMUDI = DefMUD->getMemoryInst();
543 assert(DefMUDI && "Found MemoryUseOrDef with no Instruction.");
544 if (Instruction *NewDefMUDI =
545 cast_or_null<Instruction>(VMap.lookup(DefMUDI))) {
546 InsnDefining = MSSA->getMemoryAccess(NewDefMUDI);
547 if (!CloneWasSimplified)
548 assert(InsnDefining && "Defining instruction cannot be nullptr.");
549 else if (!InsnDefining || isa<MemoryUse>(InsnDefining)) {
550 // The clone was simplified, it's no longer a MemoryDef, look up.
551 auto DefIt = DefMUD->getDefsIterator();
552 // Since simplified clones only occur in single block cloning, a
553 // previous definition must exist, otherwise NewDefMUDI would not
554 // have been found in VMap.
555 assert(DefIt != MSSA->getBlockDefs(DefMUD->getBlock())->begin() &&
556 "Previous def must exist");
557 InsnDefining = getNewDefiningAccessForClone(
558 &*(--DefIt), VMap, MPhiMap, CloneWasSimplified, MSSA);
559 }
560 }
561 }
562 } else {
563 MemoryPhi *DefPhi = cast<MemoryPhi>(InsnDefining);
564 if (MemoryAccess *NewDefPhi = MPhiMap.lookup(DefPhi))
565 InsnDefining = NewDefPhi;
566 }
567 assert(InsnDefining && "Defining instruction cannot be nullptr.");
568 return InsnDefining;
569}
570
Alina Sbirlea79800992018-09-10 20:13:01 +0000571void MemorySSAUpdater::cloneUsesAndDefs(BasicBlock *BB, BasicBlock *NewBB,
572 const ValueToValueMapTy &VMap,
Alina Sbirlea7a0098a2019-06-17 18:58:40 +0000573 PhiToDefMap &MPhiMap,
574 bool CloneWasSimplified) {
Alina Sbirlea79800992018-09-10 20:13:01 +0000575 const MemorySSA::AccessList *Acc = MSSA->getBlockAccesses(BB);
576 if (!Acc)
577 return;
578 for (const MemoryAccess &MA : *Acc) {
579 if (const MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&MA)) {
580 Instruction *Insn = MUD->getMemoryInst();
581 // Entry does not exist if the clone of the block did not clone all
582 // instructions. This occurs in LoopRotate when cloning instructions
583 // from the old header to the old preheader. The cloned instruction may
584 // also be a simplified Value, not an Instruction (see LoopRotate).
Alina Sbirlea7a0098a2019-06-17 18:58:40 +0000585 // Also in LoopRotate, even when it's an instruction, due to it being
586 // simplified, it may be a Use rather than a Def, so we cannot use MUD as
587 // template. Calls coming from updateForClonedBlockIntoPred, ensure this.
Alina Sbirlea79800992018-09-10 20:13:01 +0000588 if (Instruction *NewInsn =
589 dyn_cast_or_null<Instruction>(VMap.lookup(Insn))) {
590 MemoryAccess *NewUseOrDef = MSSA->createDefinedAccess(
Alina Sbirlea4bc625c2019-07-30 20:10:33 +0000591 NewInsn,
592 getNewDefiningAccessForClone(MUD->getDefiningAccess(), VMap,
593 MPhiMap, CloneWasSimplified, MSSA),
594 /*Template=*/CloneWasSimplified ? nullptr : MUD,
595 /*CreationMustSucceed=*/CloneWasSimplified ? false : true);
596 if (NewUseOrDef)
597 MSSA->insertIntoListsForBlock(NewUseOrDef, NewBB, MemorySSA::End);
Alina Sbirlea79800992018-09-10 20:13:01 +0000598 }
599 }
600 }
601}
602
Alina Sbirleaf31eba62019-05-08 17:05:36 +0000603void MemorySSAUpdater::updatePhisWhenInsertingUniqueBackedgeBlock(
604 BasicBlock *Header, BasicBlock *Preheader, BasicBlock *BEBlock) {
605 auto *MPhi = MSSA->getMemoryAccess(Header);
606 if (!MPhi)
607 return;
608
609 // Create phi node in the backedge block and populate it with the same
610 // incoming values as MPhi. Skip incoming values coming from Preheader.
611 auto *NewMPhi = MSSA->createMemoryPhi(BEBlock);
612 bool HasUniqueIncomingValue = true;
613 MemoryAccess *UniqueValue = nullptr;
614 for (unsigned I = 0, E = MPhi->getNumIncomingValues(); I != E; ++I) {
615 BasicBlock *IBB = MPhi->getIncomingBlock(I);
616 MemoryAccess *IV = MPhi->getIncomingValue(I);
617 if (IBB != Preheader) {
618 NewMPhi->addIncoming(IV, IBB);
619 if (HasUniqueIncomingValue) {
620 if (!UniqueValue)
621 UniqueValue = IV;
622 else if (UniqueValue != IV)
623 HasUniqueIncomingValue = false;
624 }
625 }
626 }
627
628 // Update incoming edges into MPhi. Remove all but the incoming edge from
629 // Preheader. Add an edge from NewMPhi
630 auto *AccFromPreheader = MPhi->getIncomingValueForBlock(Preheader);
631 MPhi->setIncomingValue(0, AccFromPreheader);
632 MPhi->setIncomingBlock(0, Preheader);
633 for (unsigned I = MPhi->getNumIncomingValues() - 1; I >= 1; --I)
634 MPhi->unorderedDeleteIncoming(I);
635 MPhi->addIncoming(NewMPhi, BEBlock);
636
637 // If NewMPhi is a trivial phi, remove it. Its use in the header MPhi will be
638 // replaced with the unique value.
Alina Sbirleaae40dfc2019-10-01 18:34:39 +0000639 tryRemoveTrivialPhi(NewMPhi);
Alina Sbirleaf31eba62019-05-08 17:05:36 +0000640}
641
Alina Sbirlea79800992018-09-10 20:13:01 +0000642void MemorySSAUpdater::updateForClonedLoop(const LoopBlocksRPO &LoopBlocks,
643 ArrayRef<BasicBlock *> ExitBlocks,
644 const ValueToValueMapTy &VMap,
645 bool IgnoreIncomingWithNoClones) {
646 PhiToDefMap MPhiMap;
647
648 auto FixPhiIncomingValues = [&](MemoryPhi *Phi, MemoryPhi *NewPhi) {
649 assert(Phi && NewPhi && "Invalid Phi nodes.");
650 BasicBlock *NewPhiBB = NewPhi->getBlock();
651 SmallPtrSet<BasicBlock *, 4> NewPhiBBPreds(pred_begin(NewPhiBB),
652 pred_end(NewPhiBB));
653 for (unsigned It = 0, E = Phi->getNumIncomingValues(); It < E; ++It) {
654 MemoryAccess *IncomingAccess = Phi->getIncomingValue(It);
655 BasicBlock *IncBB = Phi->getIncomingBlock(It);
656
657 if (BasicBlock *NewIncBB = cast_or_null<BasicBlock>(VMap.lookup(IncBB)))
658 IncBB = NewIncBB;
659 else if (IgnoreIncomingWithNoClones)
660 continue;
661
662 // Now we have IncBB, and will need to add incoming from it to NewPhi.
663
664 // If IncBB is not a predecessor of NewPhiBB, then do not add it.
665 // NewPhiBB was cloned without that edge.
666 if (!NewPhiBBPreds.count(IncBB))
667 continue;
668
669 // Determine incoming value and add it as incoming from IncBB.
670 if (MemoryUseOrDef *IncMUD = dyn_cast<MemoryUseOrDef>(IncomingAccess)) {
671 if (!MSSA->isLiveOnEntryDef(IncMUD)) {
672 Instruction *IncI = IncMUD->getMemoryInst();
673 assert(IncI && "Found MemoryUseOrDef with no Instruction.");
674 if (Instruction *NewIncI =
675 cast_or_null<Instruction>(VMap.lookup(IncI))) {
676 IncMUD = MSSA->getMemoryAccess(NewIncI);
677 assert(IncMUD &&
678 "MemoryUseOrDef cannot be null, all preds processed.");
679 }
680 }
681 NewPhi->addIncoming(IncMUD, IncBB);
682 } else {
683 MemoryPhi *IncPhi = cast<MemoryPhi>(IncomingAccess);
684 if (MemoryAccess *NewDefPhi = MPhiMap.lookup(IncPhi))
685 NewPhi->addIncoming(NewDefPhi, IncBB);
686 else
687 NewPhi->addIncoming(IncPhi, IncBB);
688 }
689 }
690 };
691
692 auto ProcessBlock = [&](BasicBlock *BB) {
693 BasicBlock *NewBlock = cast_or_null<BasicBlock>(VMap.lookup(BB));
694 if (!NewBlock)
695 return;
696
697 assert(!MSSA->getWritableBlockAccesses(NewBlock) &&
698 "Cloned block should have no accesses");
699
700 // Add MemoryPhi.
701 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(BB)) {
702 MemoryPhi *NewPhi = MSSA->createMemoryPhi(NewBlock);
703 MPhiMap[MPhi] = NewPhi;
704 }
705 // Update Uses and Defs.
706 cloneUsesAndDefs(BB, NewBlock, VMap, MPhiMap);
707 };
708
709 for (auto BB : llvm::concat<BasicBlock *const>(LoopBlocks, ExitBlocks))
710 ProcessBlock(BB);
711
712 for (auto BB : llvm::concat<BasicBlock *const>(LoopBlocks, ExitBlocks))
713 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(BB))
714 if (MemoryAccess *NewPhi = MPhiMap.lookup(MPhi))
715 FixPhiIncomingValues(MPhi, cast<MemoryPhi>(NewPhi));
716}
717
718void MemorySSAUpdater::updateForClonedBlockIntoPred(
719 BasicBlock *BB, BasicBlock *P1, const ValueToValueMapTy &VM) {
720 // All defs/phis from outside BB that are used in BB, are valid uses in P1.
721 // Since those defs/phis must have dominated BB, and also dominate P1.
722 // Defs from BB being used in BB will be replaced with the cloned defs from
723 // VM. The uses of BB's Phi (if it exists) in BB will be replaced by the
724 // incoming def into the Phi from P1.
Alina Sbirlea7a0098a2019-06-17 18:58:40 +0000725 // Instructions cloned into the predecessor are in practice sometimes
726 // simplified, so disable the use of the template, and create an access from
727 // scratch.
Alina Sbirlea79800992018-09-10 20:13:01 +0000728 PhiToDefMap MPhiMap;
729 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(BB))
730 MPhiMap[MPhi] = MPhi->getIncomingValueForBlock(P1);
Alina Sbirlea7a0098a2019-06-17 18:58:40 +0000731 cloneUsesAndDefs(BB, P1, VM, MPhiMap, /*CloneWasSimplified=*/true);
Alina Sbirlea79800992018-09-10 20:13:01 +0000732}
733
734template <typename Iter>
735void MemorySSAUpdater::privateUpdateExitBlocksForClonedLoop(
736 ArrayRef<BasicBlock *> ExitBlocks, Iter ValuesBegin, Iter ValuesEnd,
737 DominatorTree &DT) {
738 SmallVector<CFGUpdate, 4> Updates;
739 // Update/insert phis in all successors of exit blocks.
740 for (auto *Exit : ExitBlocks)
741 for (const ValueToValueMapTy *VMap : make_range(ValuesBegin, ValuesEnd))
742 if (BasicBlock *NewExit = cast_or_null<BasicBlock>(VMap->lookup(Exit))) {
743 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
744 Updates.push_back({DT.Insert, NewExit, ExitSucc});
745 }
746 applyInsertUpdates(Updates, DT);
747}
748
749void MemorySSAUpdater::updateExitBlocksForClonedLoop(
750 ArrayRef<BasicBlock *> ExitBlocks, const ValueToValueMapTy &VMap,
751 DominatorTree &DT) {
752 const ValueToValueMapTy *const Arr[] = {&VMap};
753 privateUpdateExitBlocksForClonedLoop(ExitBlocks, std::begin(Arr),
754 std::end(Arr), DT);
755}
756
757void MemorySSAUpdater::updateExitBlocksForClonedLoop(
758 ArrayRef<BasicBlock *> ExitBlocks,
759 ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps, DominatorTree &DT) {
760 auto GetPtr = [&](const std::unique_ptr<ValueToValueMapTy> &I) {
761 return I.get();
762 };
763 using MappedIteratorType =
764 mapped_iterator<const std::unique_ptr<ValueToValueMapTy> *,
765 decltype(GetPtr)>;
766 auto MapBegin = MappedIteratorType(VMaps.begin(), GetPtr);
767 auto MapEnd = MappedIteratorType(VMaps.end(), GetPtr);
768 privateUpdateExitBlocksForClonedLoop(ExitBlocks, MapBegin, MapEnd, DT);
769}
770
771void MemorySSAUpdater::applyUpdates(ArrayRef<CFGUpdate> Updates,
772 DominatorTree &DT) {
773 SmallVector<CFGUpdate, 4> RevDeleteUpdates;
774 SmallVector<CFGUpdate, 4> InsertUpdates;
775 for (auto &Update : Updates) {
776 if (Update.getKind() == DT.Insert)
777 InsertUpdates.push_back({DT.Insert, Update.getFrom(), Update.getTo()});
778 else
779 RevDeleteUpdates.push_back({DT.Insert, Update.getFrom(), Update.getTo()});
780 }
781
782 if (!RevDeleteUpdates.empty()) {
783 // Update for inserted edges: use newDT and snapshot CFG as if deletes had
Hiroshi Inoue02a2bb22019-02-05 08:30:48 +0000784 // not occurred.
Alina Sbirlea79800992018-09-10 20:13:01 +0000785 // FIXME: This creates a new DT, so it's more expensive to do mix
786 // delete/inserts vs just inserts. We can do an incremental update on the DT
787 // to revert deletes, than re-delete the edges. Teaching DT to do this, is
788 // part of a pending cleanup.
789 DominatorTree NewDT(DT, RevDeleteUpdates);
790 GraphDiff<BasicBlock *> GD(RevDeleteUpdates);
791 applyInsertUpdates(InsertUpdates, NewDT, &GD);
792 } else {
793 GraphDiff<BasicBlock *> GD;
794 applyInsertUpdates(InsertUpdates, DT, &GD);
795 }
796
797 // Update for deleted edges
798 for (auto &Update : RevDeleteUpdates)
799 removeEdge(Update.getFrom(), Update.getTo());
800}
801
802void MemorySSAUpdater::applyInsertUpdates(ArrayRef<CFGUpdate> Updates,
803 DominatorTree &DT) {
804 GraphDiff<BasicBlock *> GD;
805 applyInsertUpdates(Updates, DT, &GD);
806}
807
808void MemorySSAUpdater::applyInsertUpdates(ArrayRef<CFGUpdate> Updates,
809 DominatorTree &DT,
810 const GraphDiff<BasicBlock *> *GD) {
811 // Get recursive last Def, assuming well formed MSSA and updated DT.
812 auto GetLastDef = [&](BasicBlock *BB) -> MemoryAccess * {
813 while (true) {
814 MemorySSA::DefsList *Defs = MSSA->getWritableBlockDefs(BB);
815 // Return last Def or Phi in BB, if it exists.
816 if (Defs)
817 return &*(--Defs->end());
818
819 // Check number of predecessors, we only care if there's more than one.
820 unsigned Count = 0;
821 BasicBlock *Pred = nullptr;
822 for (auto &Pair : children<GraphDiffInvBBPair>({GD, BB})) {
823 Pred = Pair.second;
824 Count++;
825 if (Count == 2)
826 break;
827 }
828
829 // If BB has multiple predecessors, get last definition from IDom.
830 if (Count != 1) {
831 // [SimpleLoopUnswitch] If BB is a dead block, about to be deleted, its
832 // DT is invalidated. Return LoE as its last def. This will be added to
833 // MemoryPhi node, and later deleted when the block is deleted.
834 if (!DT.getNode(BB))
835 return MSSA->getLiveOnEntryDef();
836 if (auto *IDom = DT.getNode(BB)->getIDom())
837 if (IDom->getBlock() != BB) {
838 BB = IDom->getBlock();
839 continue;
840 }
841 return MSSA->getLiveOnEntryDef();
842 } else {
843 // Single predecessor, BB cannot be dead. GetLastDef of Pred.
844 assert(Count == 1 && Pred && "Single predecessor expected.");
Alina Sbirlea890090f2019-10-01 19:09:50 +0000845 // BB can be unreachable though, return LoE if that is the case.
846 if (!DT.getNode(BB))
847 return MSSA->getLiveOnEntryDef();
Alina Sbirlea79800992018-09-10 20:13:01 +0000848 BB = Pred;
849 }
850 };
851 llvm_unreachable("Unable to get last definition.");
852 };
853
854 // Get nearest IDom given a set of blocks.
855 // TODO: this can be optimized by starting the search at the node with the
856 // lowest level (highest in the tree).
857 auto FindNearestCommonDominator =
858 [&](const SmallSetVector<BasicBlock *, 2> &BBSet) -> BasicBlock * {
859 BasicBlock *PrevIDom = *BBSet.begin();
860 for (auto *BB : BBSet)
861 PrevIDom = DT.findNearestCommonDominator(PrevIDom, BB);
862 return PrevIDom;
863 };
864
865 // Get all blocks that dominate PrevIDom, stop when reaching CurrIDom. Do not
866 // include CurrIDom.
867 auto GetNoLongerDomBlocks =
868 [&](BasicBlock *PrevIDom, BasicBlock *CurrIDom,
869 SmallVectorImpl<BasicBlock *> &BlocksPrevDom) {
870 if (PrevIDom == CurrIDom)
871 return;
872 BlocksPrevDom.push_back(PrevIDom);
873 BasicBlock *NextIDom = PrevIDom;
874 while (BasicBlock *UpIDom =
875 DT.getNode(NextIDom)->getIDom()->getBlock()) {
876 if (UpIDom == CurrIDom)
877 break;
878 BlocksPrevDom.push_back(UpIDom);
879 NextIDom = UpIDom;
880 }
881 };
882
883 // Map a BB to its predecessors: added + previously existing. To get a
884 // deterministic order, store predecessors as SetVectors. The order in each
Hiroshi Inoue02a2bb22019-02-05 08:30:48 +0000885 // will be defined by the order in Updates (fixed) and the order given by
Alina Sbirlea79800992018-09-10 20:13:01 +0000886 // children<> (also fixed). Since we further iterate over these ordered sets,
887 // we lose the information of multiple edges possibly existing between two
888 // blocks, so we'll keep and EdgeCount map for that.
889 // An alternate implementation could keep unordered set for the predecessors,
890 // traverse either Updates or children<> each time to get the deterministic
891 // order, and drop the usage of EdgeCount. This alternate approach would still
892 // require querying the maps for each predecessor, and children<> call has
893 // additional computation inside for creating the snapshot-graph predecessors.
894 // As such, we favor using a little additional storage and less compute time.
895 // This decision can be revisited if we find the alternative more favorable.
896
897 struct PredInfo {
898 SmallSetVector<BasicBlock *, 2> Added;
899 SmallSetVector<BasicBlock *, 2> Prev;
900 };
901 SmallDenseMap<BasicBlock *, PredInfo> PredMap;
902
903 for (auto &Edge : Updates) {
904 BasicBlock *BB = Edge.getTo();
905 auto &AddedBlockSet = PredMap[BB].Added;
906 AddedBlockSet.insert(Edge.getFrom());
907 }
908
909 // Store all existing predecessor for each BB, at least one must exist.
910 SmallDenseMap<std::pair<BasicBlock *, BasicBlock *>, int> EdgeCountMap;
911 SmallPtrSet<BasicBlock *, 2> NewBlocks;
912 for (auto &BBPredPair : PredMap) {
913 auto *BB = BBPredPair.first;
914 const auto &AddedBlockSet = BBPredPair.second.Added;
915 auto &PrevBlockSet = BBPredPair.second.Prev;
916 for (auto &Pair : children<GraphDiffInvBBPair>({GD, BB})) {
917 BasicBlock *Pi = Pair.second;
918 if (!AddedBlockSet.count(Pi))
919 PrevBlockSet.insert(Pi);
920 EdgeCountMap[{Pi, BB}]++;
921 }
922
923 if (PrevBlockSet.empty()) {
924 assert(pred_size(BB) == AddedBlockSet.size() && "Duplicate edges added.");
925 LLVM_DEBUG(
926 dbgs()
927 << "Adding a predecessor to a block with no predecessors. "
928 "This must be an edge added to a new, likely cloned, block. "
929 "Its memory accesses must be already correct, assuming completed "
930 "via the updateExitBlocksForClonedLoop API. "
931 "Assert a single such edge is added so no phi addition or "
932 "additional processing is required.\n");
933 assert(AddedBlockSet.size() == 1 &&
934 "Can only handle adding one predecessor to a new block.");
935 // Need to remove new blocks from PredMap. Remove below to not invalidate
936 // iterator here.
937 NewBlocks.insert(BB);
938 }
939 }
940 // Nothing to process for new/cloned blocks.
941 for (auto *BB : NewBlocks)
942 PredMap.erase(BB);
943
Alina Sbirlea79800992018-09-10 20:13:01 +0000944 SmallVector<BasicBlock *, 16> BlocksWithDefsToReplace;
Alina Sbirleacb4ed8a2019-06-11 19:09:34 +0000945 SmallVector<WeakVH, 8> InsertedPhis;
Alina Sbirlea79800992018-09-10 20:13:01 +0000946
947 // First create MemoryPhis in all blocks that don't have one. Create in the
948 // order found in Updates, not in PredMap, to get deterministic numbering.
949 for (auto &Edge : Updates) {
950 BasicBlock *BB = Edge.getTo();
951 if (PredMap.count(BB) && !MSSA->getMemoryAccess(BB))
Alina Sbirleacb4ed8a2019-06-11 19:09:34 +0000952 InsertedPhis.push_back(MSSA->createMemoryPhi(BB));
Alina Sbirlea79800992018-09-10 20:13:01 +0000953 }
954
955 // Now we'll fill in the MemoryPhis with the right incoming values.
956 for (auto &BBPredPair : PredMap) {
957 auto *BB = BBPredPair.first;
958 const auto &PrevBlockSet = BBPredPair.second.Prev;
959 const auto &AddedBlockSet = BBPredPair.second.Added;
960 assert(!PrevBlockSet.empty() &&
961 "At least one previous predecessor must exist.");
962
963 // TODO: if this becomes a bottleneck, we can save on GetLastDef calls by
964 // keeping this map before the loop. We can reuse already populated entries
965 // if an edge is added from the same predecessor to two different blocks,
966 // and this does happen in rotate. Note that the map needs to be updated
967 // when deleting non-necessary phis below, if the phi is in the map by
968 // replacing the value with DefP1.
969 SmallDenseMap<BasicBlock *, MemoryAccess *> LastDefAddedPred;
970 for (auto *AddedPred : AddedBlockSet) {
971 auto *DefPn = GetLastDef(AddedPred);
972 assert(DefPn != nullptr && "Unable to find last definition.");
973 LastDefAddedPred[AddedPred] = DefPn;
974 }
975
976 MemoryPhi *NewPhi = MSSA->getMemoryAccess(BB);
977 // If Phi is not empty, add an incoming edge from each added pred. Must
978 // still compute blocks with defs to replace for this block below.
979 if (NewPhi->getNumOperands()) {
980 for (auto *Pred : AddedBlockSet) {
981 auto *LastDefForPred = LastDefAddedPred[Pred];
982 for (int I = 0, E = EdgeCountMap[{Pred, BB}]; I < E; ++I)
983 NewPhi->addIncoming(LastDefForPred, Pred);
984 }
985 } else {
986 // Pick any existing predecessor and get its definition. All other
987 // existing predecessors should have the same one, since no phi existed.
988 auto *P1 = *PrevBlockSet.begin();
989 MemoryAccess *DefP1 = GetLastDef(P1);
990
991 // Check DefP1 against all Defs in LastDefPredPair. If all the same,
992 // nothing to add.
993 bool InsertPhi = false;
994 for (auto LastDefPredPair : LastDefAddedPred)
995 if (DefP1 != LastDefPredPair.second) {
996 InsertPhi = true;
997 break;
998 }
999 if (!InsertPhi) {
1000 // Since NewPhi may be used in other newly added Phis, replace all uses
1001 // of NewPhi with the definition coming from all predecessors (DefP1),
1002 // before deleting it.
1003 NewPhi->replaceAllUsesWith(DefP1);
1004 removeMemoryAccess(NewPhi);
1005 continue;
1006 }
1007
1008 // Update Phi with new values for new predecessors and old value for all
1009 // other predecessors. Since AddedBlockSet and PrevBlockSet are ordered
1010 // sets, the order of entries in NewPhi is deterministic.
1011 for (auto *Pred : AddedBlockSet) {
1012 auto *LastDefForPred = LastDefAddedPred[Pred];
1013 for (int I = 0, E = EdgeCountMap[{Pred, BB}]; I < E; ++I)
1014 NewPhi->addIncoming(LastDefForPred, Pred);
1015 }
1016 for (auto *Pred : PrevBlockSet)
1017 for (int I = 0, E = EdgeCountMap[{Pred, BB}]; I < E; ++I)
1018 NewPhi->addIncoming(DefP1, Pred);
Alina Sbirlea79800992018-09-10 20:13:01 +00001019 }
1020
1021 // Get all blocks that used to dominate BB and no longer do after adding
1022 // AddedBlockSet, where PrevBlockSet are the previously known predecessors.
1023 assert(DT.getNode(BB)->getIDom() && "BB does not have valid idom");
1024 BasicBlock *PrevIDom = FindNearestCommonDominator(PrevBlockSet);
1025 assert(PrevIDom && "Previous IDom should exists");
1026 BasicBlock *NewIDom = DT.getNode(BB)->getIDom()->getBlock();
1027 assert(NewIDom && "BB should have a new valid idom");
1028 assert(DT.dominates(NewIDom, PrevIDom) &&
1029 "New idom should dominate old idom");
1030 GetNoLongerDomBlocks(PrevIDom, NewIDom, BlocksWithDefsToReplace);
1031 }
1032
Alina Sbirlea109d2ea2019-06-19 21:33:09 +00001033 tryRemoveTrivialPhis(InsertedPhis);
1034 // Create the set of blocks that now have a definition. We'll use this to
1035 // compute IDF and add Phis there next.
1036 SmallVector<BasicBlock *, 8> BlocksToProcess;
1037 for (auto &VH : InsertedPhis)
1038 if (auto *MPhi = cast_or_null<MemoryPhi>(VH))
1039 BlocksToProcess.push_back(MPhi->getBlock());
1040
Alina Sbirlea79800992018-09-10 20:13:01 +00001041 // Compute IDF and add Phis in all IDF blocks that do not have one.
1042 SmallVector<BasicBlock *, 32> IDFBlocks;
1043 if (!BlocksToProcess.empty()) {
Alina Sbirlea238b8e62019-06-19 21:17:31 +00001044 ForwardIDFCalculator IDFs(DT, GD);
Alina Sbirlea79800992018-09-10 20:13:01 +00001045 SmallPtrSet<BasicBlock *, 16> DefiningBlocks(BlocksToProcess.begin(),
1046 BlocksToProcess.end());
1047 IDFs.setDefiningBlocks(DefiningBlocks);
1048 IDFs.calculate(IDFBlocks);
Alina Sbirlea05f77802019-06-17 18:16:53 +00001049
1050 SmallSetVector<MemoryPhi *, 4> PhisToFill;
1051 // First create all needed Phis.
1052 for (auto *BBIDF : IDFBlocks)
1053 if (!MSSA->getMemoryAccess(BBIDF)) {
1054 auto *IDFPhi = MSSA->createMemoryPhi(BBIDF);
1055 InsertedPhis.push_back(IDFPhi);
1056 PhisToFill.insert(IDFPhi);
1057 }
1058 // Then update or insert their correct incoming values.
Alina Sbirlea79800992018-09-10 20:13:01 +00001059 for (auto *BBIDF : IDFBlocks) {
Alina Sbirlea05f77802019-06-17 18:16:53 +00001060 auto *IDFPhi = MSSA->getMemoryAccess(BBIDF);
1061 assert(IDFPhi && "Phi must exist");
1062 if (!PhisToFill.count(IDFPhi)) {
Alina Sbirlea79800992018-09-10 20:13:01 +00001063 // Update existing Phi.
1064 // FIXME: some updates may be redundant, try to optimize and skip some.
1065 for (unsigned I = 0, E = IDFPhi->getNumIncomingValues(); I < E; ++I)
1066 IDFPhi->setIncomingValue(I, GetLastDef(IDFPhi->getIncomingBlock(I)));
1067 } else {
Alina Sbirlea79800992018-09-10 20:13:01 +00001068 for (auto &Pair : children<GraphDiffInvBBPair>({GD, BBIDF})) {
1069 BasicBlock *Pi = Pair.second;
1070 IDFPhi->addIncoming(GetLastDef(Pi), Pi);
1071 }
1072 }
1073 }
1074 }
1075
1076 // Now for all defs in BlocksWithDefsToReplace, if there are uses they no
1077 // longer dominate, replace those with the closest dominating def.
1078 // This will also update optimized accesses, as they're also uses.
1079 for (auto *BlockWithDefsToReplace : BlocksWithDefsToReplace) {
1080 if (auto DefsList = MSSA->getWritableBlockDefs(BlockWithDefsToReplace)) {
1081 for (auto &DefToReplaceUses : *DefsList) {
1082 BasicBlock *DominatingBlock = DefToReplaceUses.getBlock();
1083 Value::use_iterator UI = DefToReplaceUses.use_begin(),
1084 E = DefToReplaceUses.use_end();
1085 for (; UI != E;) {
1086 Use &U = *UI;
1087 ++UI;
Simon Pilgrimb635964a2019-10-02 13:09:12 +00001088 MemoryAccess *Usr = cast<MemoryAccess>(U.getUser());
Alina Sbirlea79800992018-09-10 20:13:01 +00001089 if (MemoryPhi *UsrPhi = dyn_cast<MemoryPhi>(Usr)) {
1090 BasicBlock *DominatedBlock = UsrPhi->getIncomingBlock(U);
1091 if (!DT.dominates(DominatingBlock, DominatedBlock))
1092 U.set(GetLastDef(DominatedBlock));
1093 } else {
1094 BasicBlock *DominatedBlock = Usr->getBlock();
1095 if (!DT.dominates(DominatingBlock, DominatedBlock)) {
1096 if (auto *DomBlPhi = MSSA->getMemoryAccess(DominatedBlock))
1097 U.set(DomBlPhi);
1098 else {
1099 auto *IDom = DT.getNode(DominatedBlock)->getIDom();
1100 assert(IDom && "Block must have a valid IDom.");
1101 U.set(GetLastDef(IDom->getBlock()));
1102 }
1103 cast<MemoryUseOrDef>(Usr)->resetOptimized();
1104 }
1105 }
1106 }
1107 }
1108 }
1109 }
Alina Sbirleacb4ed8a2019-06-11 19:09:34 +00001110 tryRemoveTrivialPhis(InsertedPhis);
Alina Sbirlea79800992018-09-10 20:13:01 +00001111}
1112
Daniel Berlinae6b8b62017-01-28 01:35:02 +00001113// Move What before Where in the MemorySSA IR.
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001114template <class WhereType>
Daniel Berlinae6b8b62017-01-28 01:35:02 +00001115void MemorySSAUpdater::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001116 WhereType Where) {
Zhaoshi Zheng43af17b2018-04-09 20:55:37 +00001117 // Mark MemoryPhi users of What not to be optimized.
1118 for (auto *U : What->users())
George Burgess IVe7cdb7e2018-07-12 21:56:31 +00001119 if (MemoryPhi *PhiUser = dyn_cast<MemoryPhi>(U))
Zhaoshi Zheng43af17b2018-04-09 20:55:37 +00001120 NonOptPhis.insert(PhiUser);
1121
Daniel Berlinae6b8b62017-01-28 01:35:02 +00001122 // Replace all our users with our defining access.
1123 What->replaceAllUsesWith(What->getDefiningAccess());
1124
1125 // Let MemorySSA take care of moving it around in the lists.
1126 MSSA->moveTo(What, BB, Where);
1127
1128 // Now reinsert it into the IR and do whatever fixups needed.
1129 if (auto *MD = dyn_cast<MemoryDef>(What))
Alina Sbirlea1a3fdaf2019-08-19 18:57:40 +00001130 insertDef(MD, /*RenameUses=*/true);
Daniel Berlinae6b8b62017-01-28 01:35:02 +00001131 else
Alina Sbirlea1a3fdaf2019-08-19 18:57:40 +00001132 insertUse(cast<MemoryUse>(What), /*RenameUses=*/true);
Zhaoshi Zheng43af17b2018-04-09 20:55:37 +00001133
1134 // Clear dangling pointers. We added all MemoryPhi users, but not all
1135 // of them are removed by fixupDefs().
1136 NonOptPhis.clear();
Daniel Berlinae6b8b62017-01-28 01:35:02 +00001137}
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001138
Daniel Berlinae6b8b62017-01-28 01:35:02 +00001139// Move What before Where in the MemorySSA IR.
1140void MemorySSAUpdater::moveBefore(MemoryUseOrDef *What, MemoryUseOrDef *Where) {
1141 moveTo(What, Where->getBlock(), Where->getIterator());
1142}
1143
1144// Move What after Where in the MemorySSA IR.
1145void MemorySSAUpdater::moveAfter(MemoryUseOrDef *What, MemoryUseOrDef *Where) {
1146 moveTo(What, Where->getBlock(), ++Where->getIterator());
1147}
1148
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001149void MemorySSAUpdater::moveToPlace(MemoryUseOrDef *What, BasicBlock *BB,
1150 MemorySSA::InsertionPlace Where) {
1151 return moveTo(What, BB, Where);
1152}
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001153
Alina Sbirlea0f533552018-07-11 22:11:46 +00001154// All accesses in To used to be in From. Move to end and update access lists.
1155void MemorySSAUpdater::moveAllAccesses(BasicBlock *From, BasicBlock *To,
1156 Instruction *Start) {
1157
1158 MemorySSA::AccessList *Accs = MSSA->getWritableBlockAccesses(From);
1159 if (!Accs)
1160 return;
1161
Alina Sbirlea7faa14a2019-10-09 15:54:24 +00001162 assert(Start->getParent() == To && "Incorrect Start instruction");
Alina Sbirlea0f533552018-07-11 22:11:46 +00001163 MemoryAccess *FirstInNew = nullptr;
1164 for (Instruction &I : make_range(Start->getIterator(), To->end()))
1165 if ((FirstInNew = MSSA->getMemoryAccess(&I)))
1166 break;
Alina Sbirlea7faa14a2019-10-09 15:54:24 +00001167 if (FirstInNew) {
1168 auto *MUD = cast<MemoryUseOrDef>(FirstInNew);
1169 do {
1170 auto NextIt = ++MUD->getIterator();
1171 MemoryUseOrDef *NextMUD = (!Accs || NextIt == Accs->end())
1172 ? nullptr
1173 : cast<MemoryUseOrDef>(&*NextIt);
1174 MSSA->moveTo(MUD, To, MemorySSA::End);
1175 // Moving MUD from Accs in the moveTo above, may delete Accs, so we need
1176 // to retrieve it again.
1177 Accs = MSSA->getWritableBlockAccesses(From);
1178 MUD = NextMUD;
1179 } while (MUD);
1180 }
Alina Sbirlea0f533552018-07-11 22:11:46 +00001181
Alina Sbirlea7faa14a2019-10-09 15:54:24 +00001182 // If all accesses were moved and only a trivial Phi remains, we try to remove
1183 // that Phi. This is needed when From is going to be deleted.
1184 auto *Defs = MSSA->getWritableBlockDefs(From);
1185 if (Defs && !Defs->empty())
1186 if (auto *Phi = dyn_cast<MemoryPhi>(&*Defs->begin()))
1187 tryRemoveTrivialPhi(Phi);
Alina Sbirlea0f533552018-07-11 22:11:46 +00001188}
1189
1190void MemorySSAUpdater::moveAllAfterSpliceBlocks(BasicBlock *From,
1191 BasicBlock *To,
1192 Instruction *Start) {
1193 assert(MSSA->getBlockAccesses(To) == nullptr &&
1194 "To block is expected to be free of MemoryAccesses.");
1195 moveAllAccesses(From, To, Start);
1196 for (BasicBlock *Succ : successors(To))
1197 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(Succ))
1198 MPhi->setIncomingBlock(MPhi->getBasicBlockIndex(From), To);
1199}
1200
1201void MemorySSAUpdater::moveAllAfterMergeBlocks(BasicBlock *From, BasicBlock *To,
1202 Instruction *Start) {
Alina Sbirlea7faa14a2019-10-09 15:54:24 +00001203 assert(From->getUniquePredecessor() == To &&
Alina Sbirlea0f533552018-07-11 22:11:46 +00001204 "From block is expected to have a single predecessor (To).");
1205 moveAllAccesses(From, To, Start);
1206 for (BasicBlock *Succ : successors(From))
1207 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(Succ))
1208 MPhi->setIncomingBlock(MPhi->getBasicBlockIndex(From), To);
1209}
1210
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001211/// If all arguments of a MemoryPHI are defined by the same incoming
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001212/// argument, return that argument.
1213static MemoryAccess *onlySingleValue(MemoryPhi *MP) {
1214 MemoryAccess *MA = nullptr;
1215
1216 for (auto &Arg : MP->operands()) {
1217 if (!MA)
1218 MA = cast<MemoryAccess>(Arg);
1219 else if (MA != Arg)
1220 return nullptr;
1221 }
1222 return MA;
1223}
George Burgess IV56169ed2017-04-21 04:54:52 +00001224
Alina Sbirlea20c29622018-07-20 17:13:05 +00001225void MemorySSAUpdater::wireOldPredecessorsToNewImmediatePredecessor(
Alina Sbirleaf98c2c52018-09-07 21:14:48 +00001226 BasicBlock *Old, BasicBlock *New, ArrayRef<BasicBlock *> Preds,
1227 bool IdenticalEdgesWereMerged) {
Alina Sbirlea20c29622018-07-20 17:13:05 +00001228 assert(!MSSA->getWritableBlockAccesses(New) &&
1229 "Access list should be null for a new block.");
1230 MemoryPhi *Phi = MSSA->getMemoryAccess(Old);
1231 if (!Phi)
1232 return;
Vedant Kumar4de31bb2018-11-19 19:54:27 +00001233 if (Old->hasNPredecessors(1)) {
Alina Sbirlea20c29622018-07-20 17:13:05 +00001234 assert(pred_size(New) == Preds.size() &&
1235 "Should have moved all predecessors.");
1236 MSSA->moveTo(Phi, New, MemorySSA::Beginning);
1237 } else {
1238 assert(!Preds.empty() && "Must be moving at least one predecessor to the "
1239 "new immediate predecessor.");
1240 MemoryPhi *NewPhi = MSSA->createMemoryPhi(New);
1241 SmallPtrSet<BasicBlock *, 16> PredsSet(Preds.begin(), Preds.end());
Alina Sbirleaf98c2c52018-09-07 21:14:48 +00001242 // Currently only support the case of removing a single incoming edge when
1243 // identical edges were not merged.
1244 if (!IdenticalEdgesWereMerged)
1245 assert(PredsSet.size() == Preds.size() &&
1246 "If identical edges were not merged, we cannot have duplicate "
1247 "blocks in the predecessors");
Alina Sbirlea20c29622018-07-20 17:13:05 +00001248 Phi->unorderedDeleteIncomingIf([&](MemoryAccess *MA, BasicBlock *B) {
1249 if (PredsSet.count(B)) {
1250 NewPhi->addIncoming(MA, B);
Alina Sbirleaf98c2c52018-09-07 21:14:48 +00001251 if (!IdenticalEdgesWereMerged)
1252 PredsSet.erase(B);
Alina Sbirlea20c29622018-07-20 17:13:05 +00001253 return true;
1254 }
1255 return false;
1256 });
1257 Phi->addIncoming(NewPhi, New);
Alina Sbirlea28637212019-08-20 22:47:58 +00001258 tryRemoveTrivialPhi(NewPhi);
Alina Sbirlea20c29622018-07-20 17:13:05 +00001259 }
1260}
1261
Alina Sbirlea240a90a2019-01-31 20:13:47 +00001262void MemorySSAUpdater::removeMemoryAccess(MemoryAccess *MA, bool OptimizePhis) {
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001263 assert(!MSSA->isLiveOnEntryDef(MA) &&
1264 "Trying to remove the live on entry def");
1265 // We can only delete phi nodes if they have no uses, or we can replace all
1266 // uses with a single definition.
1267 MemoryAccess *NewDefTarget = nullptr;
1268 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) {
1269 // Note that it is sufficient to know that all edges of the phi node have
1270 // the same argument. If they do, by the definition of dominance frontiers
1271 // (which we used to place this phi), that argument must dominate this phi,
1272 // and thus, must dominate the phi's uses, and so we will not hit the assert
1273 // below.
1274 NewDefTarget = onlySingleValue(MP);
1275 assert((NewDefTarget || MP->use_empty()) &&
1276 "We can't delete this memory phi");
1277 } else {
1278 NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess();
1279 }
1280
Alina Sbirlea240a90a2019-01-31 20:13:47 +00001281 SmallSetVector<MemoryPhi *, 4> PhisToCheck;
1282
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001283 // Re-point the uses at our defining access
1284 if (!isa<MemoryUse>(MA) && !MA->use_empty()) {
1285 // Reset optimized on users of this store, and reset the uses.
1286 // A few notes:
1287 // 1. This is a slightly modified version of RAUW to avoid walking the
1288 // uses twice here.
1289 // 2. If we wanted to be complete, we would have to reset the optimized
1290 // flags on users of phi nodes if doing the below makes a phi node have all
1291 // the same arguments. Instead, we prefer users to removeMemoryAccess those
1292 // phi nodes, because doing it here would be N^3.
1293 if (MA->hasValueHandle())
1294 ValueHandleBase::ValueIsRAUWd(MA, NewDefTarget);
1295 // Note: We assume MemorySSA is not used in metadata since it's not really
1296 // part of the IR.
1297
1298 while (!MA->use_empty()) {
1299 Use &U = *MA->use_begin();
Daniel Berline33bc312017-04-04 23:43:10 +00001300 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U.getUser()))
1301 MUD->resetOptimized();
Alina Sbirlea240a90a2019-01-31 20:13:47 +00001302 if (OptimizePhis)
1303 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(U.getUser()))
1304 PhisToCheck.insert(MP);
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001305 U.set(NewDefTarget);
1306 }
1307 }
1308
1309 // The call below to erase will destroy MA, so we can't change the order we
1310 // are doing things here
1311 MSSA->removeFromLookups(MA);
1312 MSSA->removeFromLists(MA);
Alina Sbirlea240a90a2019-01-31 20:13:47 +00001313
1314 // Optionally optimize Phi uses. This will recursively remove trivial phis.
1315 if (!PhisToCheck.empty()) {
1316 SmallVector<WeakVH, 16> PhisToOptimize{PhisToCheck.begin(),
1317 PhisToCheck.end()};
1318 PhisToCheck.clear();
1319
1320 unsigned PhisSize = PhisToOptimize.size();
1321 while (PhisSize-- > 0)
1322 if (MemoryPhi *MP =
Alina Sbirlea28637212019-08-20 22:47:58 +00001323 cast_or_null<MemoryPhi>(PhisToOptimize.pop_back_val()))
1324 tryRemoveTrivialPhi(MP);
Alina Sbirlea240a90a2019-01-31 20:13:47 +00001325 }
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001326}
1327
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001328void MemorySSAUpdater::removeBlocks(
Alina Sbirleadb101862019-07-12 22:30:30 +00001329 const SmallSetVector<BasicBlock *, 8> &DeadBlocks) {
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001330 // First delete all uses of BB in MemoryPhis.
1331 for (BasicBlock *BB : DeadBlocks) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00001332 Instruction *TI = BB->getTerminator();
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001333 assert(TI && "Basic block expected to have a terminator instruction");
Chandler Carruth96fc1de2018-08-26 08:41:15 +00001334 for (BasicBlock *Succ : successors(TI))
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001335 if (!DeadBlocks.count(Succ))
1336 if (MemoryPhi *MP = MSSA->getMemoryAccess(Succ)) {
1337 MP->unorderedDeleteIncomingBlock(BB);
Alina Sbirlea28637212019-08-20 22:47:58 +00001338 tryRemoveTrivialPhi(MP);
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001339 }
1340 // Drop all references of all accesses in BB
1341 if (MemorySSA::AccessList *Acc = MSSA->getWritableBlockAccesses(BB))
1342 for (MemoryAccess &MA : *Acc)
1343 MA.dropAllReferences();
1344 }
1345
1346 // Next, delete all memory accesses in each block
1347 for (BasicBlock *BB : DeadBlocks) {
1348 MemorySSA::AccessList *Acc = MSSA->getWritableBlockAccesses(BB);
1349 if (!Acc)
1350 continue;
1351 for (auto AB = Acc->begin(), AE = Acc->end(); AB != AE;) {
1352 MemoryAccess *MA = &*AB;
1353 ++AB;
1354 MSSA->removeFromLookups(MA);
1355 MSSA->removeFromLists(MA);
1356 }
1357 }
1358}
1359
Alina Sbirlea151ab482019-05-02 23:12:49 +00001360void MemorySSAUpdater::tryRemoveTrivialPhis(ArrayRef<WeakVH> UpdatedPHIs) {
1361 for (auto &VH : UpdatedPHIs)
Alina Sbirlea28637212019-08-20 22:47:58 +00001362 if (auto *MPhi = cast_or_null<MemoryPhi>(VH))
1363 tryRemoveTrivialPhi(MPhi);
Alina Sbirlea151ab482019-05-02 23:12:49 +00001364}
1365
Alina Sbirleaf31eba62019-05-08 17:05:36 +00001366void MemorySSAUpdater::changeToUnreachable(const Instruction *I) {
1367 const BasicBlock *BB = I->getParent();
1368 // Remove memory accesses in BB for I and all following instructions.
1369 auto BBI = I->getIterator(), BBE = BB->end();
1370 // FIXME: If this becomes too expensive, iterate until the first instruction
1371 // with a memory access, then iterate over MemoryAccesses.
1372 while (BBI != BBE)
1373 removeMemoryAccess(&*(BBI++));
1374 // Update phis in BB's successors to remove BB.
1375 SmallVector<WeakVH, 16> UpdatedPHIs;
1376 for (const BasicBlock *Successor : successors(BB)) {
1377 removeDuplicatePhiEdgesBetween(BB, Successor);
1378 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(Successor)) {
1379 MPhi->unorderedDeleteIncomingBlock(BB);
1380 UpdatedPHIs.push_back(MPhi);
1381 }
1382 }
1383 // Optimize trivial phis.
1384 tryRemoveTrivialPhis(UpdatedPHIs);
1385}
1386
1387void MemorySSAUpdater::changeCondBranchToUnconditionalTo(const BranchInst *BI,
1388 const BasicBlock *To) {
1389 const BasicBlock *BB = BI->getParent();
1390 SmallVector<WeakVH, 16> UpdatedPHIs;
1391 for (const BasicBlock *Succ : successors(BB)) {
1392 removeDuplicatePhiEdgesBetween(BB, Succ);
1393 if (Succ != To)
1394 if (auto *MPhi = MSSA->getMemoryAccess(Succ)) {
1395 MPhi->unorderedDeleteIncomingBlock(BB);
1396 UpdatedPHIs.push_back(MPhi);
1397 }
1398 }
1399 // Optimize trivial phis.
1400 tryRemoveTrivialPhis(UpdatedPHIs);
1401}
1402
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001403MemoryAccess *MemorySSAUpdater::createMemoryAccessInBB(
1404 Instruction *I, MemoryAccess *Definition, const BasicBlock *BB,
1405 MemorySSA::InsertionPlace Point) {
1406 MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition);
1407 MSSA->insertIntoListsForBlock(NewAccess, BB, Point);
1408 return NewAccess;
1409}
1410
1411MemoryUseOrDef *MemorySSAUpdater::createMemoryAccessBefore(
1412 Instruction *I, MemoryAccess *Definition, MemoryUseOrDef *InsertPt) {
1413 assert(I->getParent() == InsertPt->getBlock() &&
1414 "New and old access must be in the same block");
1415 MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition);
1416 MSSA->insertIntoListsBefore(NewAccess, InsertPt->getBlock(),
1417 InsertPt->getIterator());
1418 return NewAccess;
1419}
1420
1421MemoryUseOrDef *MemorySSAUpdater::createMemoryAccessAfter(
1422 Instruction *I, MemoryAccess *Definition, MemoryAccess *InsertPt) {
1423 assert(I->getParent() == InsertPt->getBlock() &&
1424 "New and old access must be in the same block");
1425 MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition);
1426 MSSA->insertIntoListsBefore(NewAccess, InsertPt->getBlock(),
1427 ++InsertPt->getIterator());
1428 return NewAccess;
1429}