blob: c057b064934c40e4d0120838318003fadc95d3a2 [file] [log] [blame]
Chris Lattner60d4e692009-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
Chandler Carruthed0881b2012-12-03 16:50:05 +000014#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner60d4e692009-10-10 09:04:27 +000015#include "llvm/ADT/DenseMap.h"
Chris Lattner7b70bef2011-07-18 01:43:58 +000016#include "llvm/ADT/TinyPtrVector.h"
Duncan Sands63704952010-11-16 17:41:24 +000017#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000018#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/Constants.h"
20#include "llvm/IR/Instructions.h"
21#include "llvm/IR/IntrinsicInst.h"
Chris Lattner60d4e692009-10-10 09:04:27 +000022#include "llvm/Support/Debug.h"
Chris Lattner60d4e692009-10-10 09:04:27 +000023#include "llvm/Support/raw_ostream.h"
Devang Patela8e74112011-04-29 22:28:59 +000024#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Cameron Zwarich843bc7d2011-05-24 03:10:43 +000025#include "llvm/Transforms/Utils/Local.h"
Bob Wilsond1b38e32010-05-04 23:18:19 +000026#include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
Devang Patela8e74112011-04-29 22:28:59 +000027
Chris Lattner60d4e692009-10-10 09:04:27 +000028using namespace llvm;
29
Chandler Carruthe96dd892014-04-21 22:55:11 +000030#define DEBUG_TYPE "ssaupdater"
31
Bob Wilsonca514252010-04-17 03:08:24 +000032typedef DenseMap<BasicBlock*, Value*> AvailableValsTy;
Chris Lattner60d4e692009-10-10 09:04:27 +000033static AvailableValsTy &getAvailableVals(void *AV) {
34 return *static_cast<AvailableValsTy*>(AV);
35}
36
Chris Lattner249265d2009-10-10 23:15:24 +000037SSAUpdater::SSAUpdater(SmallVectorImpl<PHINode*> *NewPHI)
Craig Topperf40110f2014-04-25 05:29:35 +000038 : AV(nullptr), ProtoType(nullptr), ProtoName(), InsertedPHIs(NewPHI) {}
Chris Lattner60d4e692009-10-10 09:04:27 +000039
40SSAUpdater::~SSAUpdater() {
Richard Smith257c5f22012-08-17 21:42:44 +000041 delete static_cast<AvailableValsTy*>(AV);
Chris Lattner60d4e692009-10-10 09:04:27 +000042}
43
Chris Lattner229907c2011-07-18 04:54:35 +000044void SSAUpdater::Initialize(Type *Ty, StringRef Name) {
Craig Topperf40110f2014-04-25 05:29:35 +000045 if (!AV)
Chris Lattner60d4e692009-10-10 09:04:27 +000046 AV = new AvailableValsTy();
47 else
48 getAvailableVals(AV).clear();
Duncan Sands67781492010-09-02 08:14:03 +000049 ProtoType = Ty;
50 ProtoName = Name;
Chris Lattner60d4e692009-10-10 09:04:27 +000051}
52
Chris Lattner9c382ce2009-10-10 23:41:48 +000053bool SSAUpdater::HasValueForBlock(BasicBlock *BB) const {
54 return getAvailableVals(AV).count(BB);
55}
56
Chris Lattner60d4e692009-10-10 09:04:27 +000057void SSAUpdater::AddAvailableValue(BasicBlock *BB, Value *V) {
Craig Toppere73658d2014-04-28 04:05:08 +000058 assert(ProtoType && "Need to initialize SSAUpdater");
Duncan Sands67781492010-09-02 08:14:03 +000059 assert(ProtoType == V->getType() &&
Chris Lattner60d4e692009-10-10 09:04:27 +000060 "All rewritten values must have the same type");
61 getAvailableVals(AV)[BB] = V;
62}
63
Bob Wilsonca514252010-04-17 03:08:24 +000064static bool IsEquivalentPHI(PHINode *PHI,
Chris Lattner94fc4be2013-10-14 16:05:55 +000065 SmallDenseMap<BasicBlock*, Value*, 8> &ValueMapping) {
Bob Wilson7577e942010-01-27 22:01:02 +000066 unsigned PHINumValues = PHI->getNumIncomingValues();
67 if (PHINumValues != ValueMapping.size())
68 return false;
69
70 // Scan the phi to see if it matches.
71 for (unsigned i = 0, e = PHINumValues; i != e; ++i)
72 if (ValueMapping[PHI->getIncomingBlock(i)] !=
73 PHI->getIncomingValue(i)) {
74 return false;
75 }
76
77 return true;
78}
79
Chris Lattnere474a8d2009-10-10 22:41:58 +000080Value *SSAUpdater::GetValueAtEndOfBlock(BasicBlock *BB) {
Chris Lattnere474a8d2009-10-10 22:41:58 +000081 Value *Res = GetValueAtEndOfBlockInternal(BB);
Chris Lattner60d4e692009-10-10 09:04:27 +000082 return Res;
83}
84
Chris Lattner67cdd8b2009-10-10 23:00:11 +000085Value *SSAUpdater::GetValueInMiddleOfBlock(BasicBlock *BB) {
86 // If there is no definition of the renamed variable in this block, just use
87 // GetValueAtEndOfBlock to do our work.
Bob Wilsonca514252010-04-17 03:08:24 +000088 if (!HasValueForBlock(BB))
Chris Lattner67cdd8b2009-10-10 23:00:11 +000089 return GetValueAtEndOfBlock(BB);
Duncan Sands0058c7b2009-10-16 15:20:13 +000090
Chris Lattner67cdd8b2009-10-10 23:00:11 +000091 // Otherwise, we have the hard case. Get the live-in values for each
92 // predecessor.
93 SmallVector<std::pair<BasicBlock*, Value*>, 8> PredValues;
Craig Topperf40110f2014-04-25 05:29:35 +000094 Value *SingularValue = nullptr;
Duncan Sands0058c7b2009-10-16 15:20:13 +000095
Chris Lattner67cdd8b2009-10-10 23:00:11 +000096 // We can get our predecessor info by walking the pred_iterator list, but it
97 // is relatively slow. If we already have PHI nodes in this block, walk one
98 // of them to get the predecessor list instead.
99 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
100 for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) {
101 BasicBlock *PredBB = SomePhi->getIncomingBlock(i);
102 Value *PredVal = GetValueAtEndOfBlock(PredBB);
103 PredValues.push_back(std::make_pair(PredBB, PredVal));
Duncan Sands0058c7b2009-10-16 15:20:13 +0000104
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000105 // Compute SingularValue.
106 if (i == 0)
107 SingularValue = PredVal;
108 else if (PredVal != SingularValue)
Craig Topperf40110f2014-04-25 05:29:35 +0000109 SingularValue = nullptr;
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000110 }
111 } else {
112 bool isFirstPred = true;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000113 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
114 BasicBlock *PredBB = *PI;
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000115 Value *PredVal = GetValueAtEndOfBlock(PredBB);
116 PredValues.push_back(std::make_pair(PredBB, PredVal));
Duncan Sands0058c7b2009-10-16 15:20:13 +0000117
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000118 // Compute SingularValue.
119 if (isFirstPred) {
120 SingularValue = PredVal;
121 isFirstPred = false;
122 } else if (PredVal != SingularValue)
Craig Topperf40110f2014-04-25 05:29:35 +0000123 SingularValue = nullptr;
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000124 }
125 }
Duncan Sands0058c7b2009-10-16 15:20:13 +0000126
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000127 // If there are no predecessors, just return undef.
128 if (PredValues.empty())
Duncan Sands67781492010-09-02 08:14:03 +0000129 return UndefValue::get(ProtoType);
Duncan Sands0058c7b2009-10-16 15:20:13 +0000130
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000131 // Otherwise, if all the merged values are the same, just use it.
Craig Topperf40110f2014-04-25 05:29:35 +0000132 if (SingularValue)
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000133 return SingularValue;
Duncan Sands0058c7b2009-10-16 15:20:13 +0000134
Bob Wilsonca514252010-04-17 03:08:24 +0000135 // Otherwise, we do need a PHI: check to see if we already have one available
136 // in this block that produces the right value.
137 if (isa<PHINode>(BB->begin())) {
Chris Lattner94fc4be2013-10-14 16:05:55 +0000138 SmallDenseMap<BasicBlock*, Value*, 8> ValueMapping(PredValues.begin(),
139 PredValues.end());
Bob Wilsonca514252010-04-17 03:08:24 +0000140 PHINode *SomePHI;
141 for (BasicBlock::iterator It = BB->begin();
142 (SomePHI = dyn_cast<PHINode>(It)); ++It) {
143 if (IsEquivalentPHI(SomePHI, ValueMapping))
144 return SomePHI;
145 }
146 }
Bob Wilson7577e942010-01-27 22:01:02 +0000147
Chris Lattner8fb07c52009-12-21 07:16:11 +0000148 // Ok, we have no way out, insert a new one now.
Jay Foad52131342011-03-30 11:28:46 +0000149 PHINode *InsertedPHI = PHINode::Create(ProtoType, PredValues.size(),
150 ProtoName, &BB->front());
Duncan Sands0058c7b2009-10-16 15:20:13 +0000151
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000152 // Fill in all the predecessors of the PHI.
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000153 for (const auto &PredValue : PredValues)
154 InsertedPHI->addIncoming(PredValue.second, PredValue.first);
Duncan Sands0058c7b2009-10-16 15:20:13 +0000155
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000156 // See if the PHI node can be merged to a single value. This can happen in
157 // loop cases when we get a PHI of itself and one other value.
Duncan Sands63704952010-11-16 17:41:24 +0000158 if (Value *V = SimplifyInstruction(InsertedPHI)) {
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000159 InsertedPHI->eraseFromParent();
Duncan Sands63704952010-11-16 17:41:24 +0000160 return V;
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000161 }
Chris Lattner249265d2009-10-10 23:15:24 +0000162
Eli Benderskyf0ad3602012-06-25 10:13:14 +0000163 // Set the DebugLoc of the inserted PHI, if available.
164 DebugLoc DL;
165 if (const Instruction *I = BB->getFirstNonPHI())
166 DL = I->getDebugLoc();
167 InsertedPHI->setDebugLoc(DL);
Devang Patela8e74112011-04-29 22:28:59 +0000168
Chris Lattner249265d2009-10-10 23:15:24 +0000169 // If the client wants to know about all new instructions, tell it.
170 if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
Duncan Sands0058c7b2009-10-16 15:20:13 +0000171
David Greene3774a382010-01-05 01:26:49 +0000172 DEBUG(dbgs() << " Inserted PHI: " << *InsertedPHI << "\n");
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000173 return InsertedPHI;
174}
175
Chris Lattner60d4e692009-10-10 09:04:27 +0000176void SSAUpdater::RewriteUse(Use &U) {
177 Instruction *User = cast<Instruction>(U.getUser());
Bob Wilsonca514252010-04-17 03:08:24 +0000178
Chris Lattner7f903682009-10-20 20:27:49 +0000179 Value *V;
180 if (PHINode *UserPN = dyn_cast<PHINode>(User))
181 V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
182 else
183 V = GetValueInMiddleOfBlock(User->getParent());
Duncan Sands0058c7b2009-10-16 15:20:13 +0000184
Nadav Rotem8d804522012-08-13 23:06:54 +0000185 // Notify that users of the existing value that it is being replaced.
186 Value *OldVal = U.get();
187 if (OldVal != V && OldVal->hasValueHandle())
188 ValueHandleBase::ValueIsRAUWd(OldVal, V);
189
Torok Edwincf10ec92009-10-20 15:42:00 +0000190 U.set(V);
Chris Lattner60d4e692009-10-10 09:04:27 +0000191}
192
Chris Lattnerc3fb03e2010-08-29 04:54:06 +0000193void SSAUpdater::RewriteUseAfterInsertions(Use &U) {
194 Instruction *User = cast<Instruction>(U.getUser());
195
196 Value *V;
197 if (PHINode *UserPN = dyn_cast<PHINode>(User))
198 V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
199 else
200 V = GetValueAtEndOfBlock(User->getParent());
201
202 U.set(V);
203}
204
Bob Wilsond1b38e32010-05-04 23:18:19 +0000205namespace llvm {
206template<>
207class SSAUpdaterTraits<SSAUpdater> {
208public:
209 typedef BasicBlock BlkT;
210 typedef Value *ValT;
211 typedef PHINode PhiT;
212
213 typedef succ_iterator BlkSucc_iterator;
214 static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return succ_begin(BB); }
215 static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return succ_end(BB); }
216
Chandler Carruthc60fbe62012-06-20 08:39:30 +0000217 class PHI_iterator {
218 private:
219 PHINode *PHI;
220 unsigned idx;
221
222 public:
223 explicit PHI_iterator(PHINode *P) // begin iterator
224 : PHI(P), idx(0) {}
225 PHI_iterator(PHINode *P, bool) // end iterator
226 : PHI(P), idx(PHI->getNumIncomingValues()) {}
227
228 PHI_iterator &operator++() { ++idx; return *this; }
229 bool operator==(const PHI_iterator& x) const { return idx == x.idx; }
230 bool operator!=(const PHI_iterator& x) const { return !operator==(x); }
231 Value *getIncomingValue() { return PHI->getIncomingValue(idx); }
232 BasicBlock *getIncomingBlock() { return PHI->getIncomingBlock(idx); }
233 };
234
235 static PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
236 static PHI_iterator PHI_end(PhiT *PHI) {
Bob Wilsond1b38e32010-05-04 23:18:19 +0000237 return PHI_iterator(PHI, true);
238 }
239
240 /// FindPredecessorBlocks - Put the predecessors of Info->BB into the Preds
241 /// vector, set Info->NumPreds, and allocate space in Info->Preds.
242 static void FindPredecessorBlocks(BasicBlock *BB,
243 SmallVectorImpl<BasicBlock*> *Preds) {
244 // We can get our predecessor info by walking the pred_iterator list,
245 // but it is relatively slow. If we already have PHI nodes in this
246 // block, walk one of them to get the predecessor list instead.
247 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000248 Preds->append(SomePhi->block_begin(), SomePhi->block_end());
Bob Wilsond1b38e32010-05-04 23:18:19 +0000249 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000250 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
251 Preds->push_back(*PI);
Bob Wilsond1b38e32010-05-04 23:18:19 +0000252 }
253 }
254
255 /// GetUndefVal - Get an undefined value of the same type as the value
256 /// being handled.
257 static Value *GetUndefVal(BasicBlock *BB, SSAUpdater *Updater) {
Duncan Sands67781492010-09-02 08:14:03 +0000258 return UndefValue::get(Updater->ProtoType);
Bob Wilsond1b38e32010-05-04 23:18:19 +0000259 }
260
261 /// CreateEmptyPHI - Create a new PHI instruction in the specified block.
262 /// Reserve space for the operands but do not fill them in yet.
263 static Value *CreateEmptyPHI(BasicBlock *BB, unsigned NumPreds,
264 SSAUpdater *Updater) {
Jay Foad52131342011-03-30 11:28:46 +0000265 PHINode *PHI = PHINode::Create(Updater->ProtoType, NumPreds,
266 Updater->ProtoName, &BB->front());
Bob Wilsond1b38e32010-05-04 23:18:19 +0000267 return PHI;
268 }
269
270 /// AddPHIOperand - Add the specified value as an operand of the PHI for
271 /// the specified predecessor block.
272 static void AddPHIOperand(PHINode *PHI, Value *Val, BasicBlock *Pred) {
273 PHI->addIncoming(Val, Pred);
274 }
275
276 /// InstrIsPHI - Check if an instruction is a PHI.
277 ///
278 static PHINode *InstrIsPHI(Instruction *I) {
279 return dyn_cast<PHINode>(I);
280 }
281
282 /// ValueIsPHI - Check if a value is a PHI.
283 ///
284 static PHINode *ValueIsPHI(Value *Val, SSAUpdater *Updater) {
285 return dyn_cast<PHINode>(Val);
286 }
287
288 /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
289 /// operands, i.e., it was just added.
290 static PHINode *ValueIsNewPHI(Value *Val, SSAUpdater *Updater) {
291 PHINode *PHI = ValueIsPHI(Val, Updater);
292 if (PHI && PHI->getNumIncomingValues() == 0)
293 return PHI;
Craig Topperf40110f2014-04-25 05:29:35 +0000294 return nullptr;
Bob Wilsond1b38e32010-05-04 23:18:19 +0000295 }
296
297 /// GetPHIValue - For the specified PHI instruction, return the value
298 /// that it defines.
299 static Value *GetPHIValue(PHINode *PHI) {
300 return PHI;
301 }
302};
303
304} // End llvm namespace
305
Chandler Carruth6b55dbe2013-07-28 22:00:33 +0000306/// Check to see if AvailableVals has an entry for the specified BB and if so,
307/// return it. If not, construct SSA form by first calculating the required
308/// placement of PHIs and then inserting new PHIs where needed.
Chris Lattnere474a8d2009-10-10 22:41:58 +0000309Value *SSAUpdater::GetValueAtEndOfBlockInternal(BasicBlock *BB) {
Chris Lattner60d4e692009-10-10 09:04:27 +0000310 AvailableValsTy &AvailableVals = getAvailableVals(AV);
Bob Wilsonca514252010-04-17 03:08:24 +0000311 if (Value *V = AvailableVals[BB])
312 return V;
Duncan Sands0058c7b2009-10-16 15:20:13 +0000313
Bob Wilsond1b38e32010-05-04 23:18:19 +0000314 SSAUpdaterImpl<SSAUpdater> Impl(this, &AvailableVals, InsertedPHIs);
315 return Impl.GetValue(BB);
Chris Lattner60d4e692009-10-10 09:04:27 +0000316}
Chris Lattner95294b82011-01-14 19:36:13 +0000317
318//===----------------------------------------------------------------------===//
319// LoadAndStorePromoter Implementation
320//===----------------------------------------------------------------------===//
321
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000322LoadAndStorePromoter::
323LoadAndStorePromoter(const SmallVectorImpl<Instruction*> &Insts,
Devang Patela3cbf522011-07-06 21:09:55 +0000324 SSAUpdater &S, StringRef BaseName) : SSA(S) {
Chris Lattner95294b82011-01-14 19:36:13 +0000325 if (Insts.empty()) return;
326
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000327 Value *SomeVal;
Chris Lattner95294b82011-01-14 19:36:13 +0000328 if (LoadInst *LI = dyn_cast<LoadInst>(Insts[0]))
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000329 SomeVal = LI;
Chris Lattner95294b82011-01-14 19:36:13 +0000330 else
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000331 SomeVal = cast<StoreInst>(Insts[0])->getOperand(0);
332
333 if (BaseName.empty())
334 BaseName = SomeVal->getName();
335 SSA.Initialize(SomeVal->getType(), BaseName);
336}
337
338
339void LoadAndStorePromoter::
340run(const SmallVectorImpl<Instruction*> &Insts) const {
Chris Lattner95294b82011-01-14 19:36:13 +0000341
342 // First step: bucket up uses of the alloca by the block they occur in.
343 // This is important because we have to handle multiple defs/uses in a block
344 // ourselves: SSAUpdater is purely for cross-block references.
Chris Lattner7b70bef2011-07-18 01:43:58 +0000345 DenseMap<BasicBlock*, TinyPtrVector<Instruction*> > UsesByBlock;
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000346
347 for (Instruction *User : Insts)
Chris Lattner95294b82011-01-14 19:36:13 +0000348 UsesByBlock[User->getParent()].push_back(User);
Chris Lattner95294b82011-01-14 19:36:13 +0000349
350 // Okay, now we can iterate over all the blocks in the function with uses,
351 // processing them. Keep track of which loads are loading a live-in value.
352 // Walk the uses in the use-list order to be determinstic.
353 SmallVector<LoadInst*, 32> LiveInLoads;
354 DenseMap<Value*, Value*> ReplacedLoads;
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000355
356 for (Instruction *User : Insts) {
Chris Lattner95294b82011-01-14 19:36:13 +0000357 BasicBlock *BB = User->getParent();
Chris Lattner7b70bef2011-07-18 01:43:58 +0000358 TinyPtrVector<Instruction*> &BlockUses = UsesByBlock[BB];
Chris Lattner95294b82011-01-14 19:36:13 +0000359
360 // If this block has already been processed, ignore this repeat use.
361 if (BlockUses.empty()) continue;
362
363 // Okay, this is the first use in the block. If this block just has a
364 // single user in it, we can rewrite it trivially.
365 if (BlockUses.size() == 1) {
366 // If it is a store, it is a trivial def of the value in the block.
Cameron Zwarich843bc7d2011-05-24 03:10:43 +0000367 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Devang Patela3cbf522011-07-06 21:09:55 +0000368 updateDebugInfo(SI);
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000369 SSA.AddAvailableValue(BB, SI->getOperand(0));
Cameron Zwarich843bc7d2011-05-24 03:10:43 +0000370 } else
Chris Lattner95294b82011-01-14 19:36:13 +0000371 // Otherwise it is a load, queue it to rewrite as a live-in load.
372 LiveInLoads.push_back(cast<LoadInst>(User));
373 BlockUses.clear();
374 continue;
375 }
376
377 // Otherwise, check to see if this block is all loads.
378 bool HasStore = false;
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000379 for (Instruction *I : BlockUses) {
380 if (isa<StoreInst>(I)) {
Chris Lattner95294b82011-01-14 19:36:13 +0000381 HasStore = true;
382 break;
383 }
384 }
385
386 // If so, we can queue them all as live in loads. We don't have an
387 // efficient way to tell which on is first in the block and don't want to
388 // scan large blocks, so just add all loads as live ins.
389 if (!HasStore) {
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000390 for (Instruction *I : BlockUses)
391 LiveInLoads.push_back(cast<LoadInst>(I));
Chris Lattner95294b82011-01-14 19:36:13 +0000392 BlockUses.clear();
393 continue;
394 }
395
396 // Otherwise, we have mixed loads and stores (or just a bunch of stores).
397 // Since SSAUpdater is purely for cross-block values, we need to determine
398 // the order of these instructions in the block. If the first use in the
399 // block is a load, then it uses the live in value. The last store defines
400 // the live out value. We handle this by doing a linear scan of the block.
Craig Topperf40110f2014-04-25 05:29:35 +0000401 Value *StoredValue = nullptr;
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000402 for (Instruction &I : *BB) {
403 if (LoadInst *L = dyn_cast<LoadInst>(&I)) {
Chris Lattner95294b82011-01-14 19:36:13 +0000404 // If this is a load from an unrelated pointer, ignore it.
405 if (!isInstInList(L, Insts)) continue;
406
407 // If we haven't seen a store yet, this is a live in use, otherwise
408 // use the stored value.
409 if (StoredValue) {
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000410 replaceLoadWithValue(L, StoredValue);
Chris Lattner95294b82011-01-14 19:36:13 +0000411 L->replaceAllUsesWith(StoredValue);
412 ReplacedLoads[L] = StoredValue;
413 } else {
414 LiveInLoads.push_back(L);
415 }
416 continue;
417 }
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000418
419 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
Chris Lattner95294b82011-01-14 19:36:13 +0000420 // If this is a store to an unrelated pointer, ignore it.
Cameron Zwarich843bc7d2011-05-24 03:10:43 +0000421 if (!isInstInList(SI, Insts)) continue;
Devang Patela3cbf522011-07-06 21:09:55 +0000422 updateDebugInfo(SI);
Cameron Zwarich843bc7d2011-05-24 03:10:43 +0000423
Chris Lattner95294b82011-01-14 19:36:13 +0000424 // Remember that this is the active value in the block.
Cameron Zwarich843bc7d2011-05-24 03:10:43 +0000425 StoredValue = SI->getOperand(0);
Chris Lattner95294b82011-01-14 19:36:13 +0000426 }
427 }
428
429 // The last stored value that happened is the live-out for the block.
430 assert(StoredValue && "Already checked that there is a store in block");
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000431 SSA.AddAvailableValue(BB, StoredValue);
Chris Lattner95294b82011-01-14 19:36:13 +0000432 BlockUses.clear();
433 }
434
435 // Okay, now we rewrite all loads that use live-in values in the loop,
436 // inserting PHI nodes as necessary.
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000437 for (LoadInst *ALoad : LiveInLoads) {
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000438 Value *NewVal = SSA.GetValueInMiddleOfBlock(ALoad->getParent());
439 replaceLoadWithValue(ALoad, NewVal);
Chris Lattnerb4017762011-01-24 03:29:07 +0000440
441 // Avoid assertions in unreachable code.
442 if (NewVal == ALoad) NewVal = UndefValue::get(NewVal->getType());
Chris Lattner95294b82011-01-14 19:36:13 +0000443 ALoad->replaceAllUsesWith(NewVal);
444 ReplacedLoads[ALoad] = NewVal;
445 }
446
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000447 // Allow the client to do stuff before we start nuking things.
448 doExtraRewritesBeforeFinalDeletion();
449
Chris Lattner95294b82011-01-14 19:36:13 +0000450 // Now that everything is rewritten, delete the old instructions from the
451 // function. They should all be dead now.
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000452 for (Instruction *User : Insts) {
Chris Lattner95294b82011-01-14 19:36:13 +0000453 // If this is a load that still has uses, then the load must have been added
454 // as a live value in the SSAUpdate data structure for a block (e.g. because
455 // the loaded value was stored later). In this case, we need to recursively
456 // propagate the updates until we get to the real value.
457 if (!User->use_empty()) {
458 Value *NewVal = ReplacedLoads[User];
459 assert(NewVal && "not a replaced load?");
460
461 // Propagate down to the ultimate replacee. The intermediately loads
462 // could theoretically already have been deleted, so we don't want to
463 // dereference the Value*'s.
464 DenseMap<Value*, Value*>::iterator RLI = ReplacedLoads.find(NewVal);
465 while (RLI != ReplacedLoads.end()) {
466 NewVal = RLI->second;
467 RLI = ReplacedLoads.find(NewVal);
468 }
469
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000470 replaceLoadWithValue(cast<LoadInst>(User), NewVal);
Chris Lattner95294b82011-01-14 19:36:13 +0000471 User->replaceAllUsesWith(NewVal);
472 }
473
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000474 instructionDeleted(User);
Chris Lattner95294b82011-01-14 19:36:13 +0000475 User->eraseFromParent();
476 }
477}
Benjamin Kramerd00e94e2011-11-14 17:22:45 +0000478
479bool
480LoadAndStorePromoter::isInstInList(Instruction *I,
481 const SmallVectorImpl<Instruction*> &Insts)
482 const {
483 return std::find(Insts.begin(), Insts.end(), I) != Insts.end();
484}