blob: bffdd115d940cdce5aff51d4f7b76b6ac9cbd1b7 [file] [log] [blame]
Chris Lattner60d4e692009-10-10 09:04:27 +00001//===- SSAUpdater.cpp - Unstructured SSA Update Tool ----------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner60d4e692009-10-10 09:04:27 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the SSAUpdater class.
10//
11//===----------------------------------------------------------------------===//
12
Chandler Carruth6bda14b2017-06-06 11:49:48 +000013#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner60d4e692009-10-10 09:04:27 +000014#include "llvm/ADT/DenseMap.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000015#include "llvm/ADT/STLExtras.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000016#include "llvm/ADT/SmallVector.h"
Chris Lattner7b70bef2011-07-18 01:43:58 +000017#include "llvm/ADT/TinyPtrVector.h"
Duncan Sands63704952010-11-16 17:41:24 +000018#include "llvm/Analysis/InstructionSimplify.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000019#include "llvm/IR/BasicBlock.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000020#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/Constants.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000022#include "llvm/IR/DebugLoc.h"
23#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Instructions.h"
Mehdi Aminia28d91d2015-03-10 02:37:25 +000025#include "llvm/IR/Module.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000026#include "llvm/IR/Use.h"
27#include "llvm/IR/Value.h"
28#include "llvm/IR/ValueHandle.h"
29#include "llvm/Support/Casting.h"
Chris Lattner60d4e692009-10-10 09:04:27 +000030#include "llvm/Support/Debug.h"
Chris Lattner60d4e692009-10-10 09:04:27 +000031#include "llvm/Support/raw_ostream.h"
Bob Wilsond1b38e32010-05-04 23:18:19 +000032#include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
Eugene Zelenko34c23272017-01-18 00:57:48 +000033#include <cassert>
34#include <utility>
Devang Patela8e74112011-04-29 22:28:59 +000035
Chris Lattner60d4e692009-10-10 09:04:27 +000036using namespace llvm;
37
Chandler Carruthe96dd892014-04-21 22:55:11 +000038#define DEBUG_TYPE "ssaupdater"
39
Eugene Zelenko286d5892017-10-11 21:41:43 +000040using AvailableValsTy = DenseMap<BasicBlock *, Value *>;
41
Chris Lattner60d4e692009-10-10 09:04:27 +000042static AvailableValsTy &getAvailableVals(void *AV) {
43 return *static_cast<AvailableValsTy*>(AV);
44}
45
Eugene Zelenko286d5892017-10-11 21:41:43 +000046SSAUpdater::SSAUpdater(SmallVectorImpl<PHINode *> *NewPHI)
Eugene Zelenko34c23272017-01-18 00:57:48 +000047 : InsertedPHIs(NewPHI) {}
Chris Lattner60d4e692009-10-10 09:04:27 +000048
49SSAUpdater::~SSAUpdater() {
Richard Smith257c5f22012-08-17 21:42:44 +000050 delete static_cast<AvailableValsTy*>(AV);
Chris Lattner60d4e692009-10-10 09:04:27 +000051}
52
Chris Lattner229907c2011-07-18 04:54:35 +000053void SSAUpdater::Initialize(Type *Ty, StringRef Name) {
Craig Topperf40110f2014-04-25 05:29:35 +000054 if (!AV)
Chris Lattner60d4e692009-10-10 09:04:27 +000055 AV = new AvailableValsTy();
56 else
57 getAvailableVals(AV).clear();
Duncan Sands67781492010-09-02 08:14:03 +000058 ProtoType = Ty;
59 ProtoName = Name;
Chris Lattner60d4e692009-10-10 09:04:27 +000060}
61
Chris Lattner9c382ce2009-10-10 23:41:48 +000062bool SSAUpdater::HasValueForBlock(BasicBlock *BB) const {
63 return getAvailableVals(AV).count(BB);
64}
65
David Stenbergc9163852018-10-16 08:06:48 +000066Value *SSAUpdater::FindValueForBlock(BasicBlock *BB) const {
67 AvailableValsTy::iterator AVI = getAvailableVals(AV).find(BB);
68 return (AVI != getAvailableVals(AV).end()) ? AVI->second : nullptr;
69}
70
Chris Lattner60d4e692009-10-10 09:04:27 +000071void SSAUpdater::AddAvailableValue(BasicBlock *BB, Value *V) {
Craig Toppere73658d2014-04-28 04:05:08 +000072 assert(ProtoType && "Need to initialize SSAUpdater");
Duncan Sands67781492010-09-02 08:14:03 +000073 assert(ProtoType == V->getType() &&
Chris Lattner60d4e692009-10-10 09:04:27 +000074 "All rewritten values must have the same type");
75 getAvailableVals(AV)[BB] = V;
76}
77
Bob Wilsonca514252010-04-17 03:08:24 +000078static bool IsEquivalentPHI(PHINode *PHI,
Eugene Zelenko286d5892017-10-11 21:41:43 +000079 SmallDenseMap<BasicBlock *, Value *, 8> &ValueMapping) {
Bob Wilson7577e942010-01-27 22:01:02 +000080 unsigned PHINumValues = PHI->getNumIncomingValues();
81 if (PHINumValues != ValueMapping.size())
82 return false;
83
84 // Scan the phi to see if it matches.
85 for (unsigned i = 0, e = PHINumValues; i != e; ++i)
86 if (ValueMapping[PHI->getIncomingBlock(i)] !=
87 PHI->getIncomingValue(i)) {
88 return false;
89 }
90
91 return true;
92}
93
Chris Lattnere474a8d2009-10-10 22:41:58 +000094Value *SSAUpdater::GetValueAtEndOfBlock(BasicBlock *BB) {
Chris Lattnere474a8d2009-10-10 22:41:58 +000095 Value *Res = GetValueAtEndOfBlockInternal(BB);
Chris Lattner60d4e692009-10-10 09:04:27 +000096 return Res;
97}
98
Chris Lattner67cdd8b2009-10-10 23:00:11 +000099Value *SSAUpdater::GetValueInMiddleOfBlock(BasicBlock *BB) {
100 // If there is no definition of the renamed variable in this block, just use
101 // GetValueAtEndOfBlock to do our work.
Bob Wilsonca514252010-04-17 03:08:24 +0000102 if (!HasValueForBlock(BB))
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000103 return GetValueAtEndOfBlock(BB);
Duncan Sands0058c7b2009-10-16 15:20:13 +0000104
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000105 // Otherwise, we have the hard case. Get the live-in values for each
106 // predecessor.
Eugene Zelenko286d5892017-10-11 21:41:43 +0000107 SmallVector<std::pair<BasicBlock *, Value *>, 8> PredValues;
Craig Topperf40110f2014-04-25 05:29:35 +0000108 Value *SingularValue = nullptr;
Duncan Sands0058c7b2009-10-16 15:20:13 +0000109
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000110 // We can get our predecessor info by walking the pred_iterator list, but it
111 // is relatively slow. If we already have PHI nodes in this block, walk one
112 // of them to get the predecessor list instead.
113 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
114 for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) {
115 BasicBlock *PredBB = SomePhi->getIncomingBlock(i);
116 Value *PredVal = GetValueAtEndOfBlock(PredBB);
117 PredValues.push_back(std::make_pair(PredBB, PredVal));
Duncan Sands0058c7b2009-10-16 15:20:13 +0000118
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000119 // Compute SingularValue.
120 if (i == 0)
121 SingularValue = PredVal;
122 else if (PredVal != SingularValue)
Craig Topperf40110f2014-04-25 05:29:35 +0000123 SingularValue = nullptr;
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000124 }
125 } else {
126 bool isFirstPred = true;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000127 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
128 BasicBlock *PredBB = *PI;
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000129 Value *PredVal = GetValueAtEndOfBlock(PredBB);
130 PredValues.push_back(std::make_pair(PredBB, PredVal));
Duncan Sands0058c7b2009-10-16 15:20:13 +0000131
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000132 // Compute SingularValue.
133 if (isFirstPred) {
134 SingularValue = PredVal;
135 isFirstPred = false;
136 } else if (PredVal != SingularValue)
Craig Topperf40110f2014-04-25 05:29:35 +0000137 SingularValue = nullptr;
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000138 }
139 }
Duncan Sands0058c7b2009-10-16 15:20:13 +0000140
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000141 // If there are no predecessors, just return undef.
142 if (PredValues.empty())
Duncan Sands67781492010-09-02 08:14:03 +0000143 return UndefValue::get(ProtoType);
Duncan Sands0058c7b2009-10-16 15:20:13 +0000144
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000145 // Otherwise, if all the merged values are the same, just use it.
Craig Topperf40110f2014-04-25 05:29:35 +0000146 if (SingularValue)
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000147 return SingularValue;
Duncan Sands0058c7b2009-10-16 15:20:13 +0000148
Bob Wilsonca514252010-04-17 03:08:24 +0000149 // Otherwise, we do need a PHI: check to see if we already have one available
150 // in this block that produces the right value.
151 if (isa<PHINode>(BB->begin())) {
Eugene Zelenko286d5892017-10-11 21:41:43 +0000152 SmallDenseMap<BasicBlock *, Value *, 8> ValueMapping(PredValues.begin(),
153 PredValues.end());
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000154 for (PHINode &SomePHI : BB->phis()) {
155 if (IsEquivalentPHI(&SomePHI, ValueMapping))
156 return &SomePHI;
Bob Wilsonca514252010-04-17 03:08:24 +0000157 }
158 }
Bob Wilson7577e942010-01-27 22:01:02 +0000159
Chris Lattner8fb07c52009-12-21 07:16:11 +0000160 // Ok, we have no way out, insert a new one now.
Jay Foad52131342011-03-30 11:28:46 +0000161 PHINode *InsertedPHI = PHINode::Create(ProtoType, PredValues.size(),
162 ProtoName, &BB->front());
Duncan Sands0058c7b2009-10-16 15:20:13 +0000163
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000164 // Fill in all the predecessors of the PHI.
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000165 for (const auto &PredValue : PredValues)
166 InsertedPHI->addIncoming(PredValue.second, PredValue.first);
Duncan Sands0058c7b2009-10-16 15:20:13 +0000167
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000168 // See if the PHI node can be merged to a single value. This can happen in
169 // loop cases when we get a PHI of itself and one other value.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000170 if (Value *V =
171 SimplifyInstruction(InsertedPHI, BB->getModule()->getDataLayout())) {
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000172 InsertedPHI->eraseFromParent();
Duncan Sands63704952010-11-16 17:41:24 +0000173 return V;
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000174 }
Chris Lattner249265d2009-10-10 23:15:24 +0000175
Eli Benderskyf0ad3602012-06-25 10:13:14 +0000176 // Set the DebugLoc of the inserted PHI, if available.
177 DebugLoc DL;
178 if (const Instruction *I = BB->getFirstNonPHI())
179 DL = I->getDebugLoc();
180 InsertedPHI->setDebugLoc(DL);
Devang Patela8e74112011-04-29 22:28:59 +0000181
Chris Lattner249265d2009-10-10 23:15:24 +0000182 // If the client wants to know about all new instructions, tell it.
183 if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
Duncan Sands0058c7b2009-10-16 15:20:13 +0000184
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000185 LLVM_DEBUG(dbgs() << " Inserted PHI: " << *InsertedPHI << "\n");
Chris Lattner67cdd8b2009-10-10 23:00:11 +0000186 return InsertedPHI;
187}
188
Chris Lattner60d4e692009-10-10 09:04:27 +0000189void SSAUpdater::RewriteUse(Use &U) {
190 Instruction *User = cast<Instruction>(U.getUser());
Bob Wilsonca514252010-04-17 03:08:24 +0000191
Chris Lattner7f903682009-10-20 20:27:49 +0000192 Value *V;
193 if (PHINode *UserPN = dyn_cast<PHINode>(User))
194 V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
195 else
196 V = GetValueInMiddleOfBlock(User->getParent());
Duncan Sands0058c7b2009-10-16 15:20:13 +0000197
Nadav Rotem8d804522012-08-13 23:06:54 +0000198 // Notify that users of the existing value that it is being replaced.
199 Value *OldVal = U.get();
200 if (OldVal != V && OldVal->hasValueHandle())
201 ValueHandleBase::ValueIsRAUWd(OldVal, V);
202
Torok Edwincf10ec92009-10-20 15:42:00 +0000203 U.set(V);
Chris Lattner60d4e692009-10-10 09:04:27 +0000204}
205
Chris Lattnerc3fb03e2010-08-29 04:54:06 +0000206void SSAUpdater::RewriteUseAfterInsertions(Use &U) {
207 Instruction *User = cast<Instruction>(U.getUser());
Fangrui Songf78650a2018-07-30 19:41:25 +0000208
Chris Lattnerc3fb03e2010-08-29 04:54:06 +0000209 Value *V;
210 if (PHINode *UserPN = dyn_cast<PHINode>(User))
211 V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
212 else
213 V = GetValueAtEndOfBlock(User->getParent());
Fangrui Songf78650a2018-07-30 19:41:25 +0000214
Chris Lattnerc3fb03e2010-08-29 04:54:06 +0000215 U.set(V);
216}
217
Bob Wilsond1b38e32010-05-04 23:18:19 +0000218namespace llvm {
Eugene Zelenko34c23272017-01-18 00:57:48 +0000219
Bob Wilsond1b38e32010-05-04 23:18:19 +0000220template<>
221class SSAUpdaterTraits<SSAUpdater> {
222public:
Eugene Zelenko286d5892017-10-11 21:41:43 +0000223 using BlkT = BasicBlock;
224 using ValT = Value *;
225 using PhiT = PHINode;
226 using BlkSucc_iterator = succ_iterator;
Bob Wilsond1b38e32010-05-04 23:18:19 +0000227
Bob Wilsond1b38e32010-05-04 23:18:19 +0000228 static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return succ_begin(BB); }
229 static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return succ_end(BB); }
230
Chandler Carruthc60fbe62012-06-20 08:39:30 +0000231 class PHI_iterator {
232 private:
233 PHINode *PHI;
234 unsigned idx;
235
236 public:
237 explicit PHI_iterator(PHINode *P) // begin iterator
238 : PHI(P), idx(0) {}
239 PHI_iterator(PHINode *P, bool) // end iterator
240 : PHI(P), idx(PHI->getNumIncomingValues()) {}
241
Fangrui Songf78650a2018-07-30 19:41:25 +0000242 PHI_iterator &operator++() { ++idx; return *this; }
Chandler Carruthc60fbe62012-06-20 08:39:30 +0000243 bool operator==(const PHI_iterator& x) const { return idx == x.idx; }
244 bool operator!=(const PHI_iterator& x) const { return !operator==(x); }
Eugene Zelenko34c23272017-01-18 00:57:48 +0000245
Chandler Carruthc60fbe62012-06-20 08:39:30 +0000246 Value *getIncomingValue() { return PHI->getIncomingValue(idx); }
247 BasicBlock *getIncomingBlock() { return PHI->getIncomingBlock(idx); }
248 };
249
250 static PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
251 static PHI_iterator PHI_end(PhiT *PHI) {
Bob Wilsond1b38e32010-05-04 23:18:19 +0000252 return PHI_iterator(PHI, true);
253 }
254
255 /// FindPredecessorBlocks - Put the predecessors of Info->BB into the Preds
256 /// vector, set Info->NumPreds, and allocate space in Info->Preds.
257 static void FindPredecessorBlocks(BasicBlock *BB,
Eugene Zelenko286d5892017-10-11 21:41:43 +0000258 SmallVectorImpl<BasicBlock *> *Preds) {
Bob Wilsond1b38e32010-05-04 23:18:19 +0000259 // We can get our predecessor info by walking the pred_iterator list,
260 // but it is relatively slow. If we already have PHI nodes in this
261 // block, walk one of them to get the predecessor list instead.
262 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000263 Preds->append(SomePhi->block_begin(), SomePhi->block_end());
Bob Wilsond1b38e32010-05-04 23:18:19 +0000264 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000265 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
266 Preds->push_back(*PI);
Bob Wilsond1b38e32010-05-04 23:18:19 +0000267 }
268 }
269
270 /// GetUndefVal - Get an undefined value of the same type as the value
271 /// being handled.
272 static Value *GetUndefVal(BasicBlock *BB, SSAUpdater *Updater) {
Duncan Sands67781492010-09-02 08:14:03 +0000273 return UndefValue::get(Updater->ProtoType);
Bob Wilsond1b38e32010-05-04 23:18:19 +0000274 }
275
276 /// CreateEmptyPHI - Create a new PHI instruction in the specified block.
277 /// Reserve space for the operands but do not fill them in yet.
278 static Value *CreateEmptyPHI(BasicBlock *BB, unsigned NumPreds,
279 SSAUpdater *Updater) {
Jay Foad52131342011-03-30 11:28:46 +0000280 PHINode *PHI = PHINode::Create(Updater->ProtoType, NumPreds,
281 Updater->ProtoName, &BB->front());
Bob Wilsond1b38e32010-05-04 23:18:19 +0000282 return PHI;
283 }
284
285 /// AddPHIOperand - Add the specified value as an operand of the PHI for
286 /// the specified predecessor block.
287 static void AddPHIOperand(PHINode *PHI, Value *Val, BasicBlock *Pred) {
288 PHI->addIncoming(Val, Pred);
289 }
290
291 /// InstrIsPHI - Check if an instruction is a PHI.
292 ///
293 static PHINode *InstrIsPHI(Instruction *I) {
294 return dyn_cast<PHINode>(I);
295 }
296
297 /// ValueIsPHI - Check if a value is a PHI.
Bob Wilsond1b38e32010-05-04 23:18:19 +0000298 static PHINode *ValueIsPHI(Value *Val, SSAUpdater *Updater) {
299 return dyn_cast<PHINode>(Val);
300 }
301
302 /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
303 /// operands, i.e., it was just added.
304 static PHINode *ValueIsNewPHI(Value *Val, SSAUpdater *Updater) {
305 PHINode *PHI = ValueIsPHI(Val, Updater);
306 if (PHI && PHI->getNumIncomingValues() == 0)
307 return PHI;
Craig Topperf40110f2014-04-25 05:29:35 +0000308 return nullptr;
Bob Wilsond1b38e32010-05-04 23:18:19 +0000309 }
310
311 /// GetPHIValue - For the specified PHI instruction, return the value
312 /// that it defines.
313 static Value *GetPHIValue(PHINode *PHI) {
314 return PHI;
315 }
316};
317
Eugene Zelenko34c23272017-01-18 00:57:48 +0000318} // end namespace llvm
Bob Wilsond1b38e32010-05-04 23:18:19 +0000319
Chandler Carruth6b55dbe2013-07-28 22:00:33 +0000320/// Check to see if AvailableVals has an entry for the specified BB and if so,
321/// return it. If not, construct SSA form by first calculating the required
322/// placement of PHIs and then inserting new PHIs where needed.
Chris Lattnere474a8d2009-10-10 22:41:58 +0000323Value *SSAUpdater::GetValueAtEndOfBlockInternal(BasicBlock *BB) {
Chris Lattner60d4e692009-10-10 09:04:27 +0000324 AvailableValsTy &AvailableVals = getAvailableVals(AV);
Bob Wilsonca514252010-04-17 03:08:24 +0000325 if (Value *V = AvailableVals[BB])
326 return V;
Duncan Sands0058c7b2009-10-16 15:20:13 +0000327
Bob Wilsond1b38e32010-05-04 23:18:19 +0000328 SSAUpdaterImpl<SSAUpdater> Impl(this, &AvailableVals, InsertedPHIs);
329 return Impl.GetValue(BB);
Chris Lattner60d4e692009-10-10 09:04:27 +0000330}
Chris Lattner95294b82011-01-14 19:36:13 +0000331
332//===----------------------------------------------------------------------===//
333// LoadAndStorePromoter Implementation
334//===----------------------------------------------------------------------===//
335
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000336LoadAndStorePromoter::
Eugene Zelenko286d5892017-10-11 21:41:43 +0000337LoadAndStorePromoter(ArrayRef<const Instruction *> Insts,
Devang Patela3cbf522011-07-06 21:09:55 +0000338 SSAUpdater &S, StringRef BaseName) : SSA(S) {
Chris Lattner95294b82011-01-14 19:36:13 +0000339 if (Insts.empty()) return;
Fangrui Songf78650a2018-07-30 19:41:25 +0000340
Pete Cooper41e0ee32015-05-13 01:12:16 +0000341 const Value *SomeVal;
342 if (const LoadInst *LI = dyn_cast<LoadInst>(Insts[0]))
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000343 SomeVal = LI;
Chris Lattner95294b82011-01-14 19:36:13 +0000344 else
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000345 SomeVal = cast<StoreInst>(Insts[0])->getOperand(0);
346
347 if (BaseName.empty())
348 BaseName = SomeVal->getName();
349 SSA.Initialize(SomeVal->getType(), BaseName);
350}
351
Alina Sbirlea6cba96e2019-02-06 20:25:17 +0000352void LoadAndStorePromoter::run(const SmallVectorImpl<Instruction *> &Insts) {
Chris Lattner95294b82011-01-14 19:36:13 +0000353 // First step: bucket up uses of the alloca by the block they occur in.
354 // This is important because we have to handle multiple defs/uses in a block
355 // ourselves: SSAUpdater is purely for cross-block references.
Eugene Zelenko286d5892017-10-11 21:41:43 +0000356 DenseMap<BasicBlock *, TinyPtrVector<Instruction *>> UsesByBlock;
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000357
358 for (Instruction *User : Insts)
Chris Lattner95294b82011-01-14 19:36:13 +0000359 UsesByBlock[User->getParent()].push_back(User);
Fangrui Songf78650a2018-07-30 19:41:25 +0000360
Chris Lattner95294b82011-01-14 19:36:13 +0000361 // Okay, now we can iterate over all the blocks in the function with uses,
362 // processing them. Keep track of which loads are loading a live-in value.
363 // Walk the uses in the use-list order to be determinstic.
Eugene Zelenko286d5892017-10-11 21:41:43 +0000364 SmallVector<LoadInst *, 32> LiveInLoads;
365 DenseMap<Value *, Value *> ReplacedLoads;
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000366
367 for (Instruction *User : Insts) {
Chris Lattner95294b82011-01-14 19:36:13 +0000368 BasicBlock *BB = User->getParent();
Eugene Zelenko286d5892017-10-11 21:41:43 +0000369 TinyPtrVector<Instruction *> &BlockUses = UsesByBlock[BB];
Fangrui Songf78650a2018-07-30 19:41:25 +0000370
Chris Lattner95294b82011-01-14 19:36:13 +0000371 // If this block has already been processed, ignore this repeat use.
372 if (BlockUses.empty()) continue;
Fangrui Songf78650a2018-07-30 19:41:25 +0000373
Chris Lattner95294b82011-01-14 19:36:13 +0000374 // Okay, this is the first use in the block. If this block just has a
375 // single user in it, we can rewrite it trivially.
376 if (BlockUses.size() == 1) {
377 // If it is a store, it is a trivial def of the value in the block.
Cameron Zwarich843bc7d2011-05-24 03:10:43 +0000378 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Devang Patela3cbf522011-07-06 21:09:55 +0000379 updateDebugInfo(SI);
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000380 SSA.AddAvailableValue(BB, SI->getOperand(0));
Fangrui Songf78650a2018-07-30 19:41:25 +0000381 } else
Chris Lattner95294b82011-01-14 19:36:13 +0000382 // Otherwise it is a load, queue it to rewrite as a live-in load.
383 LiveInLoads.push_back(cast<LoadInst>(User));
384 BlockUses.clear();
385 continue;
386 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000387
Chris Lattner95294b82011-01-14 19:36:13 +0000388 // Otherwise, check to see if this block is all loads.
389 bool HasStore = false;
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000390 for (Instruction *I : BlockUses) {
391 if (isa<StoreInst>(I)) {
Chris Lattner95294b82011-01-14 19:36:13 +0000392 HasStore = true;
393 break;
394 }
395 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000396
Chris Lattner95294b82011-01-14 19:36:13 +0000397 // If so, we can queue them all as live in loads. We don't have an
398 // efficient way to tell which on is first in the block and don't want to
399 // scan large blocks, so just add all loads as live ins.
400 if (!HasStore) {
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000401 for (Instruction *I : BlockUses)
402 LiveInLoads.push_back(cast<LoadInst>(I));
Chris Lattner95294b82011-01-14 19:36:13 +0000403 BlockUses.clear();
404 continue;
405 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000406
Chris Lattner95294b82011-01-14 19:36:13 +0000407 // Otherwise, we have mixed loads and stores (or just a bunch of stores).
408 // Since SSAUpdater is purely for cross-block values, we need to determine
409 // the order of these instructions in the block. If the first use in the
410 // block is a load, then it uses the live in value. The last store defines
411 // the live out value. We handle this by doing a linear scan of the block.
Craig Topperf40110f2014-04-25 05:29:35 +0000412 Value *StoredValue = nullptr;
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000413 for (Instruction &I : *BB) {
414 if (LoadInst *L = dyn_cast<LoadInst>(&I)) {
Chris Lattner95294b82011-01-14 19:36:13 +0000415 // If this is a load from an unrelated pointer, ignore it.
416 if (!isInstInList(L, Insts)) continue;
Fangrui Songf78650a2018-07-30 19:41:25 +0000417
Chris Lattner95294b82011-01-14 19:36:13 +0000418 // If we haven't seen a store yet, this is a live in use, otherwise
419 // use the stored value.
420 if (StoredValue) {
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000421 replaceLoadWithValue(L, StoredValue);
Chris Lattner95294b82011-01-14 19:36:13 +0000422 L->replaceAllUsesWith(StoredValue);
423 ReplacedLoads[L] = StoredValue;
424 } else {
425 LiveInLoads.push_back(L);
426 }
427 continue;
428 }
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000429
430 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
Chris Lattner95294b82011-01-14 19:36:13 +0000431 // If this is a store to an unrelated pointer, ignore it.
Cameron Zwarich843bc7d2011-05-24 03:10:43 +0000432 if (!isInstInList(SI, Insts)) continue;
Devang Patela3cbf522011-07-06 21:09:55 +0000433 updateDebugInfo(SI);
Cameron Zwarich843bc7d2011-05-24 03:10:43 +0000434
Chris Lattner95294b82011-01-14 19:36:13 +0000435 // Remember that this is the active value in the block.
Cameron Zwarich843bc7d2011-05-24 03:10:43 +0000436 StoredValue = SI->getOperand(0);
Chris Lattner95294b82011-01-14 19:36:13 +0000437 }
438 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000439
Chris Lattner95294b82011-01-14 19:36:13 +0000440 // The last stored value that happened is the live-out for the block.
441 assert(StoredValue && "Already checked that there is a store in block");
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000442 SSA.AddAvailableValue(BB, StoredValue);
Chris Lattner95294b82011-01-14 19:36:13 +0000443 BlockUses.clear();
444 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000445
Chris Lattner95294b82011-01-14 19:36:13 +0000446 // Okay, now we rewrite all loads that use live-in values in the loop,
447 // inserting PHI nodes as necessary.
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000448 for (LoadInst *ALoad : LiveInLoads) {
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000449 Value *NewVal = SSA.GetValueInMiddleOfBlock(ALoad->getParent());
450 replaceLoadWithValue(ALoad, NewVal);
Chris Lattnerb4017762011-01-24 03:29:07 +0000451
452 // Avoid assertions in unreachable code.
453 if (NewVal == ALoad) NewVal = UndefValue::get(NewVal->getType());
Chris Lattner95294b82011-01-14 19:36:13 +0000454 ALoad->replaceAllUsesWith(NewVal);
455 ReplacedLoads[ALoad] = NewVal;
456 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000457
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000458 // Allow the client to do stuff before we start nuking things.
459 doExtraRewritesBeforeFinalDeletion();
Fangrui Songf78650a2018-07-30 19:41:25 +0000460
Chris Lattner95294b82011-01-14 19:36:13 +0000461 // Now that everything is rewritten, delete the old instructions from the
462 // function. They should all be dead now.
Benjamin Kramerdfedfeb2015-02-19 20:04:02 +0000463 for (Instruction *User : Insts) {
Chris Lattner95294b82011-01-14 19:36:13 +0000464 // If this is a load that still has uses, then the load must have been added
465 // as a live value in the SSAUpdate data structure for a block (e.g. because
466 // the loaded value was stored later). In this case, we need to recursively
467 // propagate the updates until we get to the real value.
468 if (!User->use_empty()) {
469 Value *NewVal = ReplacedLoads[User];
470 assert(NewVal && "not a replaced load?");
Fangrui Songf78650a2018-07-30 19:41:25 +0000471
Chris Lattner95294b82011-01-14 19:36:13 +0000472 // Propagate down to the ultimate replacee. The intermediately loads
473 // could theoretically already have been deleted, so we don't want to
474 // dereference the Value*'s.
475 DenseMap<Value*, Value*>::iterator RLI = ReplacedLoads.find(NewVal);
476 while (RLI != ReplacedLoads.end()) {
477 NewVal = RLI->second;
478 RLI = ReplacedLoads.find(NewVal);
479 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000480
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000481 replaceLoadWithValue(cast<LoadInst>(User), NewVal);
Chris Lattner95294b82011-01-14 19:36:13 +0000482 User->replaceAllUsesWith(NewVal);
483 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000484
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000485 instructionDeleted(User);
Chris Lattner95294b82011-01-14 19:36:13 +0000486 User->eraseFromParent();
487 }
488}
Benjamin Kramerd00e94e2011-11-14 17:22:45 +0000489
490bool
491LoadAndStorePromoter::isInstInList(Instruction *I,
Eugene Zelenko286d5892017-10-11 21:41:43 +0000492 const SmallVectorImpl<Instruction *> &Insts)
Benjamin Kramerd00e94e2011-11-14 17:22:45 +0000493 const {
David Majnemer0d955d02016-08-11 22:21:41 +0000494 return is_contained(Insts, I);
Benjamin Kramerd00e94e2011-11-14 17:22:45 +0000495}