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