1 //===-- MemorySSAUpdater.cpp - Memory SSA Updater--------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------===//
9 // This file implements the MemorySSAUpdater class.
11 //===----------------------------------------------------------------===//
12 #include "llvm/Analysis/MemorySSAUpdater.h"
13 #include "llvm/ADT/STLExtras.h"
14 #include "llvm/ADT/SetVector.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/Analysis/IteratedDominanceFrontier.h"
17 #include "llvm/Analysis/MemorySSA.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/Dominators.h"
20 #include "llvm/IR/GlobalVariable.h"
21 #include "llvm/IR/IRBuilder.h"
22 #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"
29 #define DEBUG_TYPE "memoryssa"
32 // 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.
41 MemoryAccess
*MemorySSAUpdater::getPreviousDefRecursive(
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
;
51 if (BasicBlock
*Pred
= BB
->getSinglePredecessor()) {
52 // Single predecessor case, just recurse, we can only have one definition.
53 MemoryAccess
*Result
= getPreviousDefFromEnd(Pred
, CachedPreviousDef
);
54 CachedPreviousDef
.insert({BB
, Result
});
58 if (VisitedBlocks
.count(BB
)) {
59 // 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.
62 MemoryAccess
*Result
= MSSA
->createMemoryPhi(BB
);
63 CachedPreviousDef
.insert({BB
, Result
});
67 if (VisitedBlocks
.insert(BB
).second
) {
68 // Mark us visited so we can detect a cycle
69 SmallVector
<TrackingVH
<MemoryAccess
>, 8> PhiOps
;
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
))
75 if (MSSA
->DT
->isReachableFromEntry(Pred
))
76 PhiOps
.push_back(getPreviousDefFromEnd(Pred
, CachedPreviousDef
));
78 PhiOps
.push_back(MSSA
->getLiveOnEntryDef());
80 // Now try to simplify the ops to avoid placing a phi.
81 // This may return null if we never created a phi yet, that's okay
82 MemoryPhi
*Phi
= dyn_cast_or_null
<MemoryPhi
>(MSSA
->getMemoryAccess(BB
));
84 // See if we can avoid the phi by simplifying it.
85 auto *Result
= tryRemoveTrivialPhi(Phi
, PhiOps
);
86 // If we couldn't simplify, we may have to create a phi
89 Phi
= MSSA
->createMemoryPhi(BB
);
91 // See if the existing phi operands match what we need.
92 // Unlike normal SSA, we only allow one phi node per block, so we can't just
94 if (Phi
->getNumOperands() != 0) {
95 // FIXME: Figure out whether this is dead code and if so remove it.
96 if (!std::equal(Phi
->op_begin(), Phi
->op_end(), PhiOps
.begin())) {
97 // These will have been filled in by the recursive read we did above.
98 llvm::copy(PhiOps
, Phi
->op_begin());
99 std::copy(pred_begin(BB
), pred_end(BB
), Phi
->block_begin());
103 for (auto *Pred
: predecessors(BB
))
104 Phi
->addIncoming(&*PhiOps
[i
++], Pred
);
105 InsertedPHIs
.push_back(Phi
);
110 // Set ourselves up for the next variable by resetting visited state.
111 VisitedBlocks
.erase(BB
);
112 CachedPreviousDef
.insert({BB
, Result
});
115 llvm_unreachable("Should have hit one of the three cases above");
118 // This starts at the memory access, and goes backwards in the block to find the
119 // previous definition. If a definition is not found the block of the access,
120 // it continues globally, creating phi nodes to ensure we have a single
122 MemoryAccess
*MemorySSAUpdater::getPreviousDef(MemoryAccess
*MA
) {
123 if (auto *LocalResult
= getPreviousDefInBlock(MA
))
125 DenseMap
<BasicBlock
*, TrackingVH
<MemoryAccess
>> CachedPreviousDef
;
126 return getPreviousDefRecursive(MA
->getBlock(), CachedPreviousDef
);
129 // This starts at the memory access, and goes backwards in the block to the find
130 // the previous definition. If the definition is not found in the block of the
131 // access, it returns nullptr.
132 MemoryAccess
*MemorySSAUpdater::getPreviousDefInBlock(MemoryAccess
*MA
) {
133 auto *Defs
= MSSA
->getWritableBlockDefs(MA
->getBlock());
135 // It's possible there are no defs, or we got handed the first def to start.
137 // If this is a def, we can just use the def iterators.
138 if (!isa
<MemoryUse
>(MA
)) {
139 auto Iter
= MA
->getReverseDefsIterator();
141 if (Iter
!= Defs
->rend())
144 // Otherwise, have to walk the all access iterator.
145 auto End
= MSSA
->getWritableBlockAccesses(MA
->getBlock())->rend();
146 for (auto &U
: make_range(++MA
->getReverseIterator(), End
))
147 if (!isa
<MemoryUse
>(U
))
148 return cast
<MemoryAccess
>(&U
);
149 // Note that if MA comes before Defs->begin(), we won't hit a def.
156 // This starts at the end of block
157 MemoryAccess
*MemorySSAUpdater::getPreviousDefFromEnd(
159 DenseMap
<BasicBlock
*, TrackingVH
<MemoryAccess
>> &CachedPreviousDef
) {
160 auto *Defs
= MSSA
->getWritableBlockDefs(BB
);
163 CachedPreviousDef
.insert({BB
, &*Defs
->rbegin()});
164 return &*Defs
->rbegin();
167 return getPreviousDefRecursive(BB
, CachedPreviousDef
);
169 // Recurse over a set of phi uses to eliminate the trivial ones
170 MemoryAccess
*MemorySSAUpdater::recursePhi(MemoryAccess
*Phi
) {
173 TrackingVH
<MemoryAccess
> Res(Phi
);
174 SmallVector
<TrackingVH
<Value
>, 8> Uses
;
175 std::copy(Phi
->user_begin(), Phi
->user_end(), std::back_inserter(Uses
));
176 for (auto &U
: Uses
) {
177 if (MemoryPhi
*UsePhi
= dyn_cast
<MemoryPhi
>(&*U
)) {
178 auto OperRange
= UsePhi
->operands();
179 tryRemoveTrivialPhi(UsePhi
, OperRange
);
185 // Eliminate trivial phis
186 // Phis are trivial if they are defined either by themselves, or all the same
188 // IE phi(a, a) or b = phi(a, b) or c = phi(a, a, c)
189 // We recursively try to remove them.
190 template <class RangeType
>
191 MemoryAccess
*MemorySSAUpdater::tryRemoveTrivialPhi(MemoryPhi
*Phi
,
192 RangeType
&Operands
) {
193 // Bail out on non-opt Phis.
194 if (NonOptPhis
.count(Phi
))
197 // Detect equal or self arguments
198 MemoryAccess
*Same
= nullptr;
199 for (auto &Op
: Operands
) {
200 // If the same or self, good so far
201 if (Op
== Phi
|| Op
== Same
)
203 // not the same, return the phi since it's not eliminatable by us
206 Same
= cast
<MemoryAccess
>(&*Op
);
208 // Never found a non-self reference, the phi is undef
210 return MSSA
->getLiveOnEntryDef();
212 Phi
->replaceAllUsesWith(Same
);
213 removeMemoryAccess(Phi
);
216 // We should only end up recursing in case we replaced something, in which
217 // case, we may have made other Phis trivial.
218 return recursePhi(Same
);
221 void MemorySSAUpdater::insertUse(MemoryUse
*MU
) {
222 InsertedPHIs
.clear();
223 MU
->setDefiningAccess(getPreviousDef(MU
));
224 // Unlike for defs, there is no extra work to do. Because uses do not create
225 // new may-defs, there are only two cases:
227 // 1. There was a def already below us, and therefore, we should not have
228 // created a phi node because it was already needed for the def.
230 // 2. There is no def below us, and therefore, there is no extra renaming work
234 // Set every incoming edge {BB, MP->getBlock()} of MemoryPhi MP to NewDef.
235 static void setMemoryPhiValueForBlock(MemoryPhi
*MP
, const BasicBlock
*BB
,
236 MemoryAccess
*NewDef
) {
237 // Replace any operand with us an incoming block with the new defining
239 int i
= MP
->getBasicBlockIndex(BB
);
240 assert(i
!= -1 && "Should have found the basic block in the phi");
241 // We can't just compare i against getNumOperands since one is signed and the
242 // other not. So use it to index into the block iterator.
243 for (auto BBIter
= MP
->block_begin() + i
; BBIter
!= MP
->block_end();
247 MP
->setIncomingValue(i
, NewDef
);
252 // A brief description of the algorithm:
253 // First, we compute what should define the new def, using the SSA
254 // construction algorithm.
255 // Then, we update the defs below us (and any new phi nodes) in the graph to
256 // point to the correct new defs, to ensure we only have one variable, and no
257 // disconnected stores.
258 void MemorySSAUpdater::insertDef(MemoryDef
*MD
, bool RenameUses
) {
259 InsertedPHIs
.clear();
261 // See if we had a local def, and if not, go hunting.
262 MemoryAccess
*DefBefore
= getPreviousDef(MD
);
263 bool DefBeforeSameBlock
= DefBefore
->getBlock() == MD
->getBlock();
265 // There is a def before us, which means we can replace any store/phi uses
266 // of that thing with us, since we are in the way of whatever was there
268 // We now define that def's memorydefs and memoryphis
269 if (DefBeforeSameBlock
) {
270 DefBefore
->replaceUsesWithIf(MD
, [MD
](Use
&U
) {
271 // Leave the MemoryUses alone.
272 // Also make sure we skip ourselves to avoid self references.
273 User
*Usr
= U
.getUser();
274 return !isa
<MemoryUse
>(Usr
) && Usr
!= MD
;
275 // Defs are automatically unoptimized when the user is set to MD below,
276 // because the isOptimized() call will fail to find the same ID.
280 // and that def is now our defining access.
281 MD
->setDefiningAccess(DefBefore
);
283 // Remember the index where we may insert new phis below.
284 unsigned NewPhiIndex
= InsertedPHIs
.size();
286 SmallVector
<WeakVH
, 8> FixupList(InsertedPHIs
.begin(), InsertedPHIs
.end());
287 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.
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();
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
)
314 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
);
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
),
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
);
342 FixupList
.push_back(MD
);
345 // 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();
349 while (!FixupList
.empty()) {
350 unsigned StartingPHISize
= InsertedPHIs
.size();
351 fixupDefs(FixupList
);
353 // Put any new phis on the fixup list, and process them
354 FixupList
.append(InsertedPHIs
.begin() + StartingPHISize
, InsertedPHIs
.end());
357 // Optimize potentially non-minimal phis added in this method.
358 unsigned NewPhiSize
= NewPhiIndexEnd
- NewPhiIndex
;
360 tryRemoveTrivialPhis(ArrayRef
<WeakVH
>(&InsertedPHIs
[NewPhiIndex
], NewPhiSize
));
362 // Now that all fixups are done, rename all uses if we are asked.
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
371 if (auto *MD
= dyn_cast
<MemoryDef
>(FirstDef
))
372 FirstDef
= MD
->getDefiningAccess();
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.
377 for (auto &MP
: InsertedPHIs
) {
378 MemoryPhi
*Phi
= dyn_cast_or_null
<MemoryPhi
>(MP
);
380 MSSA
->renamePass(Phi
->getBlock(), nullptr, Visited
);
385 void MemorySSAUpdater::fixupDefs(const SmallVectorImpl
<WeakVH
> &Vars
) {
386 SmallPtrSet
<const BasicBlock
*, 8> Seen
;
387 SmallVector
<const BasicBlock
*, 16> Worklist
;
388 for (auto &Var
: Vars
) {
389 MemoryAccess
*NewDef
= dyn_cast_or_null
<MemoryAccess
>(Var
);
392 // First, see if there is a local def after the operand.
393 auto *Defs
= MSSA
->getWritableBlockDefs(NewDef
->getBlock());
394 auto DefIter
= NewDef
->getDefsIterator();
396 // The temporary Phi is being fixed, unmark it for not to optimize.
397 if (MemoryPhi
*Phi
= dyn_cast
<MemoryPhi
>(NewDef
))
398 NonOptPhis
.erase(Phi
);
400 // 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
);
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
);
413 Worklist
.push_back(S
);
416 while (!Worklist
.empty()) {
417 const BasicBlock
*FixupBlock
= Worklist
.back();
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
428 assert(MSSA
->dominates(NewDef
, FirstDef
) &&
429 "Should have dominated the new access");
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
));
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
);
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
)
448 Worklist
.push_back(S
);
455 void 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
);
463 void MemorySSAUpdater::removeDuplicatePhiEdgesBetween(const BasicBlock
*From
,
464 const BasicBlock
*To
) {
465 if (MemoryPhi
*MPhi
= MSSA
->getMemoryAccess(To
)) {
467 MPhi
->unorderedDeleteIncomingIf([&](const MemoryAccess
*, BasicBlock
*B
) {
475 if (MPhi
->getNumIncomingValues() == 1)
476 removeMemoryAccess(MPhi
);
480 static MemoryAccess
*getNewDefiningAccessForClone(MemoryAccess
*MA
,
481 const ValueToValueMapTy
&VMap
,
482 PhiToDefMap
&MPhiMap
,
483 bool CloneWasSimplified
,
485 MemoryAccess
*InsnDefining
= MA
;
486 if (MemoryDef
*DefMUD
= dyn_cast
<MemoryDef
>(InsnDefining
)) {
487 if (!MSSA
->isLiveOnEntryDef(DefMUD
)) {
488 Instruction
*DefMUDI
= DefMUD
->getMemoryInst();
489 assert(DefMUDI
&& "Found MemoryUseOrDef with no Instruction.");
490 if (Instruction
*NewDefMUDI
=
491 cast_or_null
<Instruction
>(VMap
.lookup(DefMUDI
))) {
492 InsnDefining
= MSSA
->getMemoryAccess(NewDefMUDI
);
493 if (!CloneWasSimplified
)
494 assert(InsnDefining
&& "Defining instruction cannot be nullptr.");
495 else if (!InsnDefining
|| isa
<MemoryUse
>(InsnDefining
)) {
496 // The clone was simplified, it's no longer a MemoryDef, look up.
497 auto DefIt
= DefMUD
->getDefsIterator();
498 // Since simplified clones only occur in single block cloning, a
499 // previous definition must exist, otherwise NewDefMUDI would not
500 // have been found in VMap.
501 assert(DefIt
!= MSSA
->getBlockDefs(DefMUD
->getBlock())->begin() &&
502 "Previous def must exist");
503 InsnDefining
= getNewDefiningAccessForClone(
504 &*(--DefIt
), VMap
, MPhiMap
, CloneWasSimplified
, MSSA
);
509 MemoryPhi
*DefPhi
= cast
<MemoryPhi
>(InsnDefining
);
510 if (MemoryAccess
*NewDefPhi
= MPhiMap
.lookup(DefPhi
))
511 InsnDefining
= NewDefPhi
;
513 assert(InsnDefining
&& "Defining instruction cannot be nullptr.");
517 void MemorySSAUpdater::cloneUsesAndDefs(BasicBlock
*BB
, BasicBlock
*NewBB
,
518 const ValueToValueMapTy
&VMap
,
519 PhiToDefMap
&MPhiMap
,
520 bool CloneWasSimplified
) {
521 const MemorySSA::AccessList
*Acc
= MSSA
->getBlockAccesses(BB
);
524 for (const MemoryAccess
&MA
: *Acc
) {
525 if (const MemoryUseOrDef
*MUD
= dyn_cast
<MemoryUseOrDef
>(&MA
)) {
526 Instruction
*Insn
= MUD
->getMemoryInst();
527 // Entry does not exist if the clone of the block did not clone all
528 // instructions. This occurs in LoopRotate when cloning instructions
529 // from the old header to the old preheader. The cloned instruction may
530 // also be a simplified Value, not an Instruction (see LoopRotate).
531 // Also in LoopRotate, even when it's an instruction, due to it being
532 // simplified, it may be a Use rather than a Def, so we cannot use MUD as
533 // template. Calls coming from updateForClonedBlockIntoPred, ensure this.
534 if (Instruction
*NewInsn
=
535 dyn_cast_or_null
<Instruction
>(VMap
.lookup(Insn
))) {
536 MemoryAccess
*NewUseOrDef
= MSSA
->createDefinedAccess(
538 getNewDefiningAccessForClone(MUD
->getDefiningAccess(), VMap
,
539 MPhiMap
, CloneWasSimplified
, MSSA
),
540 /*Template=*/CloneWasSimplified
? nullptr : MUD
,
541 /*CreationMustSucceed=*/CloneWasSimplified
? false : true);
543 MSSA
->insertIntoListsForBlock(NewUseOrDef
, NewBB
, MemorySSA::End
);
549 void MemorySSAUpdater::updatePhisWhenInsertingUniqueBackedgeBlock(
550 BasicBlock
*Header
, BasicBlock
*Preheader
, BasicBlock
*BEBlock
) {
551 auto *MPhi
= MSSA
->getMemoryAccess(Header
);
555 // Create phi node in the backedge block and populate it with the same
556 // incoming values as MPhi. Skip incoming values coming from Preheader.
557 auto *NewMPhi
= MSSA
->createMemoryPhi(BEBlock
);
558 bool HasUniqueIncomingValue
= true;
559 MemoryAccess
*UniqueValue
= nullptr;
560 for (unsigned I
= 0, E
= MPhi
->getNumIncomingValues(); I
!= E
; ++I
) {
561 BasicBlock
*IBB
= MPhi
->getIncomingBlock(I
);
562 MemoryAccess
*IV
= MPhi
->getIncomingValue(I
);
563 if (IBB
!= Preheader
) {
564 NewMPhi
->addIncoming(IV
, IBB
);
565 if (HasUniqueIncomingValue
) {
568 else if (UniqueValue
!= IV
)
569 HasUniqueIncomingValue
= false;
574 // Update incoming edges into MPhi. Remove all but the incoming edge from
575 // Preheader. Add an edge from NewMPhi
576 auto *AccFromPreheader
= MPhi
->getIncomingValueForBlock(Preheader
);
577 MPhi
->setIncomingValue(0, AccFromPreheader
);
578 MPhi
->setIncomingBlock(0, Preheader
);
579 for (unsigned I
= MPhi
->getNumIncomingValues() - 1; I
>= 1; --I
)
580 MPhi
->unorderedDeleteIncoming(I
);
581 MPhi
->addIncoming(NewMPhi
, BEBlock
);
583 // If NewMPhi is a trivial phi, remove it. Its use in the header MPhi will be
584 // replaced with the unique value.
585 if (HasUniqueIncomingValue
)
586 removeMemoryAccess(NewMPhi
);
589 void MemorySSAUpdater::updateForClonedLoop(const LoopBlocksRPO
&LoopBlocks
,
590 ArrayRef
<BasicBlock
*> ExitBlocks
,
591 const ValueToValueMapTy
&VMap
,
592 bool IgnoreIncomingWithNoClones
) {
595 auto FixPhiIncomingValues
= [&](MemoryPhi
*Phi
, MemoryPhi
*NewPhi
) {
596 assert(Phi
&& NewPhi
&& "Invalid Phi nodes.");
597 BasicBlock
*NewPhiBB
= NewPhi
->getBlock();
598 SmallPtrSet
<BasicBlock
*, 4> NewPhiBBPreds(pred_begin(NewPhiBB
),
600 for (unsigned It
= 0, E
= Phi
->getNumIncomingValues(); It
< E
; ++It
) {
601 MemoryAccess
*IncomingAccess
= Phi
->getIncomingValue(It
);
602 BasicBlock
*IncBB
= Phi
->getIncomingBlock(It
);
604 if (BasicBlock
*NewIncBB
= cast_or_null
<BasicBlock
>(VMap
.lookup(IncBB
)))
606 else if (IgnoreIncomingWithNoClones
)
609 // Now we have IncBB, and will need to add incoming from it to NewPhi.
611 // If IncBB is not a predecessor of NewPhiBB, then do not add it.
612 // NewPhiBB was cloned without that edge.
613 if (!NewPhiBBPreds
.count(IncBB
))
616 // Determine incoming value and add it as incoming from IncBB.
617 if (MemoryUseOrDef
*IncMUD
= dyn_cast
<MemoryUseOrDef
>(IncomingAccess
)) {
618 if (!MSSA
->isLiveOnEntryDef(IncMUD
)) {
619 Instruction
*IncI
= IncMUD
->getMemoryInst();
620 assert(IncI
&& "Found MemoryUseOrDef with no Instruction.");
621 if (Instruction
*NewIncI
=
622 cast_or_null
<Instruction
>(VMap
.lookup(IncI
))) {
623 IncMUD
= MSSA
->getMemoryAccess(NewIncI
);
625 "MemoryUseOrDef cannot be null, all preds processed.");
628 NewPhi
->addIncoming(IncMUD
, IncBB
);
630 MemoryPhi
*IncPhi
= cast
<MemoryPhi
>(IncomingAccess
);
631 if (MemoryAccess
*NewDefPhi
= MPhiMap
.lookup(IncPhi
))
632 NewPhi
->addIncoming(NewDefPhi
, IncBB
);
634 NewPhi
->addIncoming(IncPhi
, IncBB
);
639 auto ProcessBlock
= [&](BasicBlock
*BB
) {
640 BasicBlock
*NewBlock
= cast_or_null
<BasicBlock
>(VMap
.lookup(BB
));
644 assert(!MSSA
->getWritableBlockAccesses(NewBlock
) &&
645 "Cloned block should have no accesses");
648 if (MemoryPhi
*MPhi
= MSSA
->getMemoryAccess(BB
)) {
649 MemoryPhi
*NewPhi
= MSSA
->createMemoryPhi(NewBlock
);
650 MPhiMap
[MPhi
] = NewPhi
;
652 // Update Uses and Defs.
653 cloneUsesAndDefs(BB
, NewBlock
, VMap
, MPhiMap
);
656 for (auto BB
: llvm::concat
<BasicBlock
*const>(LoopBlocks
, ExitBlocks
))
659 for (auto BB
: llvm::concat
<BasicBlock
*const>(LoopBlocks
, ExitBlocks
))
660 if (MemoryPhi
*MPhi
= MSSA
->getMemoryAccess(BB
))
661 if (MemoryAccess
*NewPhi
= MPhiMap
.lookup(MPhi
))
662 FixPhiIncomingValues(MPhi
, cast
<MemoryPhi
>(NewPhi
));
665 void MemorySSAUpdater::updateForClonedBlockIntoPred(
666 BasicBlock
*BB
, BasicBlock
*P1
, const ValueToValueMapTy
&VM
) {
667 // All defs/phis from outside BB that are used in BB, are valid uses in P1.
668 // Since those defs/phis must have dominated BB, and also dominate P1.
669 // Defs from BB being used in BB will be replaced with the cloned defs from
670 // VM. The uses of BB's Phi (if it exists) in BB will be replaced by the
671 // incoming def into the Phi from P1.
672 // Instructions cloned into the predecessor are in practice sometimes
673 // simplified, so disable the use of the template, and create an access from
676 if (MemoryPhi
*MPhi
= MSSA
->getMemoryAccess(BB
))
677 MPhiMap
[MPhi
] = MPhi
->getIncomingValueForBlock(P1
);
678 cloneUsesAndDefs(BB
, P1
, VM
, MPhiMap
, /*CloneWasSimplified=*/true);
681 template <typename Iter
>
682 void MemorySSAUpdater::privateUpdateExitBlocksForClonedLoop(
683 ArrayRef
<BasicBlock
*> ExitBlocks
, Iter ValuesBegin
, Iter ValuesEnd
,
685 SmallVector
<CFGUpdate
, 4> Updates
;
686 // Update/insert phis in all successors of exit blocks.
687 for (auto *Exit
: ExitBlocks
)
688 for (const ValueToValueMapTy
*VMap
: make_range(ValuesBegin
, ValuesEnd
))
689 if (BasicBlock
*NewExit
= cast_or_null
<BasicBlock
>(VMap
->lookup(Exit
))) {
690 BasicBlock
*ExitSucc
= NewExit
->getTerminator()->getSuccessor(0);
691 Updates
.push_back({DT
.Insert
, NewExit
, ExitSucc
});
693 applyInsertUpdates(Updates
, DT
);
696 void MemorySSAUpdater::updateExitBlocksForClonedLoop(
697 ArrayRef
<BasicBlock
*> ExitBlocks
, const ValueToValueMapTy
&VMap
,
699 const ValueToValueMapTy
*const Arr
[] = {&VMap
};
700 privateUpdateExitBlocksForClonedLoop(ExitBlocks
, std::begin(Arr
),
704 void MemorySSAUpdater::updateExitBlocksForClonedLoop(
705 ArrayRef
<BasicBlock
*> ExitBlocks
,
706 ArrayRef
<std::unique_ptr
<ValueToValueMapTy
>> VMaps
, DominatorTree
&DT
) {
707 auto GetPtr
= [&](const std::unique_ptr
<ValueToValueMapTy
> &I
) {
710 using MappedIteratorType
=
711 mapped_iterator
<const std::unique_ptr
<ValueToValueMapTy
> *,
713 auto MapBegin
= MappedIteratorType(VMaps
.begin(), GetPtr
);
714 auto MapEnd
= MappedIteratorType(VMaps
.end(), GetPtr
);
715 privateUpdateExitBlocksForClonedLoop(ExitBlocks
, MapBegin
, MapEnd
, DT
);
718 void MemorySSAUpdater::applyUpdates(ArrayRef
<CFGUpdate
> Updates
,
720 SmallVector
<CFGUpdate
, 4> RevDeleteUpdates
;
721 SmallVector
<CFGUpdate
, 4> InsertUpdates
;
722 for (auto &Update
: Updates
) {
723 if (Update
.getKind() == DT
.Insert
)
724 InsertUpdates
.push_back({DT
.Insert
, Update
.getFrom(), Update
.getTo()});
726 RevDeleteUpdates
.push_back({DT
.Insert
, Update
.getFrom(), Update
.getTo()});
729 if (!RevDeleteUpdates
.empty()) {
730 // Update for inserted edges: use newDT and snapshot CFG as if deletes had
732 // FIXME: This creates a new DT, so it's more expensive to do mix
733 // delete/inserts vs just inserts. We can do an incremental update on the DT
734 // to revert deletes, than re-delete the edges. Teaching DT to do this, is
735 // part of a pending cleanup.
736 DominatorTree
NewDT(DT
, RevDeleteUpdates
);
737 GraphDiff
<BasicBlock
*> GD(RevDeleteUpdates
);
738 applyInsertUpdates(InsertUpdates
, NewDT
, &GD
);
740 GraphDiff
<BasicBlock
*> GD
;
741 applyInsertUpdates(InsertUpdates
, DT
, &GD
);
744 // Update for deleted edges
745 for (auto &Update
: RevDeleteUpdates
)
746 removeEdge(Update
.getFrom(), Update
.getTo());
749 void MemorySSAUpdater::applyInsertUpdates(ArrayRef
<CFGUpdate
> Updates
,
751 GraphDiff
<BasicBlock
*> GD
;
752 applyInsertUpdates(Updates
, DT
, &GD
);
755 void MemorySSAUpdater::applyInsertUpdates(ArrayRef
<CFGUpdate
> Updates
,
757 const GraphDiff
<BasicBlock
*> *GD
) {
758 // Get recursive last Def, assuming well formed MSSA and updated DT.
759 auto GetLastDef
= [&](BasicBlock
*BB
) -> MemoryAccess
* {
761 MemorySSA::DefsList
*Defs
= MSSA
->getWritableBlockDefs(BB
);
762 // Return last Def or Phi in BB, if it exists.
764 return &*(--Defs
->end());
766 // Check number of predecessors, we only care if there's more than one.
768 BasicBlock
*Pred
= nullptr;
769 for (auto &Pair
: children
<GraphDiffInvBBPair
>({GD
, BB
})) {
776 // If BB has multiple predecessors, get last definition from IDom.
778 // [SimpleLoopUnswitch] If BB is a dead block, about to be deleted, its
779 // DT is invalidated. Return LoE as its last def. This will be added to
780 // MemoryPhi node, and later deleted when the block is deleted.
782 return MSSA
->getLiveOnEntryDef();
783 if (auto *IDom
= DT
.getNode(BB
)->getIDom())
784 if (IDom
->getBlock() != BB
) {
785 BB
= IDom
->getBlock();
788 return MSSA
->getLiveOnEntryDef();
790 // Single predecessor, BB cannot be dead. GetLastDef of Pred.
791 assert(Count
== 1 && Pred
&& "Single predecessor expected.");
795 llvm_unreachable("Unable to get last definition.");
798 // Get nearest IDom given a set of blocks.
799 // TODO: this can be optimized by starting the search at the node with the
800 // lowest level (highest in the tree).
801 auto FindNearestCommonDominator
=
802 [&](const SmallSetVector
<BasicBlock
*, 2> &BBSet
) -> BasicBlock
* {
803 BasicBlock
*PrevIDom
= *BBSet
.begin();
804 for (auto *BB
: BBSet
)
805 PrevIDom
= DT
.findNearestCommonDominator(PrevIDom
, BB
);
809 // Get all blocks that dominate PrevIDom, stop when reaching CurrIDom. Do not
811 auto GetNoLongerDomBlocks
=
812 [&](BasicBlock
*PrevIDom
, BasicBlock
*CurrIDom
,
813 SmallVectorImpl
<BasicBlock
*> &BlocksPrevDom
) {
814 if (PrevIDom
== CurrIDom
)
816 BlocksPrevDom
.push_back(PrevIDom
);
817 BasicBlock
*NextIDom
= PrevIDom
;
818 while (BasicBlock
*UpIDom
=
819 DT
.getNode(NextIDom
)->getIDom()->getBlock()) {
820 if (UpIDom
== CurrIDom
)
822 BlocksPrevDom
.push_back(UpIDom
);
827 // Map a BB to its predecessors: added + previously existing. To get a
828 // deterministic order, store predecessors as SetVectors. The order in each
829 // will be defined by the order in Updates (fixed) and the order given by
830 // children<> (also fixed). Since we further iterate over these ordered sets,
831 // we lose the information of multiple edges possibly existing between two
832 // blocks, so we'll keep and EdgeCount map for that.
833 // An alternate implementation could keep unordered set for the predecessors,
834 // traverse either Updates or children<> each time to get the deterministic
835 // order, and drop the usage of EdgeCount. This alternate approach would still
836 // require querying the maps for each predecessor, and children<> call has
837 // additional computation inside for creating the snapshot-graph predecessors.
838 // As such, we favor using a little additional storage and less compute time.
839 // This decision can be revisited if we find the alternative more favorable.
842 SmallSetVector
<BasicBlock
*, 2> Added
;
843 SmallSetVector
<BasicBlock
*, 2> Prev
;
845 SmallDenseMap
<BasicBlock
*, PredInfo
> PredMap
;
847 for (auto &Edge
: Updates
) {
848 BasicBlock
*BB
= Edge
.getTo();
849 auto &AddedBlockSet
= PredMap
[BB
].Added
;
850 AddedBlockSet
.insert(Edge
.getFrom());
853 // Store all existing predecessor for each BB, at least one must exist.
854 SmallDenseMap
<std::pair
<BasicBlock
*, BasicBlock
*>, int> EdgeCountMap
;
855 SmallPtrSet
<BasicBlock
*, 2> NewBlocks
;
856 for (auto &BBPredPair
: PredMap
) {
857 auto *BB
= BBPredPair
.first
;
858 const auto &AddedBlockSet
= BBPredPair
.second
.Added
;
859 auto &PrevBlockSet
= BBPredPair
.second
.Prev
;
860 for (auto &Pair
: children
<GraphDiffInvBBPair
>({GD
, BB
})) {
861 BasicBlock
*Pi
= Pair
.second
;
862 if (!AddedBlockSet
.count(Pi
))
863 PrevBlockSet
.insert(Pi
);
864 EdgeCountMap
[{Pi
, BB
}]++;
867 if (PrevBlockSet
.empty()) {
868 assert(pred_size(BB
) == AddedBlockSet
.size() && "Duplicate edges added.");
871 << "Adding a predecessor to a block with no predecessors. "
872 "This must be an edge added to a new, likely cloned, block. "
873 "Its memory accesses must be already correct, assuming completed "
874 "via the updateExitBlocksForClonedLoop API. "
875 "Assert a single such edge is added so no phi addition or "
876 "additional processing is required.\n");
877 assert(AddedBlockSet
.size() == 1 &&
878 "Can only handle adding one predecessor to a new block.");
879 // Need to remove new blocks from PredMap. Remove below to not invalidate
881 NewBlocks
.insert(BB
);
884 // Nothing to process for new/cloned blocks.
885 for (auto *BB
: NewBlocks
)
888 SmallVector
<BasicBlock
*, 16> BlocksWithDefsToReplace
;
889 SmallVector
<WeakVH
, 8> InsertedPhis
;
891 // First create MemoryPhis in all blocks that don't have one. Create in the
892 // order found in Updates, not in PredMap, to get deterministic numbering.
893 for (auto &Edge
: Updates
) {
894 BasicBlock
*BB
= Edge
.getTo();
895 if (PredMap
.count(BB
) && !MSSA
->getMemoryAccess(BB
))
896 InsertedPhis
.push_back(MSSA
->createMemoryPhi(BB
));
899 // Now we'll fill in the MemoryPhis with the right incoming values.
900 for (auto &BBPredPair
: PredMap
) {
901 auto *BB
= BBPredPair
.first
;
902 const auto &PrevBlockSet
= BBPredPair
.second
.Prev
;
903 const auto &AddedBlockSet
= BBPredPair
.second
.Added
;
904 assert(!PrevBlockSet
.empty() &&
905 "At least one previous predecessor must exist.");
907 // TODO: if this becomes a bottleneck, we can save on GetLastDef calls by
908 // keeping this map before the loop. We can reuse already populated entries
909 // if an edge is added from the same predecessor to two different blocks,
910 // and this does happen in rotate. Note that the map needs to be updated
911 // when deleting non-necessary phis below, if the phi is in the map by
912 // replacing the value with DefP1.
913 SmallDenseMap
<BasicBlock
*, MemoryAccess
*> LastDefAddedPred
;
914 for (auto *AddedPred
: AddedBlockSet
) {
915 auto *DefPn
= GetLastDef(AddedPred
);
916 assert(DefPn
!= nullptr && "Unable to find last definition.");
917 LastDefAddedPred
[AddedPred
] = DefPn
;
920 MemoryPhi
*NewPhi
= MSSA
->getMemoryAccess(BB
);
921 // If Phi is not empty, add an incoming edge from each added pred. Must
922 // still compute blocks with defs to replace for this block below.
923 if (NewPhi
->getNumOperands()) {
924 for (auto *Pred
: AddedBlockSet
) {
925 auto *LastDefForPred
= LastDefAddedPred
[Pred
];
926 for (int I
= 0, E
= EdgeCountMap
[{Pred
, BB
}]; I
< E
; ++I
)
927 NewPhi
->addIncoming(LastDefForPred
, Pred
);
930 // Pick any existing predecessor and get its definition. All other
931 // existing predecessors should have the same one, since no phi existed.
932 auto *P1
= *PrevBlockSet
.begin();
933 MemoryAccess
*DefP1
= GetLastDef(P1
);
935 // Check DefP1 against all Defs in LastDefPredPair. If all the same,
937 bool InsertPhi
= false;
938 for (auto LastDefPredPair
: LastDefAddedPred
)
939 if (DefP1
!= LastDefPredPair
.second
) {
944 // Since NewPhi may be used in other newly added Phis, replace all uses
945 // of NewPhi with the definition coming from all predecessors (DefP1),
946 // before deleting it.
947 NewPhi
->replaceAllUsesWith(DefP1
);
948 removeMemoryAccess(NewPhi
);
952 // Update Phi with new values for new predecessors and old value for all
953 // other predecessors. Since AddedBlockSet and PrevBlockSet are ordered
954 // sets, the order of entries in NewPhi is deterministic.
955 for (auto *Pred
: AddedBlockSet
) {
956 auto *LastDefForPred
= LastDefAddedPred
[Pred
];
957 for (int I
= 0, E
= EdgeCountMap
[{Pred
, BB
}]; I
< E
; ++I
)
958 NewPhi
->addIncoming(LastDefForPred
, Pred
);
960 for (auto *Pred
: PrevBlockSet
)
961 for (int I
= 0, E
= EdgeCountMap
[{Pred
, BB
}]; I
< E
; ++I
)
962 NewPhi
->addIncoming(DefP1
, Pred
);
965 // Get all blocks that used to dominate BB and no longer do after adding
966 // AddedBlockSet, where PrevBlockSet are the previously known predecessors.
967 assert(DT
.getNode(BB
)->getIDom() && "BB does not have valid idom");
968 BasicBlock
*PrevIDom
= FindNearestCommonDominator(PrevBlockSet
);
969 assert(PrevIDom
&& "Previous IDom should exists");
970 BasicBlock
*NewIDom
= DT
.getNode(BB
)->getIDom()->getBlock();
971 assert(NewIDom
&& "BB should have a new valid idom");
972 assert(DT
.dominates(NewIDom
, PrevIDom
) &&
973 "New idom should dominate old idom");
974 GetNoLongerDomBlocks(PrevIDom
, NewIDom
, BlocksWithDefsToReplace
);
977 tryRemoveTrivialPhis(InsertedPhis
);
978 // Create the set of blocks that now have a definition. We'll use this to
979 // compute IDF and add Phis there next.
980 SmallVector
<BasicBlock
*, 8> BlocksToProcess
;
981 for (auto &VH
: InsertedPhis
)
982 if (auto *MPhi
= cast_or_null
<MemoryPhi
>(VH
))
983 BlocksToProcess
.push_back(MPhi
->getBlock());
985 // Compute IDF and add Phis in all IDF blocks that do not have one.
986 SmallVector
<BasicBlock
*, 32> IDFBlocks
;
987 if (!BlocksToProcess
.empty()) {
988 ForwardIDFCalculator
IDFs(DT
, GD
);
989 SmallPtrSet
<BasicBlock
*, 16> DefiningBlocks(BlocksToProcess
.begin(),
990 BlocksToProcess
.end());
991 IDFs
.setDefiningBlocks(DefiningBlocks
);
992 IDFs
.calculate(IDFBlocks
);
994 SmallSetVector
<MemoryPhi
*, 4> PhisToFill
;
995 // First create all needed Phis.
996 for (auto *BBIDF
: IDFBlocks
)
997 if (!MSSA
->getMemoryAccess(BBIDF
)) {
998 auto *IDFPhi
= MSSA
->createMemoryPhi(BBIDF
);
999 InsertedPhis
.push_back(IDFPhi
);
1000 PhisToFill
.insert(IDFPhi
);
1002 // Then update or insert their correct incoming values.
1003 for (auto *BBIDF
: IDFBlocks
) {
1004 auto *IDFPhi
= MSSA
->getMemoryAccess(BBIDF
);
1005 assert(IDFPhi
&& "Phi must exist");
1006 if (!PhisToFill
.count(IDFPhi
)) {
1007 // Update existing Phi.
1008 // FIXME: some updates may be redundant, try to optimize and skip some.
1009 for (unsigned I
= 0, E
= IDFPhi
->getNumIncomingValues(); I
< E
; ++I
)
1010 IDFPhi
->setIncomingValue(I
, GetLastDef(IDFPhi
->getIncomingBlock(I
)));
1012 for (auto &Pair
: children
<GraphDiffInvBBPair
>({GD
, BBIDF
})) {
1013 BasicBlock
*Pi
= Pair
.second
;
1014 IDFPhi
->addIncoming(GetLastDef(Pi
), Pi
);
1020 // Now for all defs in BlocksWithDefsToReplace, if there are uses they no
1021 // longer dominate, replace those with the closest dominating def.
1022 // This will also update optimized accesses, as they're also uses.
1023 for (auto *BlockWithDefsToReplace
: BlocksWithDefsToReplace
) {
1024 if (auto DefsList
= MSSA
->getWritableBlockDefs(BlockWithDefsToReplace
)) {
1025 for (auto &DefToReplaceUses
: *DefsList
) {
1026 BasicBlock
*DominatingBlock
= DefToReplaceUses
.getBlock();
1027 Value::use_iterator UI
= DefToReplaceUses
.use_begin(),
1028 E
= DefToReplaceUses
.use_end();
1032 MemoryAccess
*Usr
= dyn_cast
<MemoryAccess
>(U
.getUser());
1033 if (MemoryPhi
*UsrPhi
= dyn_cast
<MemoryPhi
>(Usr
)) {
1034 BasicBlock
*DominatedBlock
= UsrPhi
->getIncomingBlock(U
);
1035 if (!DT
.dominates(DominatingBlock
, DominatedBlock
))
1036 U
.set(GetLastDef(DominatedBlock
));
1038 BasicBlock
*DominatedBlock
= Usr
->getBlock();
1039 if (!DT
.dominates(DominatingBlock
, DominatedBlock
)) {
1040 if (auto *DomBlPhi
= MSSA
->getMemoryAccess(DominatedBlock
))
1043 auto *IDom
= DT
.getNode(DominatedBlock
)->getIDom();
1044 assert(IDom
&& "Block must have a valid IDom.");
1045 U
.set(GetLastDef(IDom
->getBlock()));
1047 cast
<MemoryUseOrDef
>(Usr
)->resetOptimized();
1054 tryRemoveTrivialPhis(InsertedPhis
);
1057 // Move What before Where in the MemorySSA IR.
1058 template <class WhereType
>
1059 void MemorySSAUpdater::moveTo(MemoryUseOrDef
*What
, BasicBlock
*BB
,
1061 // Mark MemoryPhi users of What not to be optimized.
1062 for (auto *U
: What
->users())
1063 if (MemoryPhi
*PhiUser
= dyn_cast
<MemoryPhi
>(U
))
1064 NonOptPhis
.insert(PhiUser
);
1066 // Replace all our users with our defining access.
1067 What
->replaceAllUsesWith(What
->getDefiningAccess());
1069 // Let MemorySSA take care of moving it around in the lists.
1070 MSSA
->moveTo(What
, BB
, Where
);
1072 // Now reinsert it into the IR and do whatever fixups needed.
1073 if (auto *MD
= dyn_cast
<MemoryDef
>(What
))
1074 insertDef(MD
, true);
1076 insertUse(cast
<MemoryUse
>(What
));
1078 // Clear dangling pointers. We added all MemoryPhi users, but not all
1079 // of them are removed by fixupDefs().
1083 // Move What before Where in the MemorySSA IR.
1084 void MemorySSAUpdater::moveBefore(MemoryUseOrDef
*What
, MemoryUseOrDef
*Where
) {
1085 moveTo(What
, Where
->getBlock(), Where
->getIterator());
1088 // Move What after Where in the MemorySSA IR.
1089 void MemorySSAUpdater::moveAfter(MemoryUseOrDef
*What
, MemoryUseOrDef
*Where
) {
1090 moveTo(What
, Where
->getBlock(), ++Where
->getIterator());
1093 void MemorySSAUpdater::moveToPlace(MemoryUseOrDef
*What
, BasicBlock
*BB
,
1094 MemorySSA::InsertionPlace Where
) {
1095 return moveTo(What
, BB
, Where
);
1098 // All accesses in To used to be in From. Move to end and update access lists.
1099 void MemorySSAUpdater::moveAllAccesses(BasicBlock
*From
, BasicBlock
*To
,
1100 Instruction
*Start
) {
1102 MemorySSA::AccessList
*Accs
= MSSA
->getWritableBlockAccesses(From
);
1106 MemoryAccess
*FirstInNew
= nullptr;
1107 for (Instruction
&I
: make_range(Start
->getIterator(), To
->end()))
1108 if ((FirstInNew
= MSSA
->getMemoryAccess(&I
)))
1113 auto *MUD
= cast
<MemoryUseOrDef
>(FirstInNew
);
1115 auto NextIt
= ++MUD
->getIterator();
1116 MemoryUseOrDef
*NextMUD
= (!Accs
|| NextIt
== Accs
->end())
1118 : cast
<MemoryUseOrDef
>(&*NextIt
);
1119 MSSA
->moveTo(MUD
, To
, MemorySSA::End
);
1120 // Moving MUD from Accs in the moveTo above, may delete Accs, so we need to
1121 // retrieve it again.
1122 Accs
= MSSA
->getWritableBlockAccesses(From
);
1127 void MemorySSAUpdater::moveAllAfterSpliceBlocks(BasicBlock
*From
,
1129 Instruction
*Start
) {
1130 assert(MSSA
->getBlockAccesses(To
) == nullptr &&
1131 "To block is expected to be free of MemoryAccesses.");
1132 moveAllAccesses(From
, To
, Start
);
1133 for (BasicBlock
*Succ
: successors(To
))
1134 if (MemoryPhi
*MPhi
= MSSA
->getMemoryAccess(Succ
))
1135 MPhi
->setIncomingBlock(MPhi
->getBasicBlockIndex(From
), To
);
1138 void MemorySSAUpdater::moveAllAfterMergeBlocks(BasicBlock
*From
, BasicBlock
*To
,
1139 Instruction
*Start
) {
1140 assert(From
->getSinglePredecessor() == To
&&
1141 "From block is expected to have a single predecessor (To).");
1142 moveAllAccesses(From
, To
, Start
);
1143 for (BasicBlock
*Succ
: successors(From
))
1144 if (MemoryPhi
*MPhi
= MSSA
->getMemoryAccess(Succ
))
1145 MPhi
->setIncomingBlock(MPhi
->getBasicBlockIndex(From
), To
);
1148 /// If all arguments of a MemoryPHI are defined by the same incoming
1149 /// argument, return that argument.
1150 static MemoryAccess
*onlySingleValue(MemoryPhi
*MP
) {
1151 MemoryAccess
*MA
= nullptr;
1153 for (auto &Arg
: MP
->operands()) {
1155 MA
= cast
<MemoryAccess
>(Arg
);
1162 void MemorySSAUpdater::wireOldPredecessorsToNewImmediatePredecessor(
1163 BasicBlock
*Old
, BasicBlock
*New
, ArrayRef
<BasicBlock
*> Preds
,
1164 bool IdenticalEdgesWereMerged
) {
1165 assert(!MSSA
->getWritableBlockAccesses(New
) &&
1166 "Access list should be null for a new block.");
1167 MemoryPhi
*Phi
= MSSA
->getMemoryAccess(Old
);
1170 if (Old
->hasNPredecessors(1)) {
1171 assert(pred_size(New
) == Preds
.size() &&
1172 "Should have moved all predecessors.");
1173 MSSA
->moveTo(Phi
, New
, MemorySSA::Beginning
);
1175 assert(!Preds
.empty() && "Must be moving at least one predecessor to the "
1176 "new immediate predecessor.");
1177 MemoryPhi
*NewPhi
= MSSA
->createMemoryPhi(New
);
1178 SmallPtrSet
<BasicBlock
*, 16> PredsSet(Preds
.begin(), Preds
.end());
1179 // Currently only support the case of removing a single incoming edge when
1180 // identical edges were not merged.
1181 if (!IdenticalEdgesWereMerged
)
1182 assert(PredsSet
.size() == Preds
.size() &&
1183 "If identical edges were not merged, we cannot have duplicate "
1184 "blocks in the predecessors");
1185 Phi
->unorderedDeleteIncomingIf([&](MemoryAccess
*MA
, BasicBlock
*B
) {
1186 if (PredsSet
.count(B
)) {
1187 NewPhi
->addIncoming(MA
, B
);
1188 if (!IdenticalEdgesWereMerged
)
1194 Phi
->addIncoming(NewPhi
, New
);
1195 if (onlySingleValue(NewPhi
))
1196 removeMemoryAccess(NewPhi
);
1200 void MemorySSAUpdater::removeMemoryAccess(MemoryAccess
*MA
, bool OptimizePhis
) {
1201 assert(!MSSA
->isLiveOnEntryDef(MA
) &&
1202 "Trying to remove the live on entry def");
1203 // We can only delete phi nodes if they have no uses, or we can replace all
1204 // uses with a single definition.
1205 MemoryAccess
*NewDefTarget
= nullptr;
1206 if (MemoryPhi
*MP
= dyn_cast
<MemoryPhi
>(MA
)) {
1207 // Note that it is sufficient to know that all edges of the phi node have
1208 // the same argument. If they do, by the definition of dominance frontiers
1209 // (which we used to place this phi), that argument must dominate this phi,
1210 // and thus, must dominate the phi's uses, and so we will not hit the assert
1212 NewDefTarget
= onlySingleValue(MP
);
1213 assert((NewDefTarget
|| MP
->use_empty()) &&
1214 "We can't delete this memory phi");
1216 NewDefTarget
= cast
<MemoryUseOrDef
>(MA
)->getDefiningAccess();
1219 SmallSetVector
<MemoryPhi
*, 4> PhisToCheck
;
1221 // Re-point the uses at our defining access
1222 if (!isa
<MemoryUse
>(MA
) && !MA
->use_empty()) {
1223 // Reset optimized on users of this store, and reset the uses.
1225 // 1. This is a slightly modified version of RAUW to avoid walking the
1227 // 2. If we wanted to be complete, we would have to reset the optimized
1228 // flags on users of phi nodes if doing the below makes a phi node have all
1229 // the same arguments. Instead, we prefer users to removeMemoryAccess those
1230 // phi nodes, because doing it here would be N^3.
1231 if (MA
->hasValueHandle())
1232 ValueHandleBase::ValueIsRAUWd(MA
, NewDefTarget
);
1233 // Note: We assume MemorySSA is not used in metadata since it's not really
1236 while (!MA
->use_empty()) {
1237 Use
&U
= *MA
->use_begin();
1238 if (auto *MUD
= dyn_cast
<MemoryUseOrDef
>(U
.getUser()))
1239 MUD
->resetOptimized();
1241 if (MemoryPhi
*MP
= dyn_cast
<MemoryPhi
>(U
.getUser()))
1242 PhisToCheck
.insert(MP
);
1243 U
.set(NewDefTarget
);
1247 // The call below to erase will destroy MA, so we can't change the order we
1248 // are doing things here
1249 MSSA
->removeFromLookups(MA
);
1250 MSSA
->removeFromLists(MA
);
1252 // Optionally optimize Phi uses. This will recursively remove trivial phis.
1253 if (!PhisToCheck
.empty()) {
1254 SmallVector
<WeakVH
, 16> PhisToOptimize
{PhisToCheck
.begin(),
1256 PhisToCheck
.clear();
1258 unsigned PhisSize
= PhisToOptimize
.size();
1259 while (PhisSize
-- > 0)
1261 cast_or_null
<MemoryPhi
>(PhisToOptimize
.pop_back_val())) {
1262 auto OperRange
= MP
->operands();
1263 tryRemoveTrivialPhi(MP
, OperRange
);
1268 void MemorySSAUpdater::removeBlocks(
1269 const SmallSetVector
<BasicBlock
*, 8> &DeadBlocks
) {
1270 // First delete all uses of BB in MemoryPhis.
1271 for (BasicBlock
*BB
: DeadBlocks
) {
1272 Instruction
*TI
= BB
->getTerminator();
1273 assert(TI
&& "Basic block expected to have a terminator instruction");
1274 for (BasicBlock
*Succ
: successors(TI
))
1275 if (!DeadBlocks
.count(Succ
))
1276 if (MemoryPhi
*MP
= MSSA
->getMemoryAccess(Succ
)) {
1277 MP
->unorderedDeleteIncomingBlock(BB
);
1278 if (MP
->getNumIncomingValues() == 1)
1279 removeMemoryAccess(MP
);
1281 // Drop all references of all accesses in BB
1282 if (MemorySSA::AccessList
*Acc
= MSSA
->getWritableBlockAccesses(BB
))
1283 for (MemoryAccess
&MA
: *Acc
)
1284 MA
.dropAllReferences();
1287 // Next, delete all memory accesses in each block
1288 for (BasicBlock
*BB
: DeadBlocks
) {
1289 MemorySSA::AccessList
*Acc
= MSSA
->getWritableBlockAccesses(BB
);
1292 for (auto AB
= Acc
->begin(), AE
= Acc
->end(); AB
!= AE
;) {
1293 MemoryAccess
*MA
= &*AB
;
1295 MSSA
->removeFromLookups(MA
);
1296 MSSA
->removeFromLists(MA
);
1301 void MemorySSAUpdater::tryRemoveTrivialPhis(ArrayRef
<WeakVH
> UpdatedPHIs
) {
1302 for (auto &VH
: UpdatedPHIs
)
1303 if (auto *MPhi
= cast_or_null
<MemoryPhi
>(VH
)) {
1304 auto OperRange
= MPhi
->operands();
1305 tryRemoveTrivialPhi(MPhi
, OperRange
);
1309 void MemorySSAUpdater::changeToUnreachable(const Instruction
*I
) {
1310 const BasicBlock
*BB
= I
->getParent();
1311 // Remove memory accesses in BB for I and all following instructions.
1312 auto BBI
= I
->getIterator(), BBE
= BB
->end();
1313 // FIXME: If this becomes too expensive, iterate until the first instruction
1314 // with a memory access, then iterate over MemoryAccesses.
1316 removeMemoryAccess(&*(BBI
++));
1317 // Update phis in BB's successors to remove BB.
1318 SmallVector
<WeakVH
, 16> UpdatedPHIs
;
1319 for (const BasicBlock
*Successor
: successors(BB
)) {
1320 removeDuplicatePhiEdgesBetween(BB
, Successor
);
1321 if (MemoryPhi
*MPhi
= MSSA
->getMemoryAccess(Successor
)) {
1322 MPhi
->unorderedDeleteIncomingBlock(BB
);
1323 UpdatedPHIs
.push_back(MPhi
);
1326 // Optimize trivial phis.
1327 tryRemoveTrivialPhis(UpdatedPHIs
);
1330 void MemorySSAUpdater::changeCondBranchToUnconditionalTo(const BranchInst
*BI
,
1331 const BasicBlock
*To
) {
1332 const BasicBlock
*BB
= BI
->getParent();
1333 SmallVector
<WeakVH
, 16> UpdatedPHIs
;
1334 for (const BasicBlock
*Succ
: successors(BB
)) {
1335 removeDuplicatePhiEdgesBetween(BB
, Succ
);
1337 if (auto *MPhi
= MSSA
->getMemoryAccess(Succ
)) {
1338 MPhi
->unorderedDeleteIncomingBlock(BB
);
1339 UpdatedPHIs
.push_back(MPhi
);
1342 // Optimize trivial phis.
1343 tryRemoveTrivialPhis(UpdatedPHIs
);
1346 MemoryAccess
*MemorySSAUpdater::createMemoryAccessInBB(
1347 Instruction
*I
, MemoryAccess
*Definition
, const BasicBlock
*BB
,
1348 MemorySSA::InsertionPlace Point
) {
1349 MemoryUseOrDef
*NewAccess
= MSSA
->createDefinedAccess(I
, Definition
);
1350 MSSA
->insertIntoListsForBlock(NewAccess
, BB
, Point
);
1354 MemoryUseOrDef
*MemorySSAUpdater::createMemoryAccessBefore(
1355 Instruction
*I
, MemoryAccess
*Definition
, MemoryUseOrDef
*InsertPt
) {
1356 assert(I
->getParent() == InsertPt
->getBlock() &&
1357 "New and old access must be in the same block");
1358 MemoryUseOrDef
*NewAccess
= MSSA
->createDefinedAccess(I
, Definition
);
1359 MSSA
->insertIntoListsBefore(NewAccess
, InsertPt
->getBlock(),
1360 InsertPt
->getIterator());
1364 MemoryUseOrDef
*MemorySSAUpdater::createMemoryAccessAfter(
1365 Instruction
*I
, MemoryAccess
*Definition
, MemoryAccess
*InsertPt
) {
1366 assert(I
->getParent() == InsertPt
->getBlock() &&
1367 "New and old access must be in the same block");
1368 MemoryUseOrDef
*NewAccess
= MSSA
->createDefinedAccess(I
, Definition
);
1369 MSSA
->insertIntoListsBefore(NewAccess
, InsertPt
->getBlock(),
1370 ++InsertPt
->getIterator());