blob: 792ddef4e70e2ef9888cec586f339d1dde08a0f8 [file] [log] [blame]
Daniel Berlinae6b8b62017-01-28 01:35:02 +00001//===-- MemorySSAUpdater.cpp - Memory SSA Updater--------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------===//
9//
10// This file implements the MemorySSAUpdater class.
11//
12//===----------------------------------------------------------------===//
13#include "llvm/Transforms/Utils/MemorySSAUpdater.h"
14#include "llvm/ADT/STLExtras.h"
15#include "llvm/ADT/SmallPtrSet.h"
16#include "llvm/ADT/SmallSet.h"
17#include "llvm/IR/DataLayout.h"
18#include "llvm/IR/Dominators.h"
19#include "llvm/IR/GlobalVariable.h"
20#include "llvm/IR/IRBuilder.h"
21#include "llvm/IR/IntrinsicInst.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"
27#include "llvm/Transforms/Utils/MemorySSA.h"
28#include <algorithm>
29
30#define DEBUG_TYPE "memoryssa"
31using namespace llvm;
32namespace llvm {
33// This is the marker algorithm from "Simple and Efficient Construction of
34// Static Single Assignment Form"
35// The simple, non-marker algorithm places phi nodes at any join
36// Here, we place markers, and only place phi nodes if they end up necessary.
37// They are only necessary if they break a cycle (IE we recursively visit
38// ourselves again), or we discover, while getting the value of the operands,
39// that there are two or more definitions needing to be merged.
40// This still will leave non-minimal form in the case of irreducible control
41// flow, where phi nodes may be in cycles with themselves, but unnecessary.
42MemoryAccess *MemorySSAUpdater::getPreviousDefRecursive(BasicBlock *BB) {
43 // Single predecessor case, just recurse, we can only have one definition.
44 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
45 return getPreviousDefFromEnd(Pred);
46 } else if (VisitedBlocks.count(BB)) {
47 // We hit our node again, meaning we had a cycle, we must insert a phi
48 // node to break it so we have an operand. The only case this will
49 // insert useless phis is if we have irreducible control flow.
50 return MSSA->createMemoryPhi(BB);
51 } else if (VisitedBlocks.insert(BB).second) {
52 // Mark us visited so we can detect a cycle
53 SmallVector<MemoryAccess *, 8> PhiOps;
54
55 // Recurse to get the values in our predecessors for placement of a
56 // potential phi node. This will insert phi nodes if we cycle in order to
57 // break the cycle and have an operand.
58 for (auto *Pred : predecessors(BB))
59 PhiOps.push_back(getPreviousDefFromEnd(Pred));
60
61 // Now try to simplify the ops to avoid placing a phi.
62 // This may return null if we never created a phi yet, that's okay
63 MemoryPhi *Phi = dyn_cast_or_null<MemoryPhi>(MSSA->getMemoryAccess(BB));
64 bool PHIExistsButNeedsUpdate = false;
65 // See if the existing phi operands match what we need.
66 // Unlike normal SSA, we only allow one phi node per block, so we can't just
67 // create a new one.
68 if (Phi && Phi->getNumOperands() != 0)
69 if (!std::equal(Phi->op_begin(), Phi->op_end(), PhiOps.begin())) {
70 PHIExistsButNeedsUpdate = true;
71 }
72
73 // See if we can avoid the phi by simplifying it.
74 auto *Result = tryRemoveTrivialPhi(Phi, PhiOps);
75 // If we couldn't simplify, we may have to create a phi
76 if (Result == Phi) {
77 if (!Phi)
78 Phi = MSSA->createMemoryPhi(BB);
79
80 // These will have been filled in by the recursive read we did above.
81 if (PHIExistsButNeedsUpdate) {
82 std::copy(PhiOps.begin(), PhiOps.end(), Phi->op_begin());
83 std::copy(pred_begin(BB), pred_end(BB), Phi->block_begin());
84 } else {
85 unsigned i = 0;
86 for (auto *Pred : predecessors(BB))
87 Phi->addIncoming(PhiOps[i++], Pred);
88 }
89
90 Result = Phi;
91 }
92 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Result))
93 InsertedPHIs.push_back(MP);
94 // Set ourselves up for the next variable by resetting visited state.
95 VisitedBlocks.erase(BB);
96 return Result;
97 }
98 llvm_unreachable("Should have hit one of the three cases above");
99}
100
101// This starts at the memory access, and goes backwards in the block to find the
102// previous definition. If a definition is not found the block of the access,
103// it continues globally, creating phi nodes to ensure we have a single
104// definition.
105MemoryAccess *MemorySSAUpdater::getPreviousDef(MemoryAccess *MA) {
106 auto *LocalResult = getPreviousDefInBlock(MA);
107
108 return LocalResult ? LocalResult : getPreviousDefRecursive(MA->getBlock());
109}
110
111// This starts at the memory access, and goes backwards in the block to the find
112// the previous definition. If the definition is not found in the block of the
113// access, it returns nullptr.
114MemoryAccess *MemorySSAUpdater::getPreviousDefInBlock(MemoryAccess *MA) {
115 auto *Defs = MSSA->getWritableBlockDefs(MA->getBlock());
116
117 // It's possible there are no defs, or we got handed the first def to start.
118 if (Defs) {
119 // If this is a def, we can just use the def iterators.
120 if (!isa<MemoryUse>(MA)) {
121 auto Iter = MA->getReverseDefsIterator();
122 ++Iter;
123 if (Iter != Defs->rend())
124 return &*Iter;
125 } else {
126 // Otherwise, have to walk the all access iterator.
127 auto Iter = MA->getReverseIterator();
128 ++Iter;
129 while (&*Iter != &*Defs->begin()) {
130 if (!isa<MemoryUse>(*Iter))
131 return &*Iter;
132 --Iter;
133 }
134 // At this point it must be pointing at firstdef
135 assert(&*Iter == &*Defs->begin() &&
136 "Should have hit first def walking backwards");
137 return &*Iter;
138 }
139 }
140 return nullptr;
141}
142
143// This starts at the end of block
144MemoryAccess *MemorySSAUpdater::getPreviousDefFromEnd(BasicBlock *BB) {
145 auto *Defs = MSSA->getWritableBlockDefs(BB);
146
147 if (Defs)
148 return &*Defs->rbegin();
149
150 return getPreviousDefRecursive(BB);
151}
152// Recurse over a set of phi uses to eliminate the trivial ones
153MemoryAccess *MemorySSAUpdater::recursePhi(MemoryAccess *Phi) {
154 if (!Phi)
155 return nullptr;
156 TrackingVH<MemoryAccess> Res(Phi);
157 SmallVector<TrackingVH<Value>, 8> Uses;
158 std::copy(Phi->user_begin(), Phi->user_end(), std::back_inserter(Uses));
159 for (auto &U : Uses) {
160 if (MemoryPhi *UsePhi = dyn_cast<MemoryPhi>(&*U)) {
161 auto OperRange = UsePhi->operands();
162 tryRemoveTrivialPhi(UsePhi, OperRange);
163 }
164 }
165 return Res;
166}
167
168// Eliminate trivial phis
169// Phis are trivial if they are defined either by themselves, or all the same
170// argument.
171// IE phi(a, a) or b = phi(a, b) or c = phi(a, a, c)
172// We recursively try to remove them.
173template <class RangeType>
174MemoryAccess *MemorySSAUpdater::tryRemoveTrivialPhi(MemoryPhi *Phi,
175 RangeType &Operands) {
176 // Detect equal or self arguments
177 MemoryAccess *Same = nullptr;
178 for (auto &Op : Operands) {
179 // If the same or self, good so far
180 if (Op == Phi || Op == Same)
181 continue;
182 // not the same, return the phi since it's not eliminatable by us
183 if (Same)
184 return Phi;
185 Same = cast<MemoryAccess>(Op);
186 }
187 // Never found a non-self reference, the phi is undef
188 if (Same == nullptr)
189 return MSSA->getLiveOnEntryDef();
190 if (Phi) {
191 Phi->replaceAllUsesWith(Same);
192 MSSA->removeMemoryAccess(Phi);
193 }
194
195 // We should only end up recursing in case we replaced something, in which
196 // case, we may have made other Phis trivial.
197 return recursePhi(Same);
198}
199
200void MemorySSAUpdater::insertUse(MemoryUse *MU) {
201 InsertedPHIs.clear();
202 MU->setDefiningAccess(getPreviousDef(MU));
203 // Unlike for defs, there is no extra work to do. Because uses do not create
204 // new may-defs, there are only two cases:
205 //
206 // 1. There was a def already below us, and therefore, we should not have
207 // created a phi node because it was already needed for the def.
208 //
209 // 2. There is no def below us, and therefore, there is no extra renaming work
210 // to do.
211}
212
213void setMemoryPhiValueForBlock(MemoryPhi *MP, const BasicBlock *BB,
214 MemoryAccess *NewDef) {
215 // Replace any operand with us an incoming block with the new defining
216 // access.
217 int i = MP->getBasicBlockIndex(BB);
218 assert(i != -1 && "Should have found the basic block in the phi");
219 while (MP->getIncomingBlock(i) == BB) {
220 // Unlike above, there is already a phi node here, so we only need
221 // to set the right value.
222 MP->setIncomingValue(i, NewDef);
223 ++i;
224 }
225}
226
227// A brief description of the algorithm:
228// First, we compute what should define the new def, using the SSA
229// construction algorithm.
230// Then, we update the defs below us (and any new phi nodes) in the graph to
231// point to the correct new defs, to ensure we only have one variable, and no
232// disconnected stores.
233void MemorySSAUpdater::insertDef(MemoryDef *MD) {
234 InsertedPHIs.clear();
235
236 // See if we had a local def, and if not, go hunting.
237 MemoryAccess *DefBefore = getPreviousDefInBlock(MD);
238 bool DefBeforeSameBlock = DefBefore != nullptr;
239 if (!DefBefore)
240 DefBefore = getPreviousDefRecursive(MD->getBlock());
241
242 // There is a def before us, which means we can replace any store/phi uses
243 // of that thing with us, since we are in the way of whatever was there
244 // before.
245 // We now define that def's memorydefs and memoryphis
246 for (auto UI = DefBefore->use_begin(), UE = DefBefore->use_end(); UI != UE;) {
247 Use &U = *UI++;
248 // Leave the uses alone
249 if (isa<MemoryUse>(U.getUser()))
250 continue;
251 U.set(MD);
252 }
253 // and that def is now our defining access.
254 // We change them in this order otherwise we will appear in the use list
255 // above and reset ourselves.
256 MD->setDefiningAccess(DefBefore);
257
258 SmallVector<MemoryAccess *, 8> FixupList(InsertedPHIs.begin(),
259 InsertedPHIs.end());
260 if (!DefBeforeSameBlock) {
261 // If there was a local def before us, we must have the same effect it
262 // did. Because every may-def is the same, any phis/etc we would create, it
263 // would also have created. If there was no local def before us, we
264 // performed a global update, and have to search all successors and make
265 // sure we update the first def in each of them (following all paths until
266 // we hit the first def along each path). This may also insert phi nodes.
267 // TODO: There are other cases we can skip this work, such as when we have a
268 // single successor, and only used a straight line of single pred blocks
269 // backwards to find the def. To make that work, we'd have to track whether
270 // getDefRecursive only ever used the single predecessor case. These types
271 // of paths also only exist in between CFG simplifications.
272 FixupList.push_back(MD);
273 }
274
275 while (!FixupList.empty()) {
276 unsigned StartingPHISize = InsertedPHIs.size();
277 fixupDefs(FixupList);
278 FixupList.clear();
279 // Put any new phis on the fixup list, and process them
280 FixupList.append(InsertedPHIs.end() - StartingPHISize, InsertedPHIs.end());
281 }
282}
283
284void MemorySSAUpdater::fixupDefs(const SmallVectorImpl<MemoryAccess *> &Vars) {
285 SmallPtrSet<const BasicBlock *, 8> Seen;
286 SmallVector<const BasicBlock *, 16> Worklist;
287 for (auto *NewDef : Vars) {
288 // First, see if there is a local def after the operand.
289 auto *Defs = MSSA->getWritableBlockDefs(NewDef->getBlock());
290 auto DefIter = NewDef->getDefsIterator();
291
292 // If there is a local def after us, we only have to rename that.
293 if (++DefIter != Defs->end()) {
294 cast<MemoryDef>(DefIter)->setDefiningAccess(NewDef);
295 continue;
296 }
297
298 // Otherwise, we need to search down through the CFG.
299 // For each of our successors, handle it directly if their is a phi, or
300 // place on the fixup worklist.
301 for (const auto *S : successors(NewDef->getBlock())) {
302 if (auto *MP = MSSA->getMemoryAccess(S))
303 setMemoryPhiValueForBlock(MP, NewDef->getBlock(), NewDef);
304 else
305 Worklist.push_back(S);
306 }
307
308 while (!Worklist.empty()) {
309 const BasicBlock *FixupBlock = Worklist.back();
310 Worklist.pop_back();
311
312 // Get the first def in the block that isn't a phi node.
313 if (auto *Defs = MSSA->getWritableBlockDefs(FixupBlock)) {
314 auto *FirstDef = &*Defs->begin();
315 // The loop above and below should have taken care of phi nodes
316 assert(!isa<MemoryPhi>(FirstDef) &&
317 "Should have already handled phi nodes!");
318 // We are now this def's defining access, make sure we actually dominate
319 // it
320 assert(MSSA->dominates(NewDef, FirstDef) &&
321 "Should have dominated the new access");
322
323 // This may insert new phi nodes, because we are not guaranteed the
324 // block we are processing has a single pred, and depending where the
325 // store was inserted, it may require phi nodes below it.
326 cast<MemoryDef>(FirstDef)->setDefiningAccess(getPreviousDef(FirstDef));
327 return;
328 }
329 // We didn't find a def, so we must continue.
330 for (const auto *S : successors(FixupBlock)) {
331 // If there is a phi node, handle it.
332 // Otherwise, put the block on the worklist
333 if (auto *MP = MSSA->getMemoryAccess(S))
334 setMemoryPhiValueForBlock(MP, FixupBlock, NewDef);
335 else {
336 // If we cycle, we should have ended up at a phi node that we already
337 // processed. FIXME: Double check this
338 if (!Seen.insert(S).second)
339 continue;
340 Worklist.push_back(S);
341 }
342 }
343 }
344 }
345}
346
347// Move What before Where in the MemorySSA IR.
348void MemorySSAUpdater::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
349 MemorySSA::AccessList::iterator Where) {
350 // Replace all our users with our defining access.
351 What->replaceAllUsesWith(What->getDefiningAccess());
352
353 // Let MemorySSA take care of moving it around in the lists.
354 MSSA->moveTo(What, BB, Where);
355
356 // Now reinsert it into the IR and do whatever fixups needed.
357 if (auto *MD = dyn_cast<MemoryDef>(What))
358 insertDef(MD);
359 else
360 insertUse(cast<MemoryUse>(What));
361}
362// Move What before Where in the MemorySSA IR.
363void MemorySSAUpdater::moveBefore(MemoryUseOrDef *What, MemoryUseOrDef *Where) {
364 moveTo(What, Where->getBlock(), Where->getIterator());
365}
366
367// Move What after Where in the MemorySSA IR.
368void MemorySSAUpdater::moveAfter(MemoryUseOrDef *What, MemoryUseOrDef *Where) {
369 moveTo(What, Where->getBlock(), ++Where->getIterator());
370}
371
372} // namespace llvm