blob: b62cf08eb4c8da9f131b11988b8f9b6212aac5f4 [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);
306 bool DefBeforeSameBlock = DefBefore->getBlock() == MD->getBlock();
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000307
308 // There is a def before us, which means we can replace any store/phi uses
309 // of that thing with us, since we are in the way of whatever was there
310 // before.
311 // We now define that def's memorydefs and memoryphis
Daniel Berlin9d8a3352017-01-30 11:35:39 +0000312 if (DefBeforeSameBlock) {
Roman Lebedev081e9902019-08-01 12:32:08 +0000313 DefBefore->replaceUsesWithIf(MD, [MD](Use &U) {
Alexandros Lamprineas96762b32018-09-11 14:29:59 +0000314 // Leave the MemoryUses alone.
315 // Also make sure we skip ourselves to avoid self references.
Roman Lebedev081e9902019-08-01 12:32:08 +0000316 User *Usr = U.getUser();
317 return !isa<MemoryUse>(Usr) && Usr != MD;
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000318 // Defs are automatically unoptimized when the user is set to MD below,
319 // because the isOptimized() call will fail to find the same ID.
Roman Lebedev081e9902019-08-01 12:32:08 +0000320 });
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000321 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +0000322
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000323 // and that def is now our defining access.
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000324 MD->setDefiningAccess(DefBefore);
325
Alexandros Lamprineasf854ce82018-07-16 07:51:27 +0000326 SmallVector<WeakVH, 8> FixupList(InsertedPHIs.begin(), InsertedPHIs.end());
Alina Sbirlea2c5e6642019-09-23 23:50:16 +0000327
Alina Sbirlea6720ed82019-09-25 23:24:39 +0000328 // Remember the index where we may insert new phis.
329 unsigned NewPhiIndex = InsertedPHIs.size();
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000330 if (!DefBeforeSameBlock) {
331 // If there was a local def before us, we must have the same effect it
332 // did. Because every may-def is the same, any phis/etc we would create, it
333 // would also have created. If there was no local def before us, we
334 // performed a global update, and have to search all successors and make
335 // sure we update the first def in each of them (following all paths until
336 // we hit the first def along each path). This may also insert phi nodes.
337 // TODO: There are other cases we can skip this work, such as when we have a
338 // single successor, and only used a straight line of single pred blocks
339 // backwards to find the def. To make that work, we'd have to track whether
340 // getDefRecursive only ever used the single predecessor case. These types
341 // of paths also only exist in between CFG simplifications.
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000342
343 // If this is the first def in the block and this insert is in an arbitrary
344 // place, compute IDF and place phis.
345 auto Iter = MD->getDefsIterator();
346 ++Iter;
347 auto IterEnd = MSSA->getBlockDefs(MD->getBlock())->end();
Alina Sbirlea6720ed82019-09-25 23:24:39 +0000348 if (Iter == IterEnd) {
349 SmallPtrSet<BasicBlock *, 2> DefiningBlocks;
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000350 DefiningBlocks.insert(MD->getBlock());
Alina Sbirlea6720ed82019-09-25 23:24:39 +0000351 for (const auto &VH : InsertedPHIs)
352 if (const auto *RealPHI = cast_or_null<MemoryPhi>(VH))
353 DefiningBlocks.insert(RealPHI->getBlock());
354 ForwardIDFCalculator IDFs(*MSSA->DT);
355 SmallVector<BasicBlock *, 32> IDFBlocks;
356 IDFs.setDefiningBlocks(DefiningBlocks);
357 IDFs.calculate(IDFBlocks);
358 SmallVector<AssertingVH<MemoryPhi>, 4> NewInsertedPHIs;
359 for (auto *BBIDF : IDFBlocks) {
360 auto *MPhi = MSSA->getMemoryAccess(BBIDF);
361 if (!MPhi) {
362 MPhi = MSSA->createMemoryPhi(BBIDF);
363 NewInsertedPHIs.push_back(MPhi);
364 }
365 // Add the phis created into the IDF blocks to NonOptPhis, so they are
366 // not optimized out as trivial by the call to getPreviousDefFromEnd
367 // below. Once they are complete, all these Phis are added to the
368 // FixupList, and removed from NonOptPhis inside fixupDefs(). Existing
369 // Phis in IDF may need fixing as well, and potentially be trivial
370 // before this insertion, hence add all IDF Phis. See PR43044.
371 NonOptPhis.insert(MPhi);
372 }
373 for (auto &MPhi : NewInsertedPHIs) {
374 auto *BBIDF = MPhi->getBlock();
375 for (auto *Pred : predecessors(BBIDF)) {
376 DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> CachedPreviousDef;
377 MPhi->addIncoming(getPreviousDefFromEnd(Pred, CachedPreviousDef),
378 Pred);
379 }
380 }
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000381
Alina Sbirlea6720ed82019-09-25 23:24:39 +0000382 // Re-take the index where we're adding the new phis, because the above
383 // call to getPreviousDefFromEnd, may have inserted into InsertedPHIs.
384 NewPhiIndex = InsertedPHIs.size();
385 for (auto &MPhi : NewInsertedPHIs) {
386 InsertedPHIs.push_back(&*MPhi);
387 FixupList.push_back(&*MPhi);
388 }
389 }
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000390 FixupList.push_back(MD);
391 }
392
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000393 // Remember the index where we stopped inserting new phis above, since the
394 // fixupDefs call in the loop below may insert more, that are already minimal.
395 unsigned NewPhiIndexEnd = InsertedPHIs.size();
396
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000397 while (!FixupList.empty()) {
398 unsigned StartingPHISize = InsertedPHIs.size();
399 fixupDefs(FixupList);
400 FixupList.clear();
401 // Put any new phis on the fixup list, and process them
Alexandros Lamprineasf854ce82018-07-16 07:51:27 +0000402 FixupList.append(InsertedPHIs.begin() + StartingPHISize, InsertedPHIs.end());
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000403 }
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000404
405 // Optimize potentially non-minimal phis added in this method.
Alina Sbirlea151ab482019-05-02 23:12:49 +0000406 unsigned NewPhiSize = NewPhiIndexEnd - NewPhiIndex;
407 if (NewPhiSize)
408 tryRemoveTrivialPhis(ArrayRef<WeakVH>(&InsertedPHIs[NewPhiIndex], NewPhiSize));
Alina Sbirleafcfa7c52019-02-27 22:20:22 +0000409
Daniel Berlin78cbd282017-02-20 22:26:03 +0000410 // Now that all fixups are done, rename all uses if we are asked.
411 if (RenameUses) {
412 SmallPtrSet<BasicBlock *, 16> Visited;
413 BasicBlock *StartBlock = MD->getBlock();
414 // We are guaranteed there is a def in the block, because we just got it
415 // handed to us in this function.
416 MemoryAccess *FirstDef = &*MSSA->getWritableBlockDefs(StartBlock)->begin();
417 // Convert to incoming value if it's a memorydef. A phi *is* already an
418 // incoming value.
419 if (auto *MD = dyn_cast<MemoryDef>(FirstDef))
420 FirstDef = MD->getDefiningAccess();
421
422 MSSA->renamePass(MD->getBlock(), FirstDef, Visited);
423 // We just inserted a phi into this block, so the incoming value will become
424 // the phi anyway, so it does not matter what we pass.
Alexandros Lamprineasf854ce82018-07-16 07:51:27 +0000425 for (auto &MP : InsertedPHIs) {
426 MemoryPhi *Phi = dyn_cast_or_null<MemoryPhi>(MP);
427 if (Phi)
428 MSSA->renamePass(Phi->getBlock(), nullptr, Visited);
429 }
Daniel Berlin78cbd282017-02-20 22:26:03 +0000430 }
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000431}
432
Alexandros Lamprineasf854ce82018-07-16 07:51:27 +0000433void MemorySSAUpdater::fixupDefs(const SmallVectorImpl<WeakVH> &Vars) {
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000434 SmallPtrSet<const BasicBlock *, 8> Seen;
435 SmallVector<const BasicBlock *, 16> Worklist;
Alexandros Lamprineasf854ce82018-07-16 07:51:27 +0000436 for (auto &Var : Vars) {
437 MemoryAccess *NewDef = dyn_cast_or_null<MemoryAccess>(Var);
438 if (!NewDef)
439 continue;
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000440 // First, see if there is a local def after the operand.
441 auto *Defs = MSSA->getWritableBlockDefs(NewDef->getBlock());
442 auto DefIter = NewDef->getDefsIterator();
443
Zhaoshi Zheng43af17b2018-04-09 20:55:37 +0000444 // The temporary Phi is being fixed, unmark it for not to optimize.
George Burgess IVe7cdb7e2018-07-12 21:56:31 +0000445 if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(NewDef))
Zhaoshi Zheng43af17b2018-04-09 20:55:37 +0000446 NonOptPhis.erase(Phi);
447
Daniel Berlinae6b8b62017-01-28 01:35:02 +0000448 // If there is a local def after us, we only have to rename that.
449 if (++DefIter != Defs->end()) {
450 cast<MemoryDef>(DefIter)->setDefiningAccess(NewDef);
451 continue;
452 }
453
454 // Otherwise, we need to search down through the CFG.
455 // For each of our successors, handle it directly if their is a phi, or
456 // place on the fixup worklist.
457 for (const auto *S : successors(NewDef->getBlock())) {
458 if (auto *MP = MSSA->getMemoryAccess(S))
459 setMemoryPhiValueForBlock(MP, NewDef->getBlock(), NewDef);
460 else
461 Worklist.push_back(S);
462 }
463
464 while (!Worklist.empty()) {
465 const BasicBlock *FixupBlock = Worklist.back();
466 Worklist.pop_back();
467
468 // Get the first def in the block that isn't a phi node.
469 if (auto *Defs = MSSA->getWritableBlockDefs(FixupBlock)) {
470 auto *FirstDef = &*Defs->begin();
471 // The loop above and below should have taken care of phi nodes
472 assert(!isa<MemoryPhi>(FirstDef) &&
473 "Should have already handled phi nodes!");
474 // We are now this def's defining access, make sure we actually dominate
475 // it
476 assert(MSSA->dominates(NewDef, FirstDef) &&
477 "Should have dominated the new access");
478
479 // This may insert new phi nodes, because we are not guaranteed the
480 // block we are processing has a single pred, and depending where the
481 // store was inserted, it may require phi nodes below it.
482 cast<MemoryDef>(FirstDef)->setDefiningAccess(getPreviousDef(FirstDef));
483 return;
484 }
485 // We didn't find a def, so we must continue.
486 for (const auto *S : successors(FixupBlock)) {
487 // If there is a phi node, handle it.
488 // Otherwise, put the block on the worklist
489 if (auto *MP = MSSA->getMemoryAccess(S))
490 setMemoryPhiValueForBlock(MP, FixupBlock, NewDef);
491 else {
492 // If we cycle, we should have ended up at a phi node that we already
493 // processed. FIXME: Double check this
494 if (!Seen.insert(S).second)
495 continue;
496 Worklist.push_back(S);
497 }
498 }
499 }
500 }
501}
502
Alina Sbirlea79800992018-09-10 20:13:01 +0000503void MemorySSAUpdater::removeEdge(BasicBlock *From, BasicBlock *To) {
504 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(To)) {
505 MPhi->unorderedDeleteIncomingBlock(From);
Alina Sbirlea28637212019-08-20 22:47:58 +0000506 tryRemoveTrivialPhi(MPhi);
Alina Sbirlea79800992018-09-10 20:13:01 +0000507 }
508}
509
Alina Sbirleaf31eba62019-05-08 17:05:36 +0000510void MemorySSAUpdater::removeDuplicatePhiEdgesBetween(const BasicBlock *From,
511 const BasicBlock *To) {
Alina Sbirlea79800992018-09-10 20:13:01 +0000512 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(To)) {
513 bool Found = false;
514 MPhi->unorderedDeleteIncomingIf([&](const MemoryAccess *, BasicBlock *B) {
515 if (From != B)
516 return false;
517 if (Found)
518 return true;
519 Found = true;
520 return false;
521 });
Alina Sbirlea28637212019-08-20 22:47:58 +0000522 tryRemoveTrivialPhi(MPhi);
Alina Sbirlea79800992018-09-10 20:13:01 +0000523 }
524}
525
Alina Sbirlea4bc625c2019-07-30 20:10:33 +0000526static MemoryAccess *getNewDefiningAccessForClone(MemoryAccess *MA,
527 const ValueToValueMapTy &VMap,
528 PhiToDefMap &MPhiMap,
529 bool CloneWasSimplified,
530 MemorySSA *MSSA) {
531 MemoryAccess *InsnDefining = MA;
532 if (MemoryDef *DefMUD = dyn_cast<MemoryDef>(InsnDefining)) {
533 if (!MSSA->isLiveOnEntryDef(DefMUD)) {
534 Instruction *DefMUDI = DefMUD->getMemoryInst();
535 assert(DefMUDI && "Found MemoryUseOrDef with no Instruction.");
536 if (Instruction *NewDefMUDI =
537 cast_or_null<Instruction>(VMap.lookup(DefMUDI))) {
538 InsnDefining = MSSA->getMemoryAccess(NewDefMUDI);
539 if (!CloneWasSimplified)
540 assert(InsnDefining && "Defining instruction cannot be nullptr.");
541 else if (!InsnDefining || isa<MemoryUse>(InsnDefining)) {
542 // The clone was simplified, it's no longer a MemoryDef, look up.
543 auto DefIt = DefMUD->getDefsIterator();
544 // Since simplified clones only occur in single block cloning, a
545 // previous definition must exist, otherwise NewDefMUDI would not
546 // have been found in VMap.
547 assert(DefIt != MSSA->getBlockDefs(DefMUD->getBlock())->begin() &&
548 "Previous def must exist");
549 InsnDefining = getNewDefiningAccessForClone(
550 &*(--DefIt), VMap, MPhiMap, CloneWasSimplified, MSSA);
551 }
552 }
553 }
554 } else {
555 MemoryPhi *DefPhi = cast<MemoryPhi>(InsnDefining);
556 if (MemoryAccess *NewDefPhi = MPhiMap.lookup(DefPhi))
557 InsnDefining = NewDefPhi;
558 }
559 assert(InsnDefining && "Defining instruction cannot be nullptr.");
560 return InsnDefining;
561}
562
Alina Sbirlea79800992018-09-10 20:13:01 +0000563void MemorySSAUpdater::cloneUsesAndDefs(BasicBlock *BB, BasicBlock *NewBB,
564 const ValueToValueMapTy &VMap,
Alina Sbirlea7a0098a2019-06-17 18:58:40 +0000565 PhiToDefMap &MPhiMap,
566 bool CloneWasSimplified) {
Alina Sbirlea79800992018-09-10 20:13:01 +0000567 const MemorySSA::AccessList *Acc = MSSA->getBlockAccesses(BB);
568 if (!Acc)
569 return;
570 for (const MemoryAccess &MA : *Acc) {
571 if (const MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&MA)) {
572 Instruction *Insn = MUD->getMemoryInst();
573 // Entry does not exist if the clone of the block did not clone all
574 // instructions. This occurs in LoopRotate when cloning instructions
575 // from the old header to the old preheader. The cloned instruction may
576 // also be a simplified Value, not an Instruction (see LoopRotate).
Alina Sbirlea7a0098a2019-06-17 18:58:40 +0000577 // Also in LoopRotate, even when it's an instruction, due to it being
578 // simplified, it may be a Use rather than a Def, so we cannot use MUD as
579 // template. Calls coming from updateForClonedBlockIntoPred, ensure this.
Alina Sbirlea79800992018-09-10 20:13:01 +0000580 if (Instruction *NewInsn =
581 dyn_cast_or_null<Instruction>(VMap.lookup(Insn))) {
582 MemoryAccess *NewUseOrDef = MSSA->createDefinedAccess(
Alina Sbirlea4bc625c2019-07-30 20:10:33 +0000583 NewInsn,
584 getNewDefiningAccessForClone(MUD->getDefiningAccess(), VMap,
585 MPhiMap, CloneWasSimplified, MSSA),
586 /*Template=*/CloneWasSimplified ? nullptr : MUD,
587 /*CreationMustSucceed=*/CloneWasSimplified ? false : true);
588 if (NewUseOrDef)
589 MSSA->insertIntoListsForBlock(NewUseOrDef, NewBB, MemorySSA::End);
Alina Sbirlea79800992018-09-10 20:13:01 +0000590 }
591 }
592 }
593}
594
Alina Sbirleaf31eba62019-05-08 17:05:36 +0000595void MemorySSAUpdater::updatePhisWhenInsertingUniqueBackedgeBlock(
596 BasicBlock *Header, BasicBlock *Preheader, BasicBlock *BEBlock) {
597 auto *MPhi = MSSA->getMemoryAccess(Header);
598 if (!MPhi)
599 return;
600
601 // Create phi node in the backedge block and populate it with the same
602 // incoming values as MPhi. Skip incoming values coming from Preheader.
603 auto *NewMPhi = MSSA->createMemoryPhi(BEBlock);
604 bool HasUniqueIncomingValue = true;
605 MemoryAccess *UniqueValue = nullptr;
606 for (unsigned I = 0, E = MPhi->getNumIncomingValues(); I != E; ++I) {
607 BasicBlock *IBB = MPhi->getIncomingBlock(I);
608 MemoryAccess *IV = MPhi->getIncomingValue(I);
609 if (IBB != Preheader) {
610 NewMPhi->addIncoming(IV, IBB);
611 if (HasUniqueIncomingValue) {
612 if (!UniqueValue)
613 UniqueValue = IV;
614 else if (UniqueValue != IV)
615 HasUniqueIncomingValue = false;
616 }
617 }
618 }
619
620 // Update incoming edges into MPhi. Remove all but the incoming edge from
621 // Preheader. Add an edge from NewMPhi
622 auto *AccFromPreheader = MPhi->getIncomingValueForBlock(Preheader);
623 MPhi->setIncomingValue(0, AccFromPreheader);
624 MPhi->setIncomingBlock(0, Preheader);
625 for (unsigned I = MPhi->getNumIncomingValues() - 1; I >= 1; --I)
626 MPhi->unorderedDeleteIncoming(I);
627 MPhi->addIncoming(NewMPhi, BEBlock);
628
629 // If NewMPhi is a trivial phi, remove it. Its use in the header MPhi will be
630 // replaced with the unique value.
Alina Sbirlea28637212019-08-20 22:47:58 +0000631 tryRemoveTrivialPhi(MPhi);
Alina Sbirleaf31eba62019-05-08 17:05:36 +0000632}
633
Alina Sbirlea79800992018-09-10 20:13:01 +0000634void MemorySSAUpdater::updateForClonedLoop(const LoopBlocksRPO &LoopBlocks,
635 ArrayRef<BasicBlock *> ExitBlocks,
636 const ValueToValueMapTy &VMap,
637 bool IgnoreIncomingWithNoClones) {
638 PhiToDefMap MPhiMap;
639
640 auto FixPhiIncomingValues = [&](MemoryPhi *Phi, MemoryPhi *NewPhi) {
641 assert(Phi && NewPhi && "Invalid Phi nodes.");
642 BasicBlock *NewPhiBB = NewPhi->getBlock();
643 SmallPtrSet<BasicBlock *, 4> NewPhiBBPreds(pred_begin(NewPhiBB),
644 pred_end(NewPhiBB));
645 for (unsigned It = 0, E = Phi->getNumIncomingValues(); It < E; ++It) {
646 MemoryAccess *IncomingAccess = Phi->getIncomingValue(It);
647 BasicBlock *IncBB = Phi->getIncomingBlock(It);
648
649 if (BasicBlock *NewIncBB = cast_or_null<BasicBlock>(VMap.lookup(IncBB)))
650 IncBB = NewIncBB;
651 else if (IgnoreIncomingWithNoClones)
652 continue;
653
654 // Now we have IncBB, and will need to add incoming from it to NewPhi.
655
656 // If IncBB is not a predecessor of NewPhiBB, then do not add it.
657 // NewPhiBB was cloned without that edge.
658 if (!NewPhiBBPreds.count(IncBB))
659 continue;
660
661 // Determine incoming value and add it as incoming from IncBB.
662 if (MemoryUseOrDef *IncMUD = dyn_cast<MemoryUseOrDef>(IncomingAccess)) {
663 if (!MSSA->isLiveOnEntryDef(IncMUD)) {
664 Instruction *IncI = IncMUD->getMemoryInst();
665 assert(IncI && "Found MemoryUseOrDef with no Instruction.");
666 if (Instruction *NewIncI =
667 cast_or_null<Instruction>(VMap.lookup(IncI))) {
668 IncMUD = MSSA->getMemoryAccess(NewIncI);
669 assert(IncMUD &&
670 "MemoryUseOrDef cannot be null, all preds processed.");
671 }
672 }
673 NewPhi->addIncoming(IncMUD, IncBB);
674 } else {
675 MemoryPhi *IncPhi = cast<MemoryPhi>(IncomingAccess);
676 if (MemoryAccess *NewDefPhi = MPhiMap.lookup(IncPhi))
677 NewPhi->addIncoming(NewDefPhi, IncBB);
678 else
679 NewPhi->addIncoming(IncPhi, IncBB);
680 }
681 }
682 };
683
684 auto ProcessBlock = [&](BasicBlock *BB) {
685 BasicBlock *NewBlock = cast_or_null<BasicBlock>(VMap.lookup(BB));
686 if (!NewBlock)
687 return;
688
689 assert(!MSSA->getWritableBlockAccesses(NewBlock) &&
690 "Cloned block should have no accesses");
691
692 // Add MemoryPhi.
693 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(BB)) {
694 MemoryPhi *NewPhi = MSSA->createMemoryPhi(NewBlock);
695 MPhiMap[MPhi] = NewPhi;
696 }
697 // Update Uses and Defs.
698 cloneUsesAndDefs(BB, NewBlock, VMap, MPhiMap);
699 };
700
701 for (auto BB : llvm::concat<BasicBlock *const>(LoopBlocks, ExitBlocks))
702 ProcessBlock(BB);
703
704 for (auto BB : llvm::concat<BasicBlock *const>(LoopBlocks, ExitBlocks))
705 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(BB))
706 if (MemoryAccess *NewPhi = MPhiMap.lookup(MPhi))
707 FixPhiIncomingValues(MPhi, cast<MemoryPhi>(NewPhi));
708}
709
710void MemorySSAUpdater::updateForClonedBlockIntoPred(
711 BasicBlock *BB, BasicBlock *P1, const ValueToValueMapTy &VM) {
712 // All defs/phis from outside BB that are used in BB, are valid uses in P1.
713 // Since those defs/phis must have dominated BB, and also dominate P1.
714 // Defs from BB being used in BB will be replaced with the cloned defs from
715 // VM. The uses of BB's Phi (if it exists) in BB will be replaced by the
716 // incoming def into the Phi from P1.
Alina Sbirlea7a0098a2019-06-17 18:58:40 +0000717 // Instructions cloned into the predecessor are in practice sometimes
718 // simplified, so disable the use of the template, and create an access from
719 // scratch.
Alina Sbirlea79800992018-09-10 20:13:01 +0000720 PhiToDefMap MPhiMap;
721 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(BB))
722 MPhiMap[MPhi] = MPhi->getIncomingValueForBlock(P1);
Alina Sbirlea7a0098a2019-06-17 18:58:40 +0000723 cloneUsesAndDefs(BB, P1, VM, MPhiMap, /*CloneWasSimplified=*/true);
Alina Sbirlea79800992018-09-10 20:13:01 +0000724}
725
726template <typename Iter>
727void MemorySSAUpdater::privateUpdateExitBlocksForClonedLoop(
728 ArrayRef<BasicBlock *> ExitBlocks, Iter ValuesBegin, Iter ValuesEnd,
729 DominatorTree &DT) {
730 SmallVector<CFGUpdate, 4> Updates;
731 // Update/insert phis in all successors of exit blocks.
732 for (auto *Exit : ExitBlocks)
733 for (const ValueToValueMapTy *VMap : make_range(ValuesBegin, ValuesEnd))
734 if (BasicBlock *NewExit = cast_or_null<BasicBlock>(VMap->lookup(Exit))) {
735 BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
736 Updates.push_back({DT.Insert, NewExit, ExitSucc});
737 }
738 applyInsertUpdates(Updates, DT);
739}
740
741void MemorySSAUpdater::updateExitBlocksForClonedLoop(
742 ArrayRef<BasicBlock *> ExitBlocks, const ValueToValueMapTy &VMap,
743 DominatorTree &DT) {
744 const ValueToValueMapTy *const Arr[] = {&VMap};
745 privateUpdateExitBlocksForClonedLoop(ExitBlocks, std::begin(Arr),
746 std::end(Arr), DT);
747}
748
749void MemorySSAUpdater::updateExitBlocksForClonedLoop(
750 ArrayRef<BasicBlock *> ExitBlocks,
751 ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps, DominatorTree &DT) {
752 auto GetPtr = [&](const std::unique_ptr<ValueToValueMapTy> &I) {
753 return I.get();
754 };
755 using MappedIteratorType =
756 mapped_iterator<const std::unique_ptr<ValueToValueMapTy> *,
757 decltype(GetPtr)>;
758 auto MapBegin = MappedIteratorType(VMaps.begin(), GetPtr);
759 auto MapEnd = MappedIteratorType(VMaps.end(), GetPtr);
760 privateUpdateExitBlocksForClonedLoop(ExitBlocks, MapBegin, MapEnd, DT);
761}
762
763void MemorySSAUpdater::applyUpdates(ArrayRef<CFGUpdate> Updates,
764 DominatorTree &DT) {
765 SmallVector<CFGUpdate, 4> RevDeleteUpdates;
766 SmallVector<CFGUpdate, 4> InsertUpdates;
767 for (auto &Update : Updates) {
768 if (Update.getKind() == DT.Insert)
769 InsertUpdates.push_back({DT.Insert, Update.getFrom(), Update.getTo()});
770 else
771 RevDeleteUpdates.push_back({DT.Insert, Update.getFrom(), Update.getTo()});
772 }
773
774 if (!RevDeleteUpdates.empty()) {
775 // Update for inserted edges: use newDT and snapshot CFG as if deletes had
Hiroshi Inoue02a2bb22019-02-05 08:30:48 +0000776 // not occurred.
Alina Sbirlea79800992018-09-10 20:13:01 +0000777 // FIXME: This creates a new DT, so it's more expensive to do mix
778 // delete/inserts vs just inserts. We can do an incremental update on the DT
779 // to revert deletes, than re-delete the edges. Teaching DT to do this, is
780 // part of a pending cleanup.
781 DominatorTree NewDT(DT, RevDeleteUpdates);
782 GraphDiff<BasicBlock *> GD(RevDeleteUpdates);
783 applyInsertUpdates(InsertUpdates, NewDT, &GD);
784 } else {
785 GraphDiff<BasicBlock *> GD;
786 applyInsertUpdates(InsertUpdates, DT, &GD);
787 }
788
789 // Update for deleted edges
790 for (auto &Update : RevDeleteUpdates)
791 removeEdge(Update.getFrom(), Update.getTo());
792}
793
794void MemorySSAUpdater::applyInsertUpdates(ArrayRef<CFGUpdate> Updates,
795 DominatorTree &DT) {
796 GraphDiff<BasicBlock *> GD;
797 applyInsertUpdates(Updates, DT, &GD);
798}
799
800void MemorySSAUpdater::applyInsertUpdates(ArrayRef<CFGUpdate> Updates,
801 DominatorTree &DT,
802 const GraphDiff<BasicBlock *> *GD) {
803 // Get recursive last Def, assuming well formed MSSA and updated DT.
804 auto GetLastDef = [&](BasicBlock *BB) -> MemoryAccess * {
805 while (true) {
806 MemorySSA::DefsList *Defs = MSSA->getWritableBlockDefs(BB);
807 // Return last Def or Phi in BB, if it exists.
808 if (Defs)
809 return &*(--Defs->end());
810
811 // Check number of predecessors, we only care if there's more than one.
812 unsigned Count = 0;
813 BasicBlock *Pred = nullptr;
814 for (auto &Pair : children<GraphDiffInvBBPair>({GD, BB})) {
815 Pred = Pair.second;
816 Count++;
817 if (Count == 2)
818 break;
819 }
820
821 // If BB has multiple predecessors, get last definition from IDom.
822 if (Count != 1) {
823 // [SimpleLoopUnswitch] If BB is a dead block, about to be deleted, its
824 // DT is invalidated. Return LoE as its last def. This will be added to
825 // MemoryPhi node, and later deleted when the block is deleted.
826 if (!DT.getNode(BB))
827 return MSSA->getLiveOnEntryDef();
828 if (auto *IDom = DT.getNode(BB)->getIDom())
829 if (IDom->getBlock() != BB) {
830 BB = IDom->getBlock();
831 continue;
832 }
833 return MSSA->getLiveOnEntryDef();
834 } else {
835 // Single predecessor, BB cannot be dead. GetLastDef of Pred.
836 assert(Count == 1 && Pred && "Single predecessor expected.");
837 BB = Pred;
838 }
839 };
840 llvm_unreachable("Unable to get last definition.");
841 };
842
843 // Get nearest IDom given a set of blocks.
844 // TODO: this can be optimized by starting the search at the node with the
845 // lowest level (highest in the tree).
846 auto FindNearestCommonDominator =
847 [&](const SmallSetVector<BasicBlock *, 2> &BBSet) -> BasicBlock * {
848 BasicBlock *PrevIDom = *BBSet.begin();
849 for (auto *BB : BBSet)
850 PrevIDom = DT.findNearestCommonDominator(PrevIDom, BB);
851 return PrevIDom;
852 };
853
854 // Get all blocks that dominate PrevIDom, stop when reaching CurrIDom. Do not
855 // include CurrIDom.
856 auto GetNoLongerDomBlocks =
857 [&](BasicBlock *PrevIDom, BasicBlock *CurrIDom,
858 SmallVectorImpl<BasicBlock *> &BlocksPrevDom) {
859 if (PrevIDom == CurrIDom)
860 return;
861 BlocksPrevDom.push_back(PrevIDom);
862 BasicBlock *NextIDom = PrevIDom;
863 while (BasicBlock *UpIDom =
864 DT.getNode(NextIDom)->getIDom()->getBlock()) {
865 if (UpIDom == CurrIDom)
866 break;
867 BlocksPrevDom.push_back(UpIDom);
868 NextIDom = UpIDom;
869 }
870 };
871
872 // Map a BB to its predecessors: added + previously existing. To get a
873 // deterministic order, store predecessors as SetVectors. The order in each
Hiroshi Inoue02a2bb22019-02-05 08:30:48 +0000874 // will be defined by the order in Updates (fixed) and the order given by
Alina Sbirlea79800992018-09-10 20:13:01 +0000875 // children<> (also fixed). Since we further iterate over these ordered sets,
876 // we lose the information of multiple edges possibly existing between two
877 // blocks, so we'll keep and EdgeCount map for that.
878 // An alternate implementation could keep unordered set for the predecessors,
879 // traverse either Updates or children<> each time to get the deterministic
880 // order, and drop the usage of EdgeCount. This alternate approach would still
881 // require querying the maps for each predecessor, and children<> call has
882 // additional computation inside for creating the snapshot-graph predecessors.
883 // As such, we favor using a little additional storage and less compute time.
884 // This decision can be revisited if we find the alternative more favorable.
885
886 struct PredInfo {
887 SmallSetVector<BasicBlock *, 2> Added;
888 SmallSetVector<BasicBlock *, 2> Prev;
889 };
890 SmallDenseMap<BasicBlock *, PredInfo> PredMap;
891
892 for (auto &Edge : Updates) {
893 BasicBlock *BB = Edge.getTo();
894 auto &AddedBlockSet = PredMap[BB].Added;
895 AddedBlockSet.insert(Edge.getFrom());
896 }
897
898 // Store all existing predecessor for each BB, at least one must exist.
899 SmallDenseMap<std::pair<BasicBlock *, BasicBlock *>, int> EdgeCountMap;
900 SmallPtrSet<BasicBlock *, 2> NewBlocks;
901 for (auto &BBPredPair : PredMap) {
902 auto *BB = BBPredPair.first;
903 const auto &AddedBlockSet = BBPredPair.second.Added;
904 auto &PrevBlockSet = BBPredPair.second.Prev;
905 for (auto &Pair : children<GraphDiffInvBBPair>({GD, BB})) {
906 BasicBlock *Pi = Pair.second;
907 if (!AddedBlockSet.count(Pi))
908 PrevBlockSet.insert(Pi);
909 EdgeCountMap[{Pi, BB}]++;
910 }
911
912 if (PrevBlockSet.empty()) {
913 assert(pred_size(BB) == AddedBlockSet.size() && "Duplicate edges added.");
914 LLVM_DEBUG(
915 dbgs()
916 << "Adding a predecessor to a block with no predecessors. "
917 "This must be an edge added to a new, likely cloned, block. "
918 "Its memory accesses must be already correct, assuming completed "
919 "via the updateExitBlocksForClonedLoop API. "
920 "Assert a single such edge is added so no phi addition or "
921 "additional processing is required.\n");
922 assert(AddedBlockSet.size() == 1 &&
923 "Can only handle adding one predecessor to a new block.");
924 // Need to remove new blocks from PredMap. Remove below to not invalidate
925 // iterator here.
926 NewBlocks.insert(BB);
927 }
928 }
929 // Nothing to process for new/cloned blocks.
930 for (auto *BB : NewBlocks)
931 PredMap.erase(BB);
932
Alina Sbirlea79800992018-09-10 20:13:01 +0000933 SmallVector<BasicBlock *, 16> BlocksWithDefsToReplace;
Alina Sbirleacb4ed8a2019-06-11 19:09:34 +0000934 SmallVector<WeakVH, 8> InsertedPhis;
Alina Sbirlea79800992018-09-10 20:13:01 +0000935
936 // First create MemoryPhis in all blocks that don't have one. Create in the
937 // order found in Updates, not in PredMap, to get deterministic numbering.
938 for (auto &Edge : Updates) {
939 BasicBlock *BB = Edge.getTo();
940 if (PredMap.count(BB) && !MSSA->getMemoryAccess(BB))
Alina Sbirleacb4ed8a2019-06-11 19:09:34 +0000941 InsertedPhis.push_back(MSSA->createMemoryPhi(BB));
Alina Sbirlea79800992018-09-10 20:13:01 +0000942 }
943
944 // Now we'll fill in the MemoryPhis with the right incoming values.
945 for (auto &BBPredPair : PredMap) {
946 auto *BB = BBPredPair.first;
947 const auto &PrevBlockSet = BBPredPair.second.Prev;
948 const auto &AddedBlockSet = BBPredPair.second.Added;
949 assert(!PrevBlockSet.empty() &&
950 "At least one previous predecessor must exist.");
951
952 // TODO: if this becomes a bottleneck, we can save on GetLastDef calls by
953 // keeping this map before the loop. We can reuse already populated entries
954 // if an edge is added from the same predecessor to two different blocks,
955 // and this does happen in rotate. Note that the map needs to be updated
956 // when deleting non-necessary phis below, if the phi is in the map by
957 // replacing the value with DefP1.
958 SmallDenseMap<BasicBlock *, MemoryAccess *> LastDefAddedPred;
959 for (auto *AddedPred : AddedBlockSet) {
960 auto *DefPn = GetLastDef(AddedPred);
961 assert(DefPn != nullptr && "Unable to find last definition.");
962 LastDefAddedPred[AddedPred] = DefPn;
963 }
964
965 MemoryPhi *NewPhi = MSSA->getMemoryAccess(BB);
966 // If Phi is not empty, add an incoming edge from each added pred. Must
967 // still compute blocks with defs to replace for this block below.
968 if (NewPhi->getNumOperands()) {
969 for (auto *Pred : AddedBlockSet) {
970 auto *LastDefForPred = LastDefAddedPred[Pred];
971 for (int I = 0, E = EdgeCountMap[{Pred, BB}]; I < E; ++I)
972 NewPhi->addIncoming(LastDefForPred, Pred);
973 }
974 } else {
975 // Pick any existing predecessor and get its definition. All other
976 // existing predecessors should have the same one, since no phi existed.
977 auto *P1 = *PrevBlockSet.begin();
978 MemoryAccess *DefP1 = GetLastDef(P1);
979
980 // Check DefP1 against all Defs in LastDefPredPair. If all the same,
981 // nothing to add.
982 bool InsertPhi = false;
983 for (auto LastDefPredPair : LastDefAddedPred)
984 if (DefP1 != LastDefPredPair.second) {
985 InsertPhi = true;
986 break;
987 }
988 if (!InsertPhi) {
989 // Since NewPhi may be used in other newly added Phis, replace all uses
990 // of NewPhi with the definition coming from all predecessors (DefP1),
991 // before deleting it.
992 NewPhi->replaceAllUsesWith(DefP1);
993 removeMemoryAccess(NewPhi);
994 continue;
995 }
996
997 // Update Phi with new values for new predecessors and old value for all
998 // other predecessors. Since AddedBlockSet and PrevBlockSet are ordered
999 // sets, the order of entries in NewPhi is deterministic.
1000 for (auto *Pred : AddedBlockSet) {
1001 auto *LastDefForPred = LastDefAddedPred[Pred];
1002 for (int I = 0, E = EdgeCountMap[{Pred, BB}]; I < E; ++I)
1003 NewPhi->addIncoming(LastDefForPred, Pred);
1004 }
1005 for (auto *Pred : PrevBlockSet)
1006 for (int I = 0, E = EdgeCountMap[{Pred, BB}]; I < E; ++I)
1007 NewPhi->addIncoming(DefP1, Pred);
Alina Sbirlea79800992018-09-10 20:13:01 +00001008 }
1009
1010 // Get all blocks that used to dominate BB and no longer do after adding
1011 // AddedBlockSet, where PrevBlockSet are the previously known predecessors.
1012 assert(DT.getNode(BB)->getIDom() && "BB does not have valid idom");
1013 BasicBlock *PrevIDom = FindNearestCommonDominator(PrevBlockSet);
1014 assert(PrevIDom && "Previous IDom should exists");
1015 BasicBlock *NewIDom = DT.getNode(BB)->getIDom()->getBlock();
1016 assert(NewIDom && "BB should have a new valid idom");
1017 assert(DT.dominates(NewIDom, PrevIDom) &&
1018 "New idom should dominate old idom");
1019 GetNoLongerDomBlocks(PrevIDom, NewIDom, BlocksWithDefsToReplace);
1020 }
1021
Alina Sbirlea109d2ea2019-06-19 21:33:09 +00001022 tryRemoveTrivialPhis(InsertedPhis);
1023 // Create the set of blocks that now have a definition. We'll use this to
1024 // compute IDF and add Phis there next.
1025 SmallVector<BasicBlock *, 8> BlocksToProcess;
1026 for (auto &VH : InsertedPhis)
1027 if (auto *MPhi = cast_or_null<MemoryPhi>(VH))
1028 BlocksToProcess.push_back(MPhi->getBlock());
1029
Alina Sbirlea79800992018-09-10 20:13:01 +00001030 // Compute IDF and add Phis in all IDF blocks that do not have one.
1031 SmallVector<BasicBlock *, 32> IDFBlocks;
1032 if (!BlocksToProcess.empty()) {
Alina Sbirlea238b8e62019-06-19 21:17:31 +00001033 ForwardIDFCalculator IDFs(DT, GD);
Alina Sbirlea79800992018-09-10 20:13:01 +00001034 SmallPtrSet<BasicBlock *, 16> DefiningBlocks(BlocksToProcess.begin(),
1035 BlocksToProcess.end());
1036 IDFs.setDefiningBlocks(DefiningBlocks);
1037 IDFs.calculate(IDFBlocks);
Alina Sbirlea05f77802019-06-17 18:16:53 +00001038
1039 SmallSetVector<MemoryPhi *, 4> PhisToFill;
1040 // First create all needed Phis.
1041 for (auto *BBIDF : IDFBlocks)
1042 if (!MSSA->getMemoryAccess(BBIDF)) {
1043 auto *IDFPhi = MSSA->createMemoryPhi(BBIDF);
1044 InsertedPhis.push_back(IDFPhi);
1045 PhisToFill.insert(IDFPhi);
1046 }
1047 // Then update or insert their correct incoming values.
Alina Sbirlea79800992018-09-10 20:13:01 +00001048 for (auto *BBIDF : IDFBlocks) {
Alina Sbirlea05f77802019-06-17 18:16:53 +00001049 auto *IDFPhi = MSSA->getMemoryAccess(BBIDF);
1050 assert(IDFPhi && "Phi must exist");
1051 if (!PhisToFill.count(IDFPhi)) {
Alina Sbirlea79800992018-09-10 20:13:01 +00001052 // Update existing Phi.
1053 // FIXME: some updates may be redundant, try to optimize and skip some.
1054 for (unsigned I = 0, E = IDFPhi->getNumIncomingValues(); I < E; ++I)
1055 IDFPhi->setIncomingValue(I, GetLastDef(IDFPhi->getIncomingBlock(I)));
1056 } else {
Alina Sbirlea79800992018-09-10 20:13:01 +00001057 for (auto &Pair : children<GraphDiffInvBBPair>({GD, BBIDF})) {
1058 BasicBlock *Pi = Pair.second;
1059 IDFPhi->addIncoming(GetLastDef(Pi), Pi);
1060 }
1061 }
1062 }
1063 }
1064
1065 // Now for all defs in BlocksWithDefsToReplace, if there are uses they no
1066 // longer dominate, replace those with the closest dominating def.
1067 // This will also update optimized accesses, as they're also uses.
1068 for (auto *BlockWithDefsToReplace : BlocksWithDefsToReplace) {
1069 if (auto DefsList = MSSA->getWritableBlockDefs(BlockWithDefsToReplace)) {
1070 for (auto &DefToReplaceUses : *DefsList) {
1071 BasicBlock *DominatingBlock = DefToReplaceUses.getBlock();
1072 Value::use_iterator UI = DefToReplaceUses.use_begin(),
1073 E = DefToReplaceUses.use_end();
1074 for (; UI != E;) {
1075 Use &U = *UI;
1076 ++UI;
1077 MemoryAccess *Usr = dyn_cast<MemoryAccess>(U.getUser());
1078 if (MemoryPhi *UsrPhi = dyn_cast<MemoryPhi>(Usr)) {
1079 BasicBlock *DominatedBlock = UsrPhi->getIncomingBlock(U);
1080 if (!DT.dominates(DominatingBlock, DominatedBlock))
1081 U.set(GetLastDef(DominatedBlock));
1082 } else {
1083 BasicBlock *DominatedBlock = Usr->getBlock();
1084 if (!DT.dominates(DominatingBlock, DominatedBlock)) {
1085 if (auto *DomBlPhi = MSSA->getMemoryAccess(DominatedBlock))
1086 U.set(DomBlPhi);
1087 else {
1088 auto *IDom = DT.getNode(DominatedBlock)->getIDom();
1089 assert(IDom && "Block must have a valid IDom.");
1090 U.set(GetLastDef(IDom->getBlock()));
1091 }
1092 cast<MemoryUseOrDef>(Usr)->resetOptimized();
1093 }
1094 }
1095 }
1096 }
1097 }
1098 }
Alina Sbirleacb4ed8a2019-06-11 19:09:34 +00001099 tryRemoveTrivialPhis(InsertedPhis);
Alina Sbirlea79800992018-09-10 20:13:01 +00001100}
1101
Daniel Berlinae6b8b62017-01-28 01:35:02 +00001102// Move What before Where in the MemorySSA IR.
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001103template <class WhereType>
Daniel Berlinae6b8b62017-01-28 01:35:02 +00001104void MemorySSAUpdater::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001105 WhereType Where) {
Zhaoshi Zheng43af17b2018-04-09 20:55:37 +00001106 // Mark MemoryPhi users of What not to be optimized.
1107 for (auto *U : What->users())
George Burgess IVe7cdb7e2018-07-12 21:56:31 +00001108 if (MemoryPhi *PhiUser = dyn_cast<MemoryPhi>(U))
Zhaoshi Zheng43af17b2018-04-09 20:55:37 +00001109 NonOptPhis.insert(PhiUser);
1110
Daniel Berlinae6b8b62017-01-28 01:35:02 +00001111 // Replace all our users with our defining access.
1112 What->replaceAllUsesWith(What->getDefiningAccess());
1113
1114 // Let MemorySSA take care of moving it around in the lists.
1115 MSSA->moveTo(What, BB, Where);
1116
1117 // Now reinsert it into the IR and do whatever fixups needed.
1118 if (auto *MD = dyn_cast<MemoryDef>(What))
Alina Sbirlea1a3fdaf2019-08-19 18:57:40 +00001119 insertDef(MD, /*RenameUses=*/true);
Daniel Berlinae6b8b62017-01-28 01:35:02 +00001120 else
Alina Sbirlea1a3fdaf2019-08-19 18:57:40 +00001121 insertUse(cast<MemoryUse>(What), /*RenameUses=*/true);
Zhaoshi Zheng43af17b2018-04-09 20:55:37 +00001122
1123 // Clear dangling pointers. We added all MemoryPhi users, but not all
1124 // of them are removed by fixupDefs().
1125 NonOptPhis.clear();
Daniel Berlinae6b8b62017-01-28 01:35:02 +00001126}
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001127
Daniel Berlinae6b8b62017-01-28 01:35:02 +00001128// Move What before Where in the MemorySSA IR.
1129void MemorySSAUpdater::moveBefore(MemoryUseOrDef *What, MemoryUseOrDef *Where) {
1130 moveTo(What, Where->getBlock(), Where->getIterator());
1131}
1132
1133// Move What after Where in the MemorySSA IR.
1134void MemorySSAUpdater::moveAfter(MemoryUseOrDef *What, MemoryUseOrDef *Where) {
1135 moveTo(What, Where->getBlock(), ++Where->getIterator());
1136}
1137
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001138void MemorySSAUpdater::moveToPlace(MemoryUseOrDef *What, BasicBlock *BB,
1139 MemorySSA::InsertionPlace Where) {
1140 return moveTo(What, BB, Where);
1141}
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001142
Alina Sbirlea0f533552018-07-11 22:11:46 +00001143// All accesses in To used to be in From. Move to end and update access lists.
1144void MemorySSAUpdater::moveAllAccesses(BasicBlock *From, BasicBlock *To,
1145 Instruction *Start) {
1146
1147 MemorySSA::AccessList *Accs = MSSA->getWritableBlockAccesses(From);
1148 if (!Accs)
1149 return;
1150
1151 MemoryAccess *FirstInNew = nullptr;
1152 for (Instruction &I : make_range(Start->getIterator(), To->end()))
1153 if ((FirstInNew = MSSA->getMemoryAccess(&I)))
1154 break;
1155 if (!FirstInNew)
1156 return;
1157
1158 auto *MUD = cast<MemoryUseOrDef>(FirstInNew);
1159 do {
1160 auto NextIt = ++MUD->getIterator();
1161 MemoryUseOrDef *NextMUD = (!Accs || NextIt == Accs->end())
1162 ? nullptr
1163 : cast<MemoryUseOrDef>(&*NextIt);
1164 MSSA->moveTo(MUD, To, MemorySSA::End);
1165 // Moving MUD from Accs in the moveTo above, may delete Accs, so we need to
1166 // retrieve it again.
1167 Accs = MSSA->getWritableBlockAccesses(From);
1168 MUD = NextMUD;
1169 } while (MUD);
1170}
1171
1172void MemorySSAUpdater::moveAllAfterSpliceBlocks(BasicBlock *From,
1173 BasicBlock *To,
1174 Instruction *Start) {
1175 assert(MSSA->getBlockAccesses(To) == nullptr &&
1176 "To block is expected to be free of MemoryAccesses.");
1177 moveAllAccesses(From, To, Start);
1178 for (BasicBlock *Succ : successors(To))
1179 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(Succ))
1180 MPhi->setIncomingBlock(MPhi->getBasicBlockIndex(From), To);
1181}
1182
1183void MemorySSAUpdater::moveAllAfterMergeBlocks(BasicBlock *From, BasicBlock *To,
1184 Instruction *Start) {
1185 assert(From->getSinglePredecessor() == To &&
1186 "From block is expected to have a single predecessor (To).");
1187 moveAllAccesses(From, To, Start);
1188 for (BasicBlock *Succ : successors(From))
1189 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(Succ))
1190 MPhi->setIncomingBlock(MPhi->getBasicBlockIndex(From), To);
1191}
1192
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001193/// If all arguments of a MemoryPHI are defined by the same incoming
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001194/// argument, return that argument.
1195static MemoryAccess *onlySingleValue(MemoryPhi *MP) {
1196 MemoryAccess *MA = nullptr;
1197
1198 for (auto &Arg : MP->operands()) {
1199 if (!MA)
1200 MA = cast<MemoryAccess>(Arg);
1201 else if (MA != Arg)
1202 return nullptr;
1203 }
1204 return MA;
1205}
George Burgess IV56169ed2017-04-21 04:54:52 +00001206
Alina Sbirlea20c29622018-07-20 17:13:05 +00001207void MemorySSAUpdater::wireOldPredecessorsToNewImmediatePredecessor(
Alina Sbirleaf98c2c52018-09-07 21:14:48 +00001208 BasicBlock *Old, BasicBlock *New, ArrayRef<BasicBlock *> Preds,
1209 bool IdenticalEdgesWereMerged) {
Alina Sbirlea20c29622018-07-20 17:13:05 +00001210 assert(!MSSA->getWritableBlockAccesses(New) &&
1211 "Access list should be null for a new block.");
1212 MemoryPhi *Phi = MSSA->getMemoryAccess(Old);
1213 if (!Phi)
1214 return;
Vedant Kumar4de31bb2018-11-19 19:54:27 +00001215 if (Old->hasNPredecessors(1)) {
Alina Sbirlea20c29622018-07-20 17:13:05 +00001216 assert(pred_size(New) == Preds.size() &&
1217 "Should have moved all predecessors.");
1218 MSSA->moveTo(Phi, New, MemorySSA::Beginning);
1219 } else {
1220 assert(!Preds.empty() && "Must be moving at least one predecessor to the "
1221 "new immediate predecessor.");
1222 MemoryPhi *NewPhi = MSSA->createMemoryPhi(New);
1223 SmallPtrSet<BasicBlock *, 16> PredsSet(Preds.begin(), Preds.end());
Alina Sbirleaf98c2c52018-09-07 21:14:48 +00001224 // Currently only support the case of removing a single incoming edge when
1225 // identical edges were not merged.
1226 if (!IdenticalEdgesWereMerged)
1227 assert(PredsSet.size() == Preds.size() &&
1228 "If identical edges were not merged, we cannot have duplicate "
1229 "blocks in the predecessors");
Alina Sbirlea20c29622018-07-20 17:13:05 +00001230 Phi->unorderedDeleteIncomingIf([&](MemoryAccess *MA, BasicBlock *B) {
1231 if (PredsSet.count(B)) {
1232 NewPhi->addIncoming(MA, B);
Alina Sbirleaf98c2c52018-09-07 21:14:48 +00001233 if (!IdenticalEdgesWereMerged)
1234 PredsSet.erase(B);
Alina Sbirlea20c29622018-07-20 17:13:05 +00001235 return true;
1236 }
1237 return false;
1238 });
1239 Phi->addIncoming(NewPhi, New);
Alina Sbirlea28637212019-08-20 22:47:58 +00001240 tryRemoveTrivialPhi(NewPhi);
Alina Sbirlea20c29622018-07-20 17:13:05 +00001241 }
1242}
1243
Alina Sbirlea240a90a2019-01-31 20:13:47 +00001244void MemorySSAUpdater::removeMemoryAccess(MemoryAccess *MA, bool OptimizePhis) {
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001245 assert(!MSSA->isLiveOnEntryDef(MA) &&
1246 "Trying to remove the live on entry def");
1247 // We can only delete phi nodes if they have no uses, or we can replace all
1248 // uses with a single definition.
1249 MemoryAccess *NewDefTarget = nullptr;
1250 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) {
1251 // Note that it is sufficient to know that all edges of the phi node have
1252 // the same argument. If they do, by the definition of dominance frontiers
1253 // (which we used to place this phi), that argument must dominate this phi,
1254 // and thus, must dominate the phi's uses, and so we will not hit the assert
1255 // below.
1256 NewDefTarget = onlySingleValue(MP);
1257 assert((NewDefTarget || MP->use_empty()) &&
1258 "We can't delete this memory phi");
1259 } else {
1260 NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess();
1261 }
1262
Alina Sbirlea240a90a2019-01-31 20:13:47 +00001263 SmallSetVector<MemoryPhi *, 4> PhisToCheck;
1264
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001265 // Re-point the uses at our defining access
1266 if (!isa<MemoryUse>(MA) && !MA->use_empty()) {
1267 // Reset optimized on users of this store, and reset the uses.
1268 // A few notes:
1269 // 1. This is a slightly modified version of RAUW to avoid walking the
1270 // uses twice here.
1271 // 2. If we wanted to be complete, we would have to reset the optimized
1272 // flags on users of phi nodes if doing the below makes a phi node have all
1273 // the same arguments. Instead, we prefer users to removeMemoryAccess those
1274 // phi nodes, because doing it here would be N^3.
1275 if (MA->hasValueHandle())
1276 ValueHandleBase::ValueIsRAUWd(MA, NewDefTarget);
1277 // Note: We assume MemorySSA is not used in metadata since it's not really
1278 // part of the IR.
1279
1280 while (!MA->use_empty()) {
1281 Use &U = *MA->use_begin();
Daniel Berline33bc312017-04-04 23:43:10 +00001282 if (auto *MUD = dyn_cast<MemoryUseOrDef>(U.getUser()))
1283 MUD->resetOptimized();
Alina Sbirlea240a90a2019-01-31 20:13:47 +00001284 if (OptimizePhis)
1285 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(U.getUser()))
1286 PhisToCheck.insert(MP);
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001287 U.set(NewDefTarget);
1288 }
1289 }
1290
1291 // The call below to erase will destroy MA, so we can't change the order we
1292 // are doing things here
1293 MSSA->removeFromLookups(MA);
1294 MSSA->removeFromLists(MA);
Alina Sbirlea240a90a2019-01-31 20:13:47 +00001295
1296 // Optionally optimize Phi uses. This will recursively remove trivial phis.
1297 if (!PhisToCheck.empty()) {
1298 SmallVector<WeakVH, 16> PhisToOptimize{PhisToCheck.begin(),
1299 PhisToCheck.end()};
1300 PhisToCheck.clear();
1301
1302 unsigned PhisSize = PhisToOptimize.size();
1303 while (PhisSize-- > 0)
1304 if (MemoryPhi *MP =
Alina Sbirlea28637212019-08-20 22:47:58 +00001305 cast_or_null<MemoryPhi>(PhisToOptimize.pop_back_val()))
1306 tryRemoveTrivialPhi(MP);
Alina Sbirlea240a90a2019-01-31 20:13:47 +00001307 }
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001308}
1309
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001310void MemorySSAUpdater::removeBlocks(
Alina Sbirleadb101862019-07-12 22:30:30 +00001311 const SmallSetVector<BasicBlock *, 8> &DeadBlocks) {
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001312 // First delete all uses of BB in MemoryPhis.
1313 for (BasicBlock *BB : DeadBlocks) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00001314 Instruction *TI = BB->getTerminator();
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001315 assert(TI && "Basic block expected to have a terminator instruction");
Chandler Carruth96fc1de2018-08-26 08:41:15 +00001316 for (BasicBlock *Succ : successors(TI))
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001317 if (!DeadBlocks.count(Succ))
1318 if (MemoryPhi *MP = MSSA->getMemoryAccess(Succ)) {
1319 MP->unorderedDeleteIncomingBlock(BB);
Alina Sbirlea28637212019-08-20 22:47:58 +00001320 tryRemoveTrivialPhi(MP);
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001321 }
1322 // Drop all references of all accesses in BB
1323 if (MemorySSA::AccessList *Acc = MSSA->getWritableBlockAccesses(BB))
1324 for (MemoryAccess &MA : *Acc)
1325 MA.dropAllReferences();
1326 }
1327
1328 // Next, delete all memory accesses in each block
1329 for (BasicBlock *BB : DeadBlocks) {
1330 MemorySSA::AccessList *Acc = MSSA->getWritableBlockAccesses(BB);
1331 if (!Acc)
1332 continue;
1333 for (auto AB = Acc->begin(), AE = Acc->end(); AB != AE;) {
1334 MemoryAccess *MA = &*AB;
1335 ++AB;
1336 MSSA->removeFromLookups(MA);
1337 MSSA->removeFromLists(MA);
1338 }
1339 }
1340}
1341
Alina Sbirlea151ab482019-05-02 23:12:49 +00001342void MemorySSAUpdater::tryRemoveTrivialPhis(ArrayRef<WeakVH> UpdatedPHIs) {
1343 for (auto &VH : UpdatedPHIs)
Alina Sbirlea28637212019-08-20 22:47:58 +00001344 if (auto *MPhi = cast_or_null<MemoryPhi>(VH))
1345 tryRemoveTrivialPhi(MPhi);
Alina Sbirlea151ab482019-05-02 23:12:49 +00001346}
1347
Alina Sbirleaf31eba62019-05-08 17:05:36 +00001348void MemorySSAUpdater::changeToUnreachable(const Instruction *I) {
1349 const BasicBlock *BB = I->getParent();
1350 // Remove memory accesses in BB for I and all following instructions.
1351 auto BBI = I->getIterator(), BBE = BB->end();
1352 // FIXME: If this becomes too expensive, iterate until the first instruction
1353 // with a memory access, then iterate over MemoryAccesses.
1354 while (BBI != BBE)
1355 removeMemoryAccess(&*(BBI++));
1356 // Update phis in BB's successors to remove BB.
1357 SmallVector<WeakVH, 16> UpdatedPHIs;
1358 for (const BasicBlock *Successor : successors(BB)) {
1359 removeDuplicatePhiEdgesBetween(BB, Successor);
1360 if (MemoryPhi *MPhi = MSSA->getMemoryAccess(Successor)) {
1361 MPhi->unorderedDeleteIncomingBlock(BB);
1362 UpdatedPHIs.push_back(MPhi);
1363 }
1364 }
1365 // Optimize trivial phis.
1366 tryRemoveTrivialPhis(UpdatedPHIs);
1367}
1368
1369void MemorySSAUpdater::changeCondBranchToUnconditionalTo(const BranchInst *BI,
1370 const BasicBlock *To) {
1371 const BasicBlock *BB = BI->getParent();
1372 SmallVector<WeakVH, 16> UpdatedPHIs;
1373 for (const BasicBlock *Succ : successors(BB)) {
1374 removeDuplicatePhiEdgesBetween(BB, Succ);
1375 if (Succ != To)
1376 if (auto *MPhi = MSSA->getMemoryAccess(Succ)) {
1377 MPhi->unorderedDeleteIncomingBlock(BB);
1378 UpdatedPHIs.push_back(MPhi);
1379 }
1380 }
1381 // Optimize trivial phis.
1382 tryRemoveTrivialPhis(UpdatedPHIs);
1383}
1384
Daniel Berlin17e8d0e2017-02-22 22:19:55 +00001385MemoryAccess *MemorySSAUpdater::createMemoryAccessInBB(
1386 Instruction *I, MemoryAccess *Definition, const BasicBlock *BB,
1387 MemorySSA::InsertionPlace Point) {
1388 MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition);
1389 MSSA->insertIntoListsForBlock(NewAccess, BB, Point);
1390 return NewAccess;
1391}
1392
1393MemoryUseOrDef *MemorySSAUpdater::createMemoryAccessBefore(
1394 Instruction *I, MemoryAccess *Definition, MemoryUseOrDef *InsertPt) {
1395 assert(I->getParent() == InsertPt->getBlock() &&
1396 "New and old access must be in the same block");
1397 MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition);
1398 MSSA->insertIntoListsBefore(NewAccess, InsertPt->getBlock(),
1399 InsertPt->getIterator());
1400 return NewAccess;
1401}
1402
1403MemoryUseOrDef *MemorySSAUpdater::createMemoryAccessAfter(
1404 Instruction *I, MemoryAccess *Definition, MemoryAccess *InsertPt) {
1405 assert(I->getParent() == InsertPt->getBlock() &&
1406 "New and old access must be in the same block");
1407 MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition);
1408 MSSA->insertIntoListsBefore(NewAccess, InsertPt->getBlock(),
1409 ++InsertPt->getIterator());
1410 return NewAccess;
1411}