blob: cd7f06844f4a34a90bd6a489ced7af6f3a96480d [file] [log] [blame]
Chris Lattner93f3bcf2009-10-10 09:04:27 +00001//===- SSAUpdater.cpp - Unstructured SSA Update Tool ----------------------===//
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 SSAUpdater class.
11//
12//===----------------------------------------------------------------------===//
13
Bob Wilson84bd6b02010-04-17 03:08:24 +000014#define DEBUG_TYPE "ssaupdater"
Jay Foad562b84b2011-04-11 09:35:34 +000015#include "llvm/Constants.h"
Chris Lattner93f3bcf2009-10-10 09:04:27 +000016#include "llvm/Instructions.h"
17#include "llvm/ADT/DenseMap.h"
Duncan Sandscdbd9922010-11-16 17:41:24 +000018#include "llvm/Analysis/InstructionSimplify.h"
Bob Wilson84bd6b02010-04-17 03:08:24 +000019#include "llvm/Support/AlignOf.h"
20#include "llvm/Support/Allocator.h"
Chris Lattner93f3bcf2009-10-10 09:04:27 +000021#include "llvm/Support/CFG.h"
22#include "llvm/Support/Debug.h"
Chris Lattner93f3bcf2009-10-10 09:04:27 +000023#include "llvm/Support/raw_ostream.h"
Bob Wilson4aad88d2010-05-04 23:18:19 +000024#include "llvm/Transforms/Utils/SSAUpdater.h"
25#include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
Chris Lattner93f3bcf2009-10-10 09:04:27 +000026using namespace llvm;
27
Bob Wilson84bd6b02010-04-17 03:08:24 +000028typedef DenseMap<BasicBlock*, Value*> AvailableValsTy;
Chris Lattner93f3bcf2009-10-10 09:04:27 +000029static AvailableValsTy &getAvailableVals(void *AV) {
30 return *static_cast<AvailableValsTy*>(AV);
31}
32
Chris Lattnerf5a1fb62009-10-10 23:15:24 +000033SSAUpdater::SSAUpdater(SmallVectorImpl<PHINode*> *NewPHI)
Duncan Sandsfc6e29d2010-09-02 08:14:03 +000034 : AV(0), ProtoType(0), ProtoName(), InsertedPHIs(NewPHI) {}
Chris Lattner93f3bcf2009-10-10 09:04:27 +000035
36SSAUpdater::~SSAUpdater() {
37 delete &getAvailableVals(AV);
Chris Lattner93f3bcf2009-10-10 09:04:27 +000038}
39
40/// Initialize - Reset this object to get ready for a new set of SSA
Duncan Sandsfc6e29d2010-09-02 08:14:03 +000041/// updates with type 'Ty'. PHI nodes get a name based on 'Name'.
42void SSAUpdater::Initialize(const Type *Ty, StringRef Name) {
Chris Lattner93f3bcf2009-10-10 09:04:27 +000043 if (AV == 0)
44 AV = new AvailableValsTy();
45 else
46 getAvailableVals(AV).clear();
Duncan Sandsfc6e29d2010-09-02 08:14:03 +000047 ProtoType = Ty;
48 ProtoName = Name;
Chris Lattner93f3bcf2009-10-10 09:04:27 +000049}
50
Chris Lattner0bef5622009-10-10 23:41:48 +000051/// HasValueForBlock - Return true if the SSAUpdater already has a value for
52/// the specified block.
53bool SSAUpdater::HasValueForBlock(BasicBlock *BB) const {
54 return getAvailableVals(AV).count(BB);
55}
56
Chris Lattner93f3bcf2009-10-10 09:04:27 +000057/// AddAvailableValue - Indicate that a rewritten value is available in the
58/// specified block with the specified value.
59void SSAUpdater::AddAvailableValue(BasicBlock *BB, Value *V) {
Duncan Sandsfc6e29d2010-09-02 08:14:03 +000060 assert(ProtoType != 0 && "Need to initialize SSAUpdater");
61 assert(ProtoType == V->getType() &&
Chris Lattner93f3bcf2009-10-10 09:04:27 +000062 "All rewritten values must have the same type");
63 getAvailableVals(AV)[BB] = V;
64}
65
Bob Wilsone98585e2010-01-27 22:01:02 +000066/// IsEquivalentPHI - Check if PHI has the same incoming value as specified
67/// in ValueMapping for each predecessor block.
Bob Wilson84bd6b02010-04-17 03:08:24 +000068static bool IsEquivalentPHI(PHINode *PHI,
Bob Wilsone98585e2010-01-27 22:01:02 +000069 DenseMap<BasicBlock*, Value*> &ValueMapping) {
70 unsigned PHINumValues = PHI->getNumIncomingValues();
71 if (PHINumValues != ValueMapping.size())
72 return false;
73
74 // Scan the phi to see if it matches.
75 for (unsigned i = 0, e = PHINumValues; i != e; ++i)
76 if (ValueMapping[PHI->getIncomingBlock(i)] !=
77 PHI->getIncomingValue(i)) {
78 return false;
79 }
80
81 return true;
82}
83
Chris Lattner1a8d4de2009-10-10 23:00:11 +000084/// GetValueAtEndOfBlock - Construct SSA form, materializing a value that is
85/// live at the end of the specified block.
Chris Lattner5fb10722009-10-10 22:41:58 +000086Value *SSAUpdater::GetValueAtEndOfBlock(BasicBlock *BB) {
Chris Lattner5fb10722009-10-10 22:41:58 +000087 Value *Res = GetValueAtEndOfBlockInternal(BB);
Chris Lattner93f3bcf2009-10-10 09:04:27 +000088 return Res;
89}
90
Chris Lattner1a8d4de2009-10-10 23:00:11 +000091/// GetValueInMiddleOfBlock - Construct SSA form, materializing a value that
92/// is live in the middle of the specified block.
93///
94/// GetValueInMiddleOfBlock is the same as GetValueAtEndOfBlock except in one
95/// important case: if there is a definition of the rewritten value after the
96/// 'use' in BB. Consider code like this:
97///
98/// X1 = ...
99/// SomeBB:
100/// use(X)
101/// X2 = ...
102/// br Cond, SomeBB, OutBB
103///
104/// In this case, there are two values (X1 and X2) added to the AvailableVals
105/// set by the client of the rewriter, and those values are both live out of
106/// their respective blocks. However, the use of X happens in the *middle* of
107/// a block. Because of this, we need to insert a new PHI node in SomeBB to
108/// merge the appropriate values, and this value isn't live out of the block.
109///
110Value *SSAUpdater::GetValueInMiddleOfBlock(BasicBlock *BB) {
111 // If there is no definition of the renamed variable in this block, just use
112 // GetValueAtEndOfBlock to do our work.
Bob Wilson84bd6b02010-04-17 03:08:24 +0000113 if (!HasValueForBlock(BB))
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000114 return GetValueAtEndOfBlock(BB);
Duncan Sandsed903422009-10-16 15:20:13 +0000115
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000116 // Otherwise, we have the hard case. Get the live-in values for each
117 // predecessor.
118 SmallVector<std::pair<BasicBlock*, Value*>, 8> PredValues;
119 Value *SingularValue = 0;
Duncan Sandsed903422009-10-16 15:20:13 +0000120
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000121 // We can get our predecessor info by walking the pred_iterator list, but it
122 // is relatively slow. If we already have PHI nodes in this block, walk one
123 // of them to get the predecessor list instead.
124 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
125 for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) {
126 BasicBlock *PredBB = SomePhi->getIncomingBlock(i);
127 Value *PredVal = GetValueAtEndOfBlock(PredBB);
128 PredValues.push_back(std::make_pair(PredBB, PredVal));
Duncan Sandsed903422009-10-16 15:20:13 +0000129
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000130 // Compute SingularValue.
131 if (i == 0)
132 SingularValue = PredVal;
133 else if (PredVal != SingularValue)
134 SingularValue = 0;
135 }
136 } else {
137 bool isFirstPred = true;
138 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
139 BasicBlock *PredBB = *PI;
140 Value *PredVal = GetValueAtEndOfBlock(PredBB);
141 PredValues.push_back(std::make_pair(PredBB, PredVal));
Duncan Sandsed903422009-10-16 15:20:13 +0000142
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000143 // Compute SingularValue.
144 if (isFirstPred) {
145 SingularValue = PredVal;
146 isFirstPred = false;
147 } else if (PredVal != SingularValue)
148 SingularValue = 0;
149 }
150 }
Duncan Sandsed903422009-10-16 15:20:13 +0000151
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000152 // If there are no predecessors, just return undef.
153 if (PredValues.empty())
Duncan Sandsfc6e29d2010-09-02 08:14:03 +0000154 return UndefValue::get(ProtoType);
Duncan Sandsed903422009-10-16 15:20:13 +0000155
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000156 // Otherwise, if all the merged values are the same, just use it.
157 if (SingularValue != 0)
158 return SingularValue;
Duncan Sandsed903422009-10-16 15:20:13 +0000159
Bob Wilson84bd6b02010-04-17 03:08:24 +0000160 // Otherwise, we do need a PHI: check to see if we already have one available
161 // in this block that produces the right value.
162 if (isa<PHINode>(BB->begin())) {
163 DenseMap<BasicBlock*, Value*> ValueMapping(PredValues.begin(),
164 PredValues.end());
165 PHINode *SomePHI;
166 for (BasicBlock::iterator It = BB->begin();
167 (SomePHI = dyn_cast<PHINode>(It)); ++It) {
168 if (IsEquivalentPHI(SomePHI, ValueMapping))
169 return SomePHI;
170 }
171 }
Bob Wilsone98585e2010-01-27 22:01:02 +0000172
Chris Lattner4c1e3da2009-12-21 07:16:11 +0000173 // Ok, we have no way out, insert a new one now.
Jay Foad3ecfc862011-03-30 11:28:46 +0000174 PHINode *InsertedPHI = PHINode::Create(ProtoType, PredValues.size(),
175 ProtoName, &BB->front());
Duncan Sandsed903422009-10-16 15:20:13 +0000176
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000177 // Fill in all the predecessors of the PHI.
178 for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
179 InsertedPHI->addIncoming(PredValues[i].second, PredValues[i].first);
Duncan Sandsed903422009-10-16 15:20:13 +0000180
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000181 // See if the PHI node can be merged to a single value. This can happen in
182 // loop cases when we get a PHI of itself and one other value.
Duncan Sandscdbd9922010-11-16 17:41:24 +0000183 if (Value *V = SimplifyInstruction(InsertedPHI)) {
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000184 InsertedPHI->eraseFromParent();
Duncan Sandscdbd9922010-11-16 17:41:24 +0000185 return V;
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000186 }
Chris Lattnerf5a1fb62009-10-10 23:15:24 +0000187
188 // If the client wants to know about all new instructions, tell it.
189 if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
Duncan Sandsed903422009-10-16 15:20:13 +0000190
David Greene1af40ca2010-01-05 01:26:49 +0000191 DEBUG(dbgs() << " Inserted PHI: " << *InsertedPHI << "\n");
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000192 return InsertedPHI;
193}
194
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000195/// RewriteUse - Rewrite a use of the symbolic value. This handles PHI nodes,
196/// which use their value in the corresponding predecessor.
197void SSAUpdater::RewriteUse(Use &U) {
198 Instruction *User = cast<Instruction>(U.getUser());
Bob Wilson84bd6b02010-04-17 03:08:24 +0000199
Chris Lattner88a86242009-10-20 20:27:49 +0000200 Value *V;
201 if (PHINode *UserPN = dyn_cast<PHINode>(User))
202 V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
203 else
204 V = GetValueInMiddleOfBlock(User->getParent());
Duncan Sandsed903422009-10-16 15:20:13 +0000205
Torok Edwinf9933272009-10-20 15:42:00 +0000206 U.set(V);
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000207}
208
Chris Lattnerffd9bee2010-08-29 04:54:06 +0000209/// RewriteUseAfterInsertions - Rewrite a use, just like RewriteUse. However,
210/// this version of the method can rewrite uses in the same block as a
211/// definition, because it assumes that all uses of a value are below any
212/// inserted values.
213void SSAUpdater::RewriteUseAfterInsertions(Use &U) {
214 Instruction *User = cast<Instruction>(U.getUser());
215
216 Value *V;
217 if (PHINode *UserPN = dyn_cast<PHINode>(User))
218 V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
219 else
220 V = GetValueAtEndOfBlock(User->getParent());
221
222 U.set(V);
223}
224
Bob Wilson4aad88d2010-05-04 23:18:19 +0000225/// PHIiter - Iterator for PHI operands. This is used for the PHI_iterator
226/// in the SSAUpdaterImpl template.
227namespace {
228 class PHIiter {
229 private:
230 PHINode *PHI;
231 unsigned idx;
232
233 public:
234 explicit PHIiter(PHINode *P) // begin iterator
235 : PHI(P), idx(0) {}
236 PHIiter(PHINode *P, bool) // end iterator
237 : PHI(P), idx(PHI->getNumIncomingValues()) {}
238
239 PHIiter &operator++() { ++idx; return *this; }
240 bool operator==(const PHIiter& x) const { return idx == x.idx; }
241 bool operator!=(const PHIiter& x) const { return !operator==(x); }
242 Value *getIncomingValue() { return PHI->getIncomingValue(idx); }
243 BasicBlock *getIncomingBlock() { return PHI->getIncomingBlock(idx); }
244 };
245}
246
247/// SSAUpdaterTraits<SSAUpdater> - Traits for the SSAUpdaterImpl template,
248/// specialized for SSAUpdater.
249namespace llvm {
250template<>
251class SSAUpdaterTraits<SSAUpdater> {
252public:
253 typedef BasicBlock BlkT;
254 typedef Value *ValT;
255 typedef PHINode PhiT;
256
257 typedef succ_iterator BlkSucc_iterator;
258 static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return succ_begin(BB); }
259 static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return succ_end(BB); }
260
261 typedef PHIiter PHI_iterator;
262 static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
263 static inline PHI_iterator PHI_end(PhiT *PHI) {
264 return PHI_iterator(PHI, true);
265 }
266
267 /// FindPredecessorBlocks - Put the predecessors of Info->BB into the Preds
268 /// vector, set Info->NumPreds, and allocate space in Info->Preds.
269 static void FindPredecessorBlocks(BasicBlock *BB,
270 SmallVectorImpl<BasicBlock*> *Preds) {
271 // We can get our predecessor info by walking the pred_iterator list,
272 // but it is relatively slow. If we already have PHI nodes in this
273 // block, walk one of them to get the predecessor list instead.
274 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
275 for (unsigned PI = 0, E = SomePhi->getNumIncomingValues(); PI != E; ++PI)
276 Preds->push_back(SomePhi->getIncomingBlock(PI));
277 } else {
278 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
279 Preds->push_back(*PI);
280 }
281 }
282
283 /// GetUndefVal - Get an undefined value of the same type as the value
284 /// being handled.
285 static Value *GetUndefVal(BasicBlock *BB, SSAUpdater *Updater) {
Duncan Sandsfc6e29d2010-09-02 08:14:03 +0000286 return UndefValue::get(Updater->ProtoType);
Bob Wilson4aad88d2010-05-04 23:18:19 +0000287 }
288
289 /// CreateEmptyPHI - Create a new PHI instruction in the specified block.
290 /// Reserve space for the operands but do not fill them in yet.
291 static Value *CreateEmptyPHI(BasicBlock *BB, unsigned NumPreds,
292 SSAUpdater *Updater) {
Jay Foad3ecfc862011-03-30 11:28:46 +0000293 PHINode *PHI = PHINode::Create(Updater->ProtoType, NumPreds,
294 Updater->ProtoName, &BB->front());
Bob Wilson4aad88d2010-05-04 23:18:19 +0000295 return PHI;
296 }
297
298 /// AddPHIOperand - Add the specified value as an operand of the PHI for
299 /// the specified predecessor block.
300 static void AddPHIOperand(PHINode *PHI, Value *Val, BasicBlock *Pred) {
301 PHI->addIncoming(Val, Pred);
302 }
303
304 /// InstrIsPHI - Check if an instruction is a PHI.
305 ///
306 static PHINode *InstrIsPHI(Instruction *I) {
307 return dyn_cast<PHINode>(I);
308 }
309
310 /// ValueIsPHI - Check if a value is a PHI.
311 ///
312 static PHINode *ValueIsPHI(Value *Val, SSAUpdater *Updater) {
313 return dyn_cast<PHINode>(Val);
314 }
315
316 /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
317 /// operands, i.e., it was just added.
318 static PHINode *ValueIsNewPHI(Value *Val, SSAUpdater *Updater) {
319 PHINode *PHI = ValueIsPHI(Val, Updater);
320 if (PHI && PHI->getNumIncomingValues() == 0)
321 return PHI;
322 return 0;
323 }
324
325 /// GetPHIValue - For the specified PHI instruction, return the value
326 /// that it defines.
327 static Value *GetPHIValue(PHINode *PHI) {
328 return PHI;
329 }
330};
331
332} // End llvm namespace
333
Chris Lattner5fb10722009-10-10 22:41:58 +0000334/// GetValueAtEndOfBlockInternal - Check to see if AvailableVals has an entry
335/// for the specified BB and if so, return it. If not, construct SSA form by
Bob Wilson84bd6b02010-04-17 03:08:24 +0000336/// first calculating the required placement of PHIs and then inserting new
337/// PHIs where needed.
Chris Lattner5fb10722009-10-10 22:41:58 +0000338Value *SSAUpdater::GetValueAtEndOfBlockInternal(BasicBlock *BB) {
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000339 AvailableValsTy &AvailableVals = getAvailableVals(AV);
Bob Wilson84bd6b02010-04-17 03:08:24 +0000340 if (Value *V = AvailableVals[BB])
341 return V;
Duncan Sandsed903422009-10-16 15:20:13 +0000342
Bob Wilson4aad88d2010-05-04 23:18:19 +0000343 SSAUpdaterImpl<SSAUpdater> Impl(this, &AvailableVals, InsertedPHIs);
344 return Impl.GetValue(BB);
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000345}
Chris Lattnera2d845a2011-01-14 19:36:13 +0000346
347//===----------------------------------------------------------------------===//
348// LoadAndStorePromoter Implementation
349//===----------------------------------------------------------------------===//
350
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000351LoadAndStorePromoter::
352LoadAndStorePromoter(const SmallVectorImpl<Instruction*> &Insts,
353 SSAUpdater &S, StringRef BaseName) : SSA(S) {
Chris Lattnera2d845a2011-01-14 19:36:13 +0000354 if (Insts.empty()) return;
355
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000356 Value *SomeVal;
Chris Lattnera2d845a2011-01-14 19:36:13 +0000357 if (LoadInst *LI = dyn_cast<LoadInst>(Insts[0]))
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000358 SomeVal = LI;
Chris Lattnera2d845a2011-01-14 19:36:13 +0000359 else
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000360 SomeVal = cast<StoreInst>(Insts[0])->getOperand(0);
361
362 if (BaseName.empty())
363 BaseName = SomeVal->getName();
364 SSA.Initialize(SomeVal->getType(), BaseName);
365}
366
367
368void LoadAndStorePromoter::
369run(const SmallVectorImpl<Instruction*> &Insts) const {
Chris Lattnera2d845a2011-01-14 19:36:13 +0000370
371 // First step: bucket up uses of the alloca by the block they occur in.
372 // This is important because we have to handle multiple defs/uses in a block
373 // ourselves: SSAUpdater is purely for cross-block references.
374 // FIXME: Want a TinyVector<Instruction*> since there is often 0/1 element.
375 DenseMap<BasicBlock*, std::vector<Instruction*> > UsesByBlock;
376
377 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
378 Instruction *User = Insts[i];
379 UsesByBlock[User->getParent()].push_back(User);
380 }
381
382 // Okay, now we can iterate over all the blocks in the function with uses,
383 // processing them. Keep track of which loads are loading a live-in value.
384 // Walk the uses in the use-list order to be determinstic.
385 SmallVector<LoadInst*, 32> LiveInLoads;
386 DenseMap<Value*, Value*> ReplacedLoads;
387
388 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
389 Instruction *User = Insts[i];
390 BasicBlock *BB = User->getParent();
391 std::vector<Instruction*> &BlockUses = UsesByBlock[BB];
392
393 // If this block has already been processed, ignore this repeat use.
394 if (BlockUses.empty()) continue;
395
396 // Okay, this is the first use in the block. If this block just has a
397 // single user in it, we can rewrite it trivially.
398 if (BlockUses.size() == 1) {
399 // If it is a store, it is a trivial def of the value in the block.
400 if (StoreInst *SI = dyn_cast<StoreInst>(User))
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000401 SSA.AddAvailableValue(BB, SI->getOperand(0));
Chris Lattnera2d845a2011-01-14 19:36:13 +0000402 else
403 // Otherwise it is a load, queue it to rewrite as a live-in load.
404 LiveInLoads.push_back(cast<LoadInst>(User));
405 BlockUses.clear();
406 continue;
407 }
408
409 // Otherwise, check to see if this block is all loads.
410 bool HasStore = false;
411 for (unsigned i = 0, e = BlockUses.size(); i != e; ++i) {
412 if (isa<StoreInst>(BlockUses[i])) {
413 HasStore = true;
414 break;
415 }
416 }
417
418 // If so, we can queue them all as live in loads. We don't have an
419 // efficient way to tell which on is first in the block and don't want to
420 // scan large blocks, so just add all loads as live ins.
421 if (!HasStore) {
422 for (unsigned i = 0, e = BlockUses.size(); i != e; ++i)
423 LiveInLoads.push_back(cast<LoadInst>(BlockUses[i]));
424 BlockUses.clear();
425 continue;
426 }
427
428 // Otherwise, we have mixed loads and stores (or just a bunch of stores).
429 // Since SSAUpdater is purely for cross-block values, we need to determine
430 // the order of these instructions in the block. If the first use in the
431 // block is a load, then it uses the live in value. The last store defines
432 // the live out value. We handle this by doing a linear scan of the block.
433 Value *StoredValue = 0;
434 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
435 if (LoadInst *L = dyn_cast<LoadInst>(II)) {
436 // If this is a load from an unrelated pointer, ignore it.
437 if (!isInstInList(L, Insts)) continue;
438
439 // If we haven't seen a store yet, this is a live in use, otherwise
440 // use the stored value.
441 if (StoredValue) {
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000442 replaceLoadWithValue(L, StoredValue);
Chris Lattnera2d845a2011-01-14 19:36:13 +0000443 L->replaceAllUsesWith(StoredValue);
444 ReplacedLoads[L] = StoredValue;
445 } else {
446 LiveInLoads.push_back(L);
447 }
448 continue;
449 }
450
451 if (StoreInst *S = dyn_cast<StoreInst>(II)) {
452 // If this is a store to an unrelated pointer, ignore it.
453 if (!isInstInList(S, Insts)) continue;
454
455 // Remember that this is the active value in the block.
456 StoredValue = S->getOperand(0);
457 }
458 }
459
460 // The last stored value that happened is the live-out for the block.
461 assert(StoredValue && "Already checked that there is a store in block");
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000462 SSA.AddAvailableValue(BB, StoredValue);
Chris Lattnera2d845a2011-01-14 19:36:13 +0000463 BlockUses.clear();
464 }
465
466 // Okay, now we rewrite all loads that use live-in values in the loop,
467 // inserting PHI nodes as necessary.
468 for (unsigned i = 0, e = LiveInLoads.size(); i != e; ++i) {
469 LoadInst *ALoad = LiveInLoads[i];
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000470 Value *NewVal = SSA.GetValueInMiddleOfBlock(ALoad->getParent());
471 replaceLoadWithValue(ALoad, NewVal);
Chris Lattner867be592011-01-24 03:29:07 +0000472
473 // Avoid assertions in unreachable code.
474 if (NewVal == ALoad) NewVal = UndefValue::get(NewVal->getType());
Chris Lattnera2d845a2011-01-14 19:36:13 +0000475 ALoad->replaceAllUsesWith(NewVal);
476 ReplacedLoads[ALoad] = NewVal;
477 }
478
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000479 // Allow the client to do stuff before we start nuking things.
480 doExtraRewritesBeforeFinalDeletion();
481
Chris Lattnera2d845a2011-01-14 19:36:13 +0000482 // Now that everything is rewritten, delete the old instructions from the
483 // function. They should all be dead now.
484 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
485 Instruction *User = Insts[i];
486
487 // If this is a load that still has uses, then the load must have been added
488 // as a live value in the SSAUpdate data structure for a block (e.g. because
489 // the loaded value was stored later). In this case, we need to recursively
490 // propagate the updates until we get to the real value.
491 if (!User->use_empty()) {
492 Value *NewVal = ReplacedLoads[User];
493 assert(NewVal && "not a replaced load?");
494
495 // Propagate down to the ultimate replacee. The intermediately loads
496 // could theoretically already have been deleted, so we don't want to
497 // dereference the Value*'s.
498 DenseMap<Value*, Value*>::iterator RLI = ReplacedLoads.find(NewVal);
499 while (RLI != ReplacedLoads.end()) {
500 NewVal = RLI->second;
501 RLI = ReplacedLoads.find(NewVal);
502 }
503
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000504 replaceLoadWithValue(cast<LoadInst>(User), NewVal);
Chris Lattnera2d845a2011-01-14 19:36:13 +0000505 User->replaceAllUsesWith(NewVal);
506 }
507
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000508 instructionDeleted(User);
Chris Lattnera2d845a2011-01-14 19:36:13 +0000509 User->eraseFromParent();
510 }
511}