blob: b2231d68a301af2bfa6504c887821897e9556fed [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 Carruth6bda14b2017-06-06 11:49:48 +000014#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner60d4e692009-10-10 09:04:27 +000015#include "llvm/ADT/DenseMap.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000016#include "llvm/ADT/STLExtras.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000017#include "llvm/ADT/SmallVector.h"
Chris Lattner7b70bef2011-07-18 01:43:58 +000018#include "llvm/ADT/TinyPtrVector.h"
Duncan Sands63704952010-11-16 17:41:24 +000019#include "llvm/Analysis/InstructionSimplify.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000020#include "llvm/IR/BasicBlock.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000021#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000023#include "llvm/IR/DebugLoc.h"
24#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Instructions.h"
Mehdi Aminia28d91d2015-03-10 02:37:25 +000026#include "llvm/IR/Module.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000027#include "llvm/IR/Use.h"
28#include "llvm/IR/Value.h"
29#include "llvm/IR/ValueHandle.h"
30#include "llvm/Support/Casting.h"
Chris Lattner60d4e692009-10-10 09:04:27 +000031#include "llvm/Support/Debug.h"
Chris Lattner60d4e692009-10-10 09:04:27 +000032#include "llvm/Support/raw_ostream.h"
Bob Wilsond1b38e32010-05-04 23:18:19 +000033#include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000034#include <cassert>
35#include <utility>
Devang Patela8e74112011-04-29 22:28:59 +000036
Chris Lattner60d4e692009-10-10 09:04:27 +000037using namespace llvm;
38
Chandler Carruthe96dd892014-04-21 22:55:11 +000039#define DEBUG_TYPE "ssaupdater"
40
Eugene Zelenko286d5892017-10-11 21:41:43 +000041using AvailableValsTy = DenseMap<BasicBlock *, Value *>;
42
Chris Lattner60d4e692009-10-10 09:04:27 +000043static AvailableValsTy &getAvailableVals(void *AV) {
44 return *static_cast<AvailableValsTy*>(AV);
45}
46
Eugene Zelenko286d5892017-10-11 21:41:43 +000047SSAUpdater::SSAUpdater(SmallVectorImpl<PHINode *> *NewPHI)
Eugene Zelenko34c23272017-01-18 00:57:48 +000048 : InsertedPHIs(NewPHI) {}
Chris Lattner60d4e692009-10-10 09:04:27 +000049
50SSAUpdater::~SSAUpdater() {
Richard Smith257c5f22012-08-17 21:42:44 +000051 delete static_cast<AvailableValsTy*>(AV);
Chris Lattner60d4e692009-10-10 09:04:27 +000052}
53
Chris Lattner229907c2011-07-18 04:54:35 +000054void SSAUpdater::Initialize(Type *Ty, StringRef Name) {
Craig Topperf40110f2014-04-25 05:29:35 +000055 if (!AV)
Chris Lattner60d4e692009-10-10 09:04:27 +000056 AV = new AvailableValsTy();
57 else
58 getAvailableVals(AV).clear();
Duncan Sands67781492010-09-02 08:14:03 +000059 ProtoType = Ty;
60 ProtoName = Name;
Chris Lattner60d4e692009-10-10 09:04:27 +000061}
62
Chris Lattner9c382ce2009-10-10 23:41:48 +000063bool SSAUpdater::HasValueForBlock(BasicBlock *BB) const {
64 return getAvailableVals(AV).count(BB);
65}
66
Chris Lattner60d4e692009-10-10 09:04:27 +000067void SSAUpdater::AddAvailableValue(BasicBlock *BB, Value *V) {
Craig Toppere73658d2014-04-28 04:05:08 +000068 assert(ProtoType && "Need to initialize SSAUpdater");
Duncan Sands67781492010-09-02 08:14:03 +000069 assert(ProtoType == V->getType() &&
Chris Lattner60d4e692009-10-10 09:04:27 +000070 "All rewritten values must have the same type");
71 getAvailableVals(AV)[BB] = V;
72}
73
Bob Wilsonca514252010-04-17 03:08:24 +000074static bool IsEquivalentPHI(PHINode *PHI,
Eugene Zelenko286d5892017-10-11 21:41:43 +000075 SmallDenseMap<BasicBlock *, Value *, 8> &ValueMapping) {
Bob Wilson7577e942010-01-27 22:01:02 +000076 unsigned PHINumValues = PHI->getNumIncomingValues();
77 if (PHINumValues != ValueMapping.size())
78 return false;
79
80 // Scan the phi to see if it matches.
81 for (unsigned i = 0, e = PHINumValues; i != e; ++i)
82 if (ValueMapping[PHI->getIncomingBlock(i)] !=
83 PHI->getIncomingValue(i)) {
84 return false;
85 }
86
87 return true;
88}
89
Chris Lattnere474a8d2009-10-10 22:41:58 +000090Value *SSAUpdater::GetValueAtEndOfBlock(BasicBlock *BB) {
Chris Lattnere474a8d2009-10-10 22:41:58 +000091 Value *Res = GetValueAtEndOfBlockInternal(BB);
Chris Lattner60d4e692009-10-10 09:04:27 +000092 return Res;
93}
94
Chris Lattner67cdd8b2009-10-10 23:00:11 +000095Value *SSAUpdater::GetValueInMiddleOfBlock(BasicBlock *BB) {
96 // If there is no definition of the renamed variable in this block, just use
97 // GetValueAtEndOfBlock to do our work.
Bob Wilsonca514252010-04-17 03:08:24 +000098 if (!HasValueForBlock(BB))
Chris Lattner67cdd8b2009-10-10 23:00:11 +000099 return GetValueAtEndOfBlock(BB);
Duncan Sands0058c7b2009-10-16 15:20:13 +0000100
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000101 // Otherwise, we have the hard case. Get the live-in values for each
102 // predecessor.
Eugene Zelenko286d5892017-10-11 21:41:43 +0000103 SmallVector<std::pair<BasicBlock *, Value *>, 8> PredValues;
Craig Topperf40110f2014-04-25 05:29:35 +0000104 Value *SingularValue = nullptr;
Duncan Sands0058c7b2009-10-16 15:20:13 +0000105
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000106 // We can get our predecessor info by walking the pred_iterator list, but it
107 // is relatively slow. If we already have PHI nodes in this block, walk one
108 // of them to get the predecessor list instead.
109 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
110 for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) {
111 BasicBlock *PredBB = SomePhi->getIncomingBlock(i);
112 Value *PredVal = GetValueAtEndOfBlock(PredBB);
113 PredValues.push_back(std::make_pair(PredBB, PredVal));
Duncan Sands0058c7b2009-10-16 15:20:13 +0000114
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000115 // Compute SingularValue.
116 if (i == 0)
117 SingularValue = PredVal;
118 else if (PredVal != SingularValue)
Craig Topperf40110f2014-04-25 05:29:35 +0000119 SingularValue = nullptr;
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000120 }
121 } else {
122 bool isFirstPred = true;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000123 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
124 BasicBlock *PredBB = *PI;
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000125 Value *PredVal = GetValueAtEndOfBlock(PredBB);
126 PredValues.push_back(std::make_pair(PredBB, PredVal));
Duncan Sands0058c7b2009-10-16 15:20:13 +0000127
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000128 // Compute SingularValue.
129 if (isFirstPred) {
130 SingularValue = PredVal;
131 isFirstPred = false;
132 } else if (PredVal != SingularValue)
Craig Topperf40110f2014-04-25 05:29:35 +0000133 SingularValue = nullptr;
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000134 }
135 }
Duncan Sands0058c7b2009-10-16 15:20:13 +0000136
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000137 // If there are no predecessors, just return undef.
138 if (PredValues.empty())
Duncan Sands67781492010-09-02 08:14:03 +0000139 return UndefValue::get(ProtoType);
Duncan Sands0058c7b2009-10-16 15:20:13 +0000140
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000141 // Otherwise, if all the merged values are the same, just use it.
Craig Topperf40110f2014-04-25 05:29:35 +0000142 if (SingularValue)
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000143 return SingularValue;
Duncan Sands0058c7b2009-10-16 15:20:13 +0000144
Bob Wilsonca514252010-04-17 03:08:24 +0000145 // Otherwise, we do need a PHI: check to see if we already have one available
146 // in this block that produces the right value.
147 if (isa<PHINode>(BB->begin())) {
Eugene Zelenko286d5892017-10-11 21:41:43 +0000148 SmallDenseMap<BasicBlock *, Value *, 8> ValueMapping(PredValues.begin(),
149 PredValues.end());
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000150 for (PHINode &SomePHI : BB->phis()) {
151 if (IsEquivalentPHI(&SomePHI, ValueMapping))
152 return &SomePHI;
Bob Wilsonca514252010-04-17 03:08:24 +0000153 }
154 }
Bob Wilson7577e942010-01-27 22:01:02 +0000155
Chris Lattner8fb07c52009-12-21 07:16:11 +0000156 // Ok, we have no way out, insert a new one now.
Jay Foad52131342011-03-30 11:28:46 +0000157 PHINode *InsertedPHI = PHINode::Create(ProtoType, PredValues.size(),
158 ProtoName, &BB->front());
Duncan Sands0058c7b2009-10-16 15:20:13 +0000159
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000160 // Fill in all the predecessors of the PHI.
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000161 for (const auto &PredValue : PredValues)
162 InsertedPHI->addIncoming(PredValue.second, PredValue.first);
Duncan Sands0058c7b2009-10-16 15:20:13 +0000163
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000164 // See if the PHI node can be merged to a single value. This can happen in
165 // loop cases when we get a PHI of itself and one other value.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000166 if (Value *V =
167 SimplifyInstruction(InsertedPHI, BB->getModule()->getDataLayout())) {
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000168 InsertedPHI->eraseFromParent();
Duncan Sands63704952010-11-16 17:41:24 +0000169 return V;
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000170 }
Chris Lattner249265d2009-10-10 23:15:24 +0000171
Eli Benderskyf0ad3602012-06-25 10:13:14 +0000172 // Set the DebugLoc of the inserted PHI, if available.
173 DebugLoc DL;
174 if (const Instruction *I = BB->getFirstNonPHI())
175 DL = I->getDebugLoc();
176 InsertedPHI->setDebugLoc(DL);
Devang Patela8e74112011-04-29 22:28:59 +0000177
Chris Lattner249265d2009-10-10 23:15:24 +0000178 // If the client wants to know about all new instructions, tell it.
179 if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
Duncan Sands0058c7b2009-10-16 15:20:13 +0000180
David Greene3774a382010-01-05 01:26:49 +0000181 DEBUG(dbgs() << " Inserted PHI: " << *InsertedPHI << "\n");
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000182 return InsertedPHI;
183}
184
Chris Lattner60d4e692009-10-10 09:04:27 +0000185void SSAUpdater::RewriteUse(Use &U) {
186 Instruction *User = cast<Instruction>(U.getUser());
Bob Wilsonca514252010-04-17 03:08:24 +0000187
Chris Lattner7f903682009-10-20 20:27:49 +0000188 Value *V;
189 if (PHINode *UserPN = dyn_cast<PHINode>(User))
190 V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
191 else
192 V = GetValueInMiddleOfBlock(User->getParent());
Duncan Sands0058c7b2009-10-16 15:20:13 +0000193
Nadav Rotem8d804522012-08-13 23:06:54 +0000194 // Notify that users of the existing value that it is being replaced.
195 Value *OldVal = U.get();
196 if (OldVal != V && OldVal->hasValueHandle())
197 ValueHandleBase::ValueIsRAUWd(OldVal, V);
198
Torok Edwincf10ec92009-10-20 15:42:00 +0000199 U.set(V);
Chris Lattner60d4e692009-10-10 09:04:27 +0000200}
201
Chris Lattnerc3fb03e2010-08-29 04:54:06 +0000202void SSAUpdater::RewriteUseAfterInsertions(Use &U) {
203 Instruction *User = cast<Instruction>(U.getUser());
204
205 Value *V;
206 if (PHINode *UserPN = dyn_cast<PHINode>(User))
207 V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
208 else
209 V = GetValueAtEndOfBlock(User->getParent());
210
211 U.set(V);
212}
213
Bob Wilsond1b38e32010-05-04 23:18:19 +0000214namespace llvm {
Eugene Zelenko34c23272017-01-18 00:57:48 +0000215
Bob Wilsond1b38e32010-05-04 23:18:19 +0000216template<>
217class SSAUpdaterTraits<SSAUpdater> {
218public:
Eugene Zelenko286d5892017-10-11 21:41:43 +0000219 using BlkT = BasicBlock;
220 using ValT = Value *;
221 using PhiT = PHINode;
222 using BlkSucc_iterator = succ_iterator;
Bob Wilsond1b38e32010-05-04 23:18:19 +0000223
Bob Wilsond1b38e32010-05-04 23:18:19 +0000224 static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return succ_begin(BB); }
225 static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return succ_end(BB); }
226
Chandler Carruthc60fbe62012-06-20 08:39:30 +0000227 class PHI_iterator {
228 private:
229 PHINode *PHI;
230 unsigned idx;
231
232 public:
233 explicit PHI_iterator(PHINode *P) // begin iterator
234 : PHI(P), idx(0) {}
235 PHI_iterator(PHINode *P, bool) // end iterator
236 : PHI(P), idx(PHI->getNumIncomingValues()) {}
237
238 PHI_iterator &operator++() { ++idx; return *this; }
239 bool operator==(const PHI_iterator& x) const { return idx == x.idx; }
240 bool operator!=(const PHI_iterator& x) const { return !operator==(x); }
Eugene Zelenko34c23272017-01-18 00:57:48 +0000241
Chandler Carruthc60fbe62012-06-20 08:39:30 +0000242 Value *getIncomingValue() { return PHI->getIncomingValue(idx); }
243 BasicBlock *getIncomingBlock() { return PHI->getIncomingBlock(idx); }
244 };
245
246 static PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
247 static PHI_iterator PHI_end(PhiT *PHI) {
Bob Wilsond1b38e32010-05-04 23:18:19 +0000248 return PHI_iterator(PHI, true);
249 }
250
251 /// FindPredecessorBlocks - Put the predecessors of Info->BB into the Preds
252 /// vector, set Info->NumPreds, and allocate space in Info->Preds.
253 static void FindPredecessorBlocks(BasicBlock *BB,
Eugene Zelenko286d5892017-10-11 21:41:43 +0000254 SmallVectorImpl<BasicBlock *> *Preds) {
Bob Wilsond1b38e32010-05-04 23:18:19 +0000255 // We can get our predecessor info by walking the pred_iterator list,
256 // but it is relatively slow. If we already have PHI nodes in this
257 // block, walk one of them to get the predecessor list instead.
258 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000259 Preds->append(SomePhi->block_begin(), SomePhi->block_end());
Bob Wilsond1b38e32010-05-04 23:18:19 +0000260 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000261 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
262 Preds->push_back(*PI);
Bob Wilsond1b38e32010-05-04 23:18:19 +0000263 }
264 }
265
266 /// GetUndefVal - Get an undefined value of the same type as the value
267 /// being handled.
268 static Value *GetUndefVal(BasicBlock *BB, SSAUpdater *Updater) {
Duncan Sands67781492010-09-02 08:14:03 +0000269 return UndefValue::get(Updater->ProtoType);
Bob Wilsond1b38e32010-05-04 23:18:19 +0000270 }
271
272 /// CreateEmptyPHI - Create a new PHI instruction in the specified block.
273 /// Reserve space for the operands but do not fill them in yet.
274 static Value *CreateEmptyPHI(BasicBlock *BB, unsigned NumPreds,
275 SSAUpdater *Updater) {
Jay Foad52131342011-03-30 11:28:46 +0000276 PHINode *PHI = PHINode::Create(Updater->ProtoType, NumPreds,
277 Updater->ProtoName, &BB->front());
Bob Wilsond1b38e32010-05-04 23:18:19 +0000278 return PHI;
279 }
280
281 /// AddPHIOperand - Add the specified value as an operand of the PHI for
282 /// the specified predecessor block.
283 static void AddPHIOperand(PHINode *PHI, Value *Val, BasicBlock *Pred) {
284 PHI->addIncoming(Val, Pred);
285 }
286
287 /// InstrIsPHI - Check if an instruction is a PHI.
288 ///
289 static PHINode *InstrIsPHI(Instruction *I) {
290 return dyn_cast<PHINode>(I);
291 }
292
293 /// ValueIsPHI - Check if a value is a PHI.
Bob Wilsond1b38e32010-05-04 23:18:19 +0000294 static PHINode *ValueIsPHI(Value *Val, SSAUpdater *Updater) {
295 return dyn_cast<PHINode>(Val);
296 }
297
298 /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
299 /// operands, i.e., it was just added.
300 static PHINode *ValueIsNewPHI(Value *Val, SSAUpdater *Updater) {
301 PHINode *PHI = ValueIsPHI(Val, Updater);
302 if (PHI && PHI->getNumIncomingValues() == 0)
303 return PHI;
Craig Topperf40110f2014-04-25 05:29:35 +0000304 return nullptr;
Bob Wilsond1b38e32010-05-04 23:18:19 +0000305 }
306
307 /// GetPHIValue - For the specified PHI instruction, return the value
308 /// that it defines.
309 static Value *GetPHIValue(PHINode *PHI) {
310 return PHI;
311 }
312};
313
Eugene Zelenko34c23272017-01-18 00:57:48 +0000314} // end namespace llvm
Bob Wilsond1b38e32010-05-04 23:18:19 +0000315
Chandler Carruth6b55dbe2013-07-28 22:00:33 +0000316/// Check to see if AvailableVals has an entry for the specified BB and if so,
317/// return it. If not, construct SSA form by first calculating the required
318/// placement of PHIs and then inserting new PHIs where needed.
Chris Lattnere474a8d2009-10-10 22:41:58 +0000319Value *SSAUpdater::GetValueAtEndOfBlockInternal(BasicBlock *BB) {
Chris Lattner60d4e692009-10-10 09:04:27 +0000320 AvailableValsTy &AvailableVals = getAvailableVals(AV);
Bob Wilsonca514252010-04-17 03:08:24 +0000321 if (Value *V = AvailableVals[BB])
322 return V;
Duncan Sands0058c7b2009-10-16 15:20:13 +0000323
Bob Wilsond1b38e32010-05-04 23:18:19 +0000324 SSAUpdaterImpl<SSAUpdater> Impl(this, &AvailableVals, InsertedPHIs);
325 return Impl.GetValue(BB);
Chris Lattner60d4e692009-10-10 09:04:27 +0000326}
Chris Lattner95294b82011-01-14 19:36:13 +0000327
328//===----------------------------------------------------------------------===//
329// LoadAndStorePromoter Implementation
330//===----------------------------------------------------------------------===//
331
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000332LoadAndStorePromoter::
Eugene Zelenko286d5892017-10-11 21:41:43 +0000333LoadAndStorePromoter(ArrayRef<const Instruction *> Insts,
Devang Patela3cbf522011-07-06 21:09:55 +0000334 SSAUpdater &S, StringRef BaseName) : SSA(S) {
Chris Lattner95294b82011-01-14 19:36:13 +0000335 if (Insts.empty()) return;
336
Pete Cooper41e0ee32015-05-13 01:12:16 +0000337 const Value *SomeVal;
338 if (const LoadInst *LI = dyn_cast<LoadInst>(Insts[0]))
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000339 SomeVal = LI;
Chris Lattner95294b82011-01-14 19:36:13 +0000340 else
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000341 SomeVal = cast<StoreInst>(Insts[0])->getOperand(0);
342
343 if (BaseName.empty())
344 BaseName = SomeVal->getName();
345 SSA.Initialize(SomeVal->getType(), BaseName);
346}
347
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000348void LoadAndStorePromoter::
Eugene Zelenko286d5892017-10-11 21:41:43 +0000349run(const SmallVectorImpl<Instruction *> &Insts) const {
Chris Lattner95294b82011-01-14 19:36:13 +0000350 // First step: bucket up uses of the alloca by the block they occur in.
351 // This is important because we have to handle multiple defs/uses in a block
352 // ourselves: SSAUpdater is purely for cross-block references.
Eugene Zelenko286d5892017-10-11 21:41:43 +0000353 DenseMap<BasicBlock *, TinyPtrVector<Instruction *>> UsesByBlock;
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000354
355 for (Instruction *User : Insts)
Chris Lattner95294b82011-01-14 19:36:13 +0000356 UsesByBlock[User->getParent()].push_back(User);
Chris Lattner95294b82011-01-14 19:36:13 +0000357
358 // Okay, now we can iterate over all the blocks in the function with uses,
359 // processing them. Keep track of which loads are loading a live-in value.
360 // Walk the uses in the use-list order to be determinstic.
Eugene Zelenko286d5892017-10-11 21:41:43 +0000361 SmallVector<LoadInst *, 32> LiveInLoads;
362 DenseMap<Value *, Value *> ReplacedLoads;
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000363
364 for (Instruction *User : Insts) {
Chris Lattner95294b82011-01-14 19:36:13 +0000365 BasicBlock *BB = User->getParent();
Eugene Zelenko286d5892017-10-11 21:41:43 +0000366 TinyPtrVector<Instruction *> &BlockUses = UsesByBlock[BB];
Chris Lattner95294b82011-01-14 19:36:13 +0000367
368 // If this block has already been processed, ignore this repeat use.
369 if (BlockUses.empty()) continue;
370
371 // Okay, this is the first use in the block. If this block just has a
372 // single user in it, we can rewrite it trivially.
373 if (BlockUses.size() == 1) {
374 // If it is a store, it is a trivial def of the value in the block.
Cameron Zwarich843bc7d2011-05-24 03:10:43 +0000375 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Devang Patela3cbf522011-07-06 21:09:55 +0000376 updateDebugInfo(SI);
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000377 SSA.AddAvailableValue(BB, SI->getOperand(0));
Cameron Zwarich843bc7d2011-05-24 03:10:43 +0000378 } else
Chris Lattner95294b82011-01-14 19:36:13 +0000379 // Otherwise it is a load, queue it to rewrite as a live-in load.
380 LiveInLoads.push_back(cast<LoadInst>(User));
381 BlockUses.clear();
382 continue;
383 }
384
385 // Otherwise, check to see if this block is all loads.
386 bool HasStore = false;
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000387 for (Instruction *I : BlockUses) {
388 if (isa<StoreInst>(I)) {
Chris Lattner95294b82011-01-14 19:36:13 +0000389 HasStore = true;
390 break;
391 }
392 }
393
394 // If so, we can queue them all as live in loads. We don't have an
395 // efficient way to tell which on is first in the block and don't want to
396 // scan large blocks, so just add all loads as live ins.
397 if (!HasStore) {
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000398 for (Instruction *I : BlockUses)
399 LiveInLoads.push_back(cast<LoadInst>(I));
Chris Lattner95294b82011-01-14 19:36:13 +0000400 BlockUses.clear();
401 continue;
402 }
403
404 // Otherwise, we have mixed loads and stores (or just a bunch of stores).
405 // Since SSAUpdater is purely for cross-block values, we need to determine
406 // the order of these instructions in the block. If the first use in the
407 // block is a load, then it uses the live in value. The last store defines
408 // the live out value. We handle this by doing a linear scan of the block.
Craig Topperf40110f2014-04-25 05:29:35 +0000409 Value *StoredValue = nullptr;
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000410 for (Instruction &I : *BB) {
411 if (LoadInst *L = dyn_cast<LoadInst>(&I)) {
Chris Lattner95294b82011-01-14 19:36:13 +0000412 // If this is a load from an unrelated pointer, ignore it.
413 if (!isInstInList(L, Insts)) continue;
414
415 // If we haven't seen a store yet, this is a live in use, otherwise
416 // use the stored value.
417 if (StoredValue) {
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000418 replaceLoadWithValue(L, StoredValue);
Chris Lattner95294b82011-01-14 19:36:13 +0000419 L->replaceAllUsesWith(StoredValue);
420 ReplacedLoads[L] = StoredValue;
421 } else {
422 LiveInLoads.push_back(L);
423 }
424 continue;
425 }
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000426
427 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
Chris Lattner95294b82011-01-14 19:36:13 +0000428 // If this is a store to an unrelated pointer, ignore it.
Cameron Zwarich843bc7d2011-05-24 03:10:43 +0000429 if (!isInstInList(SI, Insts)) continue;
Devang Patela3cbf522011-07-06 21:09:55 +0000430 updateDebugInfo(SI);
Cameron Zwarich843bc7d2011-05-24 03:10:43 +0000431
Chris Lattner95294b82011-01-14 19:36:13 +0000432 // Remember that this is the active value in the block.
Cameron Zwarich843bc7d2011-05-24 03:10:43 +0000433 StoredValue = SI->getOperand(0);
Chris Lattner95294b82011-01-14 19:36:13 +0000434 }
435 }
436
437 // The last stored value that happened is the live-out for the block.
438 assert(StoredValue && "Already checked that there is a store in block");
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000439 SSA.AddAvailableValue(BB, StoredValue);
Chris Lattner95294b82011-01-14 19:36:13 +0000440 BlockUses.clear();
441 }
442
443 // Okay, now we rewrite all loads that use live-in values in the loop,
444 // inserting PHI nodes as necessary.
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000445 for (LoadInst *ALoad : LiveInLoads) {
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000446 Value *NewVal = SSA.GetValueInMiddleOfBlock(ALoad->getParent());
447 replaceLoadWithValue(ALoad, NewVal);
Chris Lattnerb4017762011-01-24 03:29:07 +0000448
449 // Avoid assertions in unreachable code.
450 if (NewVal == ALoad) NewVal = UndefValue::get(NewVal->getType());
Chris Lattner95294b82011-01-14 19:36:13 +0000451 ALoad->replaceAllUsesWith(NewVal);
452 ReplacedLoads[ALoad] = NewVal;
453 }
454
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000455 // Allow the client to do stuff before we start nuking things.
456 doExtraRewritesBeforeFinalDeletion();
457
Chris Lattner95294b82011-01-14 19:36:13 +0000458 // Now that everything is rewritten, delete the old instructions from the
459 // function. They should all be dead now.
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000460 for (Instruction *User : Insts) {
Chris Lattner95294b82011-01-14 19:36:13 +0000461 // If this is a load that still has uses, then the load must have been added
462 // as a live value in the SSAUpdate data structure for a block (e.g. because
463 // the loaded value was stored later). In this case, we need to recursively
464 // propagate the updates until we get to the real value.
465 if (!User->use_empty()) {
466 Value *NewVal = ReplacedLoads[User];
467 assert(NewVal && "not a replaced load?");
468
469 // Propagate down to the ultimate replacee. The intermediately loads
470 // could theoretically already have been deleted, so we don't want to
471 // dereference the Value*'s.
472 DenseMap<Value*, Value*>::iterator RLI = ReplacedLoads.find(NewVal);
473 while (RLI != ReplacedLoads.end()) {
474 NewVal = RLI->second;
475 RLI = ReplacedLoads.find(NewVal);
476 }
477
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000478 replaceLoadWithValue(cast<LoadInst>(User), NewVal);
Chris Lattner95294b82011-01-14 19:36:13 +0000479 User->replaceAllUsesWith(NewVal);
480 }
481
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000482 instructionDeleted(User);
Chris Lattner95294b82011-01-14 19:36:13 +0000483 User->eraseFromParent();
484 }
485}
Benjamin Kramerd00e94e2011-11-14 17:22:45 +0000486
487bool
488LoadAndStorePromoter::isInstInList(Instruction *I,
Eugene Zelenko286d5892017-10-11 21:41:43 +0000489 const SmallVectorImpl<Instruction *> &Insts)
Benjamin Kramerd00e94e2011-11-14 17:22:45 +0000490 const {
David Majnemer0d955d02016-08-11 22:21:41 +0000491 return is_contained(Insts, I);
Benjamin Kramerd00e94e2011-11-14 17:22:45 +0000492}