blob: b336194a35e3b16193e895e10b8b6bc76d5ce86d [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"
Cameron Zwarichc8279392011-05-24 03:10:43 +000017#include "llvm/IntrinsicInst.h"
Chris Lattner93f3bcf2009-10-10 09:04:27 +000018#include "llvm/ADT/DenseMap.h"
Cameron Zwarichc8279392011-05-24 03:10:43 +000019#include "llvm/Analysis/DIBuilder.h"
Duncan Sandscdbd9922010-11-16 17:41:24 +000020#include "llvm/Analysis/InstructionSimplify.h"
Bob Wilson84bd6b02010-04-17 03:08:24 +000021#include "llvm/Support/AlignOf.h"
22#include "llvm/Support/Allocator.h"
Chris Lattner93f3bcf2009-10-10 09:04:27 +000023#include "llvm/Support/CFG.h"
24#include "llvm/Support/Debug.h"
Chris Lattner93f3bcf2009-10-10 09:04:27 +000025#include "llvm/Support/raw_ostream.h"
Devang Patel40348e82011-04-29 22:28:59 +000026#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Cameron Zwarichc8279392011-05-24 03:10:43 +000027#include "llvm/Transforms/Utils/Local.h"
Bob Wilson4aad88d2010-05-04 23:18:19 +000028#include "llvm/Transforms/Utils/SSAUpdater.h"
29#include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
Devang Patel40348e82011-04-29 22:28:59 +000030
Chris Lattner93f3bcf2009-10-10 09:04:27 +000031using namespace llvm;
32
Bob Wilson84bd6b02010-04-17 03:08:24 +000033typedef DenseMap<BasicBlock*, Value*> AvailableValsTy;
Chris Lattner93f3bcf2009-10-10 09:04:27 +000034static AvailableValsTy &getAvailableVals(void *AV) {
35 return *static_cast<AvailableValsTy*>(AV);
36}
37
Chris Lattnerf5a1fb62009-10-10 23:15:24 +000038SSAUpdater::SSAUpdater(SmallVectorImpl<PHINode*> *NewPHI)
Duncan Sandsfc6e29d2010-09-02 08:14:03 +000039 : AV(0), ProtoType(0), ProtoName(), InsertedPHIs(NewPHI) {}
Chris Lattner93f3bcf2009-10-10 09:04:27 +000040
41SSAUpdater::~SSAUpdater() {
42 delete &getAvailableVals(AV);
Chris Lattner93f3bcf2009-10-10 09:04:27 +000043}
44
45/// Initialize - Reset this object to get ready for a new set of SSA
Duncan Sandsfc6e29d2010-09-02 08:14:03 +000046/// updates with type 'Ty'. PHI nodes get a name based on 'Name'.
47void SSAUpdater::Initialize(const Type *Ty, StringRef Name) {
Chris Lattner93f3bcf2009-10-10 09:04:27 +000048 if (AV == 0)
49 AV = new AvailableValsTy();
50 else
51 getAvailableVals(AV).clear();
Duncan Sandsfc6e29d2010-09-02 08:14:03 +000052 ProtoType = Ty;
53 ProtoName = Name;
Chris Lattner93f3bcf2009-10-10 09:04:27 +000054}
55
Chris Lattner0bef5622009-10-10 23:41:48 +000056/// HasValueForBlock - Return true if the SSAUpdater already has a value for
57/// the specified block.
58bool SSAUpdater::HasValueForBlock(BasicBlock *BB) const {
59 return getAvailableVals(AV).count(BB);
60}
61
Chris Lattner93f3bcf2009-10-10 09:04:27 +000062/// AddAvailableValue - Indicate that a rewritten value is available in the
63/// specified block with the specified value.
64void SSAUpdater::AddAvailableValue(BasicBlock *BB, Value *V) {
Duncan Sandsfc6e29d2010-09-02 08:14:03 +000065 assert(ProtoType != 0 && "Need to initialize SSAUpdater");
66 assert(ProtoType == V->getType() &&
Chris Lattner93f3bcf2009-10-10 09:04:27 +000067 "All rewritten values must have the same type");
68 getAvailableVals(AV)[BB] = V;
69}
70
Bob Wilsone98585e2010-01-27 22:01:02 +000071/// IsEquivalentPHI - Check if PHI has the same incoming value as specified
72/// in ValueMapping for each predecessor block.
Bob Wilson84bd6b02010-04-17 03:08:24 +000073static bool IsEquivalentPHI(PHINode *PHI,
Bob Wilsone98585e2010-01-27 22:01:02 +000074 DenseMap<BasicBlock*, Value*> &ValueMapping) {
75 unsigned PHINumValues = PHI->getNumIncomingValues();
76 if (PHINumValues != ValueMapping.size())
77 return false;
78
79 // Scan the phi to see if it matches.
80 for (unsigned i = 0, e = PHINumValues; i != e; ++i)
81 if (ValueMapping[PHI->getIncomingBlock(i)] !=
82 PHI->getIncomingValue(i)) {
83 return false;
84 }
85
86 return true;
87}
88
Chris Lattner1a8d4de2009-10-10 23:00:11 +000089/// GetValueAtEndOfBlock - Construct SSA form, materializing a value that is
90/// live at the end of the specified block.
Chris Lattner5fb10722009-10-10 22:41:58 +000091Value *SSAUpdater::GetValueAtEndOfBlock(BasicBlock *BB) {
Chris Lattner5fb10722009-10-10 22:41:58 +000092 Value *Res = GetValueAtEndOfBlockInternal(BB);
Chris Lattner93f3bcf2009-10-10 09:04:27 +000093 return Res;
94}
95
Chris Lattner1a8d4de2009-10-10 23:00:11 +000096/// GetValueInMiddleOfBlock - Construct SSA form, materializing a value that
97/// is live in the middle of the specified block.
98///
99/// GetValueInMiddleOfBlock is the same as GetValueAtEndOfBlock except in one
100/// important case: if there is a definition of the rewritten value after the
101/// 'use' in BB. Consider code like this:
102///
103/// X1 = ...
104/// SomeBB:
105/// use(X)
106/// X2 = ...
107/// br Cond, SomeBB, OutBB
108///
109/// In this case, there are two values (X1 and X2) added to the AvailableVals
110/// set by the client of the rewriter, and those values are both live out of
111/// their respective blocks. However, the use of X happens in the *middle* of
112/// a block. Because of this, we need to insert a new PHI node in SomeBB to
113/// merge the appropriate values, and this value isn't live out of the block.
114///
115Value *SSAUpdater::GetValueInMiddleOfBlock(BasicBlock *BB) {
116 // If there is no definition of the renamed variable in this block, just use
117 // GetValueAtEndOfBlock to do our work.
Bob Wilson84bd6b02010-04-17 03:08:24 +0000118 if (!HasValueForBlock(BB))
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000119 return GetValueAtEndOfBlock(BB);
Duncan Sandsed903422009-10-16 15:20:13 +0000120
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000121 // Otherwise, we have the hard case. Get the live-in values for each
122 // predecessor.
123 SmallVector<std::pair<BasicBlock*, Value*>, 8> PredValues;
124 Value *SingularValue = 0;
Duncan Sandsed903422009-10-16 15:20:13 +0000125
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000126 // We can get our predecessor info by walking the pred_iterator list, but it
127 // is relatively slow. If we already have PHI nodes in this block, walk one
128 // of them to get the predecessor list instead.
129 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
130 for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) {
131 BasicBlock *PredBB = SomePhi->getIncomingBlock(i);
132 Value *PredVal = GetValueAtEndOfBlock(PredBB);
133 PredValues.push_back(std::make_pair(PredBB, PredVal));
Duncan Sandsed903422009-10-16 15:20:13 +0000134
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000135 // Compute SingularValue.
136 if (i == 0)
137 SingularValue = PredVal;
138 else if (PredVal != SingularValue)
139 SingularValue = 0;
140 }
141 } else {
142 bool isFirstPred = true;
143 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
144 BasicBlock *PredBB = *PI;
145 Value *PredVal = GetValueAtEndOfBlock(PredBB);
146 PredValues.push_back(std::make_pair(PredBB, PredVal));
Duncan Sandsed903422009-10-16 15:20:13 +0000147
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000148 // Compute SingularValue.
149 if (isFirstPred) {
150 SingularValue = PredVal;
151 isFirstPred = false;
152 } else if (PredVal != SingularValue)
153 SingularValue = 0;
154 }
155 }
Duncan Sandsed903422009-10-16 15:20:13 +0000156
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000157 // If there are no predecessors, just return undef.
158 if (PredValues.empty())
Duncan Sandsfc6e29d2010-09-02 08:14:03 +0000159 return UndefValue::get(ProtoType);
Duncan Sandsed903422009-10-16 15:20:13 +0000160
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000161 // Otherwise, if all the merged values are the same, just use it.
162 if (SingularValue != 0)
163 return SingularValue;
Duncan Sandsed903422009-10-16 15:20:13 +0000164
Bob Wilson84bd6b02010-04-17 03:08:24 +0000165 // Otherwise, we do need a PHI: check to see if we already have one available
166 // in this block that produces the right value.
167 if (isa<PHINode>(BB->begin())) {
168 DenseMap<BasicBlock*, Value*> ValueMapping(PredValues.begin(),
169 PredValues.end());
170 PHINode *SomePHI;
171 for (BasicBlock::iterator It = BB->begin();
172 (SomePHI = dyn_cast<PHINode>(It)); ++It) {
173 if (IsEquivalentPHI(SomePHI, ValueMapping))
174 return SomePHI;
175 }
176 }
Bob Wilsone98585e2010-01-27 22:01:02 +0000177
Chris Lattner4c1e3da2009-12-21 07:16:11 +0000178 // Ok, we have no way out, insert a new one now.
Jay Foad3ecfc862011-03-30 11:28:46 +0000179 PHINode *InsertedPHI = PHINode::Create(ProtoType, PredValues.size(),
180 ProtoName, &BB->front());
Duncan Sandsed903422009-10-16 15:20:13 +0000181
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000182 // Fill in all the predecessors of the PHI.
183 for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
184 InsertedPHI->addIncoming(PredValues[i].second, PredValues[i].first);
Duncan Sandsed903422009-10-16 15:20:13 +0000185
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000186 // See if the PHI node can be merged to a single value. This can happen in
187 // loop cases when we get a PHI of itself and one other value.
Duncan Sandscdbd9922010-11-16 17:41:24 +0000188 if (Value *V = SimplifyInstruction(InsertedPHI)) {
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000189 InsertedPHI->eraseFromParent();
Duncan Sandscdbd9922010-11-16 17:41:24 +0000190 return V;
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000191 }
Chris Lattnerf5a1fb62009-10-10 23:15:24 +0000192
Devang Patel40348e82011-04-29 22:28:59 +0000193 // Set DebugLoc.
194 InsertedPHI->setDebugLoc(GetFirstDebugLocInBasicBlock(BB));
195
Chris Lattnerf5a1fb62009-10-10 23:15:24 +0000196 // If the client wants to know about all new instructions, tell it.
197 if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
Duncan Sandsed903422009-10-16 15:20:13 +0000198
David Greene1af40ca2010-01-05 01:26:49 +0000199 DEBUG(dbgs() << " Inserted PHI: " << *InsertedPHI << "\n");
Chris Lattner1a8d4de2009-10-10 23:00:11 +0000200 return InsertedPHI;
201}
202
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000203/// RewriteUse - Rewrite a use of the symbolic value. This handles PHI nodes,
204/// which use their value in the corresponding predecessor.
205void SSAUpdater::RewriteUse(Use &U) {
206 Instruction *User = cast<Instruction>(U.getUser());
Bob Wilson84bd6b02010-04-17 03:08:24 +0000207
Chris Lattner88a86242009-10-20 20:27:49 +0000208 Value *V;
209 if (PHINode *UserPN = dyn_cast<PHINode>(User))
210 V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
211 else
212 V = GetValueInMiddleOfBlock(User->getParent());
Duncan Sandsed903422009-10-16 15:20:13 +0000213
Torok Edwinf9933272009-10-20 15:42:00 +0000214 U.set(V);
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000215}
216
Chris Lattnerffd9bee2010-08-29 04:54:06 +0000217/// RewriteUseAfterInsertions - Rewrite a use, just like RewriteUse. However,
218/// this version of the method can rewrite uses in the same block as a
219/// definition, because it assumes that all uses of a value are below any
220/// inserted values.
221void SSAUpdater::RewriteUseAfterInsertions(Use &U) {
222 Instruction *User = cast<Instruction>(U.getUser());
223
224 Value *V;
225 if (PHINode *UserPN = dyn_cast<PHINode>(User))
226 V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
227 else
228 V = GetValueAtEndOfBlock(User->getParent());
229
230 U.set(V);
231}
232
Bob Wilson4aad88d2010-05-04 23:18:19 +0000233/// PHIiter - Iterator for PHI operands. This is used for the PHI_iterator
234/// in the SSAUpdaterImpl template.
235namespace {
236 class PHIiter {
237 private:
238 PHINode *PHI;
239 unsigned idx;
240
241 public:
242 explicit PHIiter(PHINode *P) // begin iterator
243 : PHI(P), idx(0) {}
244 PHIiter(PHINode *P, bool) // end iterator
245 : PHI(P), idx(PHI->getNumIncomingValues()) {}
246
247 PHIiter &operator++() { ++idx; return *this; }
248 bool operator==(const PHIiter& x) const { return idx == x.idx; }
249 bool operator!=(const PHIiter& x) const { return !operator==(x); }
250 Value *getIncomingValue() { return PHI->getIncomingValue(idx); }
251 BasicBlock *getIncomingBlock() { return PHI->getIncomingBlock(idx); }
252 };
253}
254
255/// SSAUpdaterTraits<SSAUpdater> - Traits for the SSAUpdaterImpl template,
256/// specialized for SSAUpdater.
257namespace llvm {
258template<>
259class SSAUpdaterTraits<SSAUpdater> {
260public:
261 typedef BasicBlock BlkT;
262 typedef Value *ValT;
263 typedef PHINode PhiT;
264
265 typedef succ_iterator BlkSucc_iterator;
266 static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return succ_begin(BB); }
267 static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return succ_end(BB); }
268
269 typedef PHIiter PHI_iterator;
270 static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
271 static inline PHI_iterator PHI_end(PhiT *PHI) {
272 return PHI_iterator(PHI, true);
273 }
274
275 /// FindPredecessorBlocks - Put the predecessors of Info->BB into the Preds
276 /// vector, set Info->NumPreds, and allocate space in Info->Preds.
277 static void FindPredecessorBlocks(BasicBlock *BB,
278 SmallVectorImpl<BasicBlock*> *Preds) {
279 // We can get our predecessor info by walking the pred_iterator list,
280 // but it is relatively slow. If we already have PHI nodes in this
281 // block, walk one of them to get the predecessor list instead.
282 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
283 for (unsigned PI = 0, E = SomePhi->getNumIncomingValues(); PI != E; ++PI)
284 Preds->push_back(SomePhi->getIncomingBlock(PI));
285 } else {
286 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
287 Preds->push_back(*PI);
288 }
289 }
290
291 /// GetUndefVal - Get an undefined value of the same type as the value
292 /// being handled.
293 static Value *GetUndefVal(BasicBlock *BB, SSAUpdater *Updater) {
Duncan Sandsfc6e29d2010-09-02 08:14:03 +0000294 return UndefValue::get(Updater->ProtoType);
Bob Wilson4aad88d2010-05-04 23:18:19 +0000295 }
296
297 /// CreateEmptyPHI - Create a new PHI instruction in the specified block.
298 /// Reserve space for the operands but do not fill them in yet.
299 static Value *CreateEmptyPHI(BasicBlock *BB, unsigned NumPreds,
300 SSAUpdater *Updater) {
Jay Foad3ecfc862011-03-30 11:28:46 +0000301 PHINode *PHI = PHINode::Create(Updater->ProtoType, NumPreds,
302 Updater->ProtoName, &BB->front());
Bob Wilson4aad88d2010-05-04 23:18:19 +0000303 return PHI;
304 }
305
306 /// AddPHIOperand - Add the specified value as an operand of the PHI for
307 /// the specified predecessor block.
308 static void AddPHIOperand(PHINode *PHI, Value *Val, BasicBlock *Pred) {
309 PHI->addIncoming(Val, Pred);
310 }
311
312 /// InstrIsPHI - Check if an instruction is a PHI.
313 ///
314 static PHINode *InstrIsPHI(Instruction *I) {
315 return dyn_cast<PHINode>(I);
316 }
317
318 /// ValueIsPHI - Check if a value is a PHI.
319 ///
320 static PHINode *ValueIsPHI(Value *Val, SSAUpdater *Updater) {
321 return dyn_cast<PHINode>(Val);
322 }
323
324 /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
325 /// operands, i.e., it was just added.
326 static PHINode *ValueIsNewPHI(Value *Val, SSAUpdater *Updater) {
327 PHINode *PHI = ValueIsPHI(Val, Updater);
328 if (PHI && PHI->getNumIncomingValues() == 0)
329 return PHI;
330 return 0;
331 }
332
333 /// GetPHIValue - For the specified PHI instruction, return the value
334 /// that it defines.
335 static Value *GetPHIValue(PHINode *PHI) {
336 return PHI;
337 }
338};
339
340} // End llvm namespace
341
Chris Lattner5fb10722009-10-10 22:41:58 +0000342/// GetValueAtEndOfBlockInternal - Check to see if AvailableVals has an entry
343/// for the specified BB and if so, return it. If not, construct SSA form by
Bob Wilson84bd6b02010-04-17 03:08:24 +0000344/// first calculating the required placement of PHIs and then inserting new
345/// PHIs where needed.
Chris Lattner5fb10722009-10-10 22:41:58 +0000346Value *SSAUpdater::GetValueAtEndOfBlockInternal(BasicBlock *BB) {
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000347 AvailableValsTy &AvailableVals = getAvailableVals(AV);
Bob Wilson84bd6b02010-04-17 03:08:24 +0000348 if (Value *V = AvailableVals[BB])
349 return V;
Duncan Sandsed903422009-10-16 15:20:13 +0000350
Bob Wilson4aad88d2010-05-04 23:18:19 +0000351 SSAUpdaterImpl<SSAUpdater> Impl(this, &AvailableVals, InsertedPHIs);
352 return Impl.GetValue(BB);
Chris Lattner93f3bcf2009-10-10 09:04:27 +0000353}
Chris Lattnera2d845a2011-01-14 19:36:13 +0000354
355//===----------------------------------------------------------------------===//
356// LoadAndStorePromoter Implementation
357//===----------------------------------------------------------------------===//
358
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000359LoadAndStorePromoter::
360LoadAndStorePromoter(const SmallVectorImpl<Instruction*> &Insts,
Cameron Zwarich13a16082011-05-24 06:00:08 +0000361 SSAUpdater &S, DbgDeclareInst *DD, DIBuilder *DB,
Cameron Zwarichc8279392011-05-24 03:10:43 +0000362 StringRef BaseName) : SSA(S), DDI(DD), DIB(DB) {
Chris Lattnera2d845a2011-01-14 19:36:13 +0000363 if (Insts.empty()) return;
364
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000365 Value *SomeVal;
Chris Lattnera2d845a2011-01-14 19:36:13 +0000366 if (LoadInst *LI = dyn_cast<LoadInst>(Insts[0]))
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000367 SomeVal = LI;
Chris Lattnera2d845a2011-01-14 19:36:13 +0000368 else
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000369 SomeVal = cast<StoreInst>(Insts[0])->getOperand(0);
370
371 if (BaseName.empty())
372 BaseName = SomeVal->getName();
373 SSA.Initialize(SomeVal->getType(), BaseName);
374}
375
376
377void LoadAndStorePromoter::
378run(const SmallVectorImpl<Instruction*> &Insts) const {
Chris Lattnera2d845a2011-01-14 19:36:13 +0000379
380 // First step: bucket up uses of the alloca by the block they occur in.
381 // This is important because we have to handle multiple defs/uses in a block
382 // ourselves: SSAUpdater is purely for cross-block references.
383 // FIXME: Want a TinyVector<Instruction*> since there is often 0/1 element.
384 DenseMap<BasicBlock*, std::vector<Instruction*> > UsesByBlock;
385
386 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
387 Instruction *User = Insts[i];
388 UsesByBlock[User->getParent()].push_back(User);
389 }
390
391 // Okay, now we can iterate over all the blocks in the function with uses,
392 // processing them. Keep track of which loads are loading a live-in value.
393 // Walk the uses in the use-list order to be determinstic.
394 SmallVector<LoadInst*, 32> LiveInLoads;
395 DenseMap<Value*, Value*> ReplacedLoads;
396
397 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
398 Instruction *User = Insts[i];
399 BasicBlock *BB = User->getParent();
400 std::vector<Instruction*> &BlockUses = UsesByBlock[BB];
401
402 // If this block has already been processed, ignore this repeat use.
403 if (BlockUses.empty()) continue;
404
405 // Okay, this is the first use in the block. If this block just has a
406 // single user in it, we can rewrite it trivially.
407 if (BlockUses.size() == 1) {
408 // If it is a store, it is a trivial def of the value in the block.
Cameron Zwarichc8279392011-05-24 03:10:43 +0000409 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Cameron Zwarich13a16082011-05-24 06:00:08 +0000410 if (DDI)
Cameron Zwarichc8279392011-05-24 03:10:43 +0000411 ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000412 SSA.AddAvailableValue(BB, SI->getOperand(0));
Cameron Zwarichc8279392011-05-24 03:10:43 +0000413 } else
Chris Lattnera2d845a2011-01-14 19:36:13 +0000414 // Otherwise it is a load, queue it to rewrite as a live-in load.
415 LiveInLoads.push_back(cast<LoadInst>(User));
416 BlockUses.clear();
417 continue;
418 }
419
420 // Otherwise, check to see if this block is all loads.
421 bool HasStore = false;
422 for (unsigned i = 0, e = BlockUses.size(); i != e; ++i) {
423 if (isa<StoreInst>(BlockUses[i])) {
424 HasStore = true;
425 break;
426 }
427 }
428
429 // If so, we can queue them all as live in loads. We don't have an
430 // efficient way to tell which on is first in the block and don't want to
431 // scan large blocks, so just add all loads as live ins.
432 if (!HasStore) {
433 for (unsigned i = 0, e = BlockUses.size(); i != e; ++i)
434 LiveInLoads.push_back(cast<LoadInst>(BlockUses[i]));
435 BlockUses.clear();
436 continue;
437 }
438
439 // Otherwise, we have mixed loads and stores (or just a bunch of stores).
440 // Since SSAUpdater is purely for cross-block values, we need to determine
441 // the order of these instructions in the block. If the first use in the
442 // block is a load, then it uses the live in value. The last store defines
443 // the live out value. We handle this by doing a linear scan of the block.
444 Value *StoredValue = 0;
445 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
446 if (LoadInst *L = dyn_cast<LoadInst>(II)) {
447 // If this is a load from an unrelated pointer, ignore it.
448 if (!isInstInList(L, Insts)) continue;
449
450 // If we haven't seen a store yet, this is a live in use, otherwise
451 // use the stored value.
452 if (StoredValue) {
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000453 replaceLoadWithValue(L, StoredValue);
Chris Lattnera2d845a2011-01-14 19:36:13 +0000454 L->replaceAllUsesWith(StoredValue);
455 ReplacedLoads[L] = StoredValue;
456 } else {
457 LiveInLoads.push_back(L);
458 }
459 continue;
460 }
461
Cameron Zwarichc8279392011-05-24 03:10:43 +0000462 if (StoreInst *SI = dyn_cast<StoreInst>(II)) {
Chris Lattnera2d845a2011-01-14 19:36:13 +0000463 // If this is a store to an unrelated pointer, ignore it.
Cameron Zwarichc8279392011-05-24 03:10:43 +0000464 if (!isInstInList(SI, Insts)) continue;
465
Cameron Zwarich13a16082011-05-24 06:00:08 +0000466 if (DDI)
Cameron Zwarichc8279392011-05-24 03:10:43 +0000467 ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
Cameron Zwarichc8279392011-05-24 03:10:43 +0000468
Chris Lattnera2d845a2011-01-14 19:36:13 +0000469 // Remember that this is the active value in the block.
Cameron Zwarichc8279392011-05-24 03:10:43 +0000470 StoredValue = SI->getOperand(0);
Chris Lattnera2d845a2011-01-14 19:36:13 +0000471 }
472 }
473
474 // The last stored value that happened is the live-out for the block.
475 assert(StoredValue && "Already checked that there is a store in block");
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000476 SSA.AddAvailableValue(BB, StoredValue);
Chris Lattnera2d845a2011-01-14 19:36:13 +0000477 BlockUses.clear();
478 }
479
480 // Okay, now we rewrite all loads that use live-in values in the loop,
481 // inserting PHI nodes as necessary.
482 for (unsigned i = 0, e = LiveInLoads.size(); i != e; ++i) {
483 LoadInst *ALoad = LiveInLoads[i];
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000484 Value *NewVal = SSA.GetValueInMiddleOfBlock(ALoad->getParent());
485 replaceLoadWithValue(ALoad, NewVal);
Chris Lattner867be592011-01-24 03:29:07 +0000486
487 // Avoid assertions in unreachable code.
488 if (NewVal == ALoad) NewVal = UndefValue::get(NewVal->getType());
Chris Lattnera2d845a2011-01-14 19:36:13 +0000489 ALoad->replaceAllUsesWith(NewVal);
490 ReplacedLoads[ALoad] = NewVal;
491 }
492
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000493 // Allow the client to do stuff before we start nuking things.
494 doExtraRewritesBeforeFinalDeletion();
495
Chris Lattnera2d845a2011-01-14 19:36:13 +0000496 // Now that everything is rewritten, delete the old instructions from the
497 // function. They should all be dead now.
498 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
499 Instruction *User = Insts[i];
500
501 // If this is a load that still has uses, then the load must have been added
502 // as a live value in the SSAUpdate data structure for a block (e.g. because
503 // the loaded value was stored later). In this case, we need to recursively
504 // propagate the updates until we get to the real value.
505 if (!User->use_empty()) {
506 Value *NewVal = ReplacedLoads[User];
507 assert(NewVal && "not a replaced load?");
508
509 // Propagate down to the ultimate replacee. The intermediately loads
510 // could theoretically already have been deleted, so we don't want to
511 // dereference the Value*'s.
512 DenseMap<Value*, Value*>::iterator RLI = ReplacedLoads.find(NewVal);
513 while (RLI != ReplacedLoads.end()) {
514 NewVal = RLI->second;
515 RLI = ReplacedLoads.find(NewVal);
516 }
517
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000518 replaceLoadWithValue(cast<LoadInst>(User), NewVal);
Chris Lattnera2d845a2011-01-14 19:36:13 +0000519 User->replaceAllUsesWith(NewVal);
520 }
521
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000522 instructionDeleted(User);
Chris Lattnera2d845a2011-01-14 19:36:13 +0000523 User->eraseFromParent();
524 }
Cameron Zwarichc8279392011-05-24 03:10:43 +0000525
526 if (DDI)
527 DDI->eraseFromParent();
Chris Lattnera2d845a2011-01-14 19:36:13 +0000528}