1 //===- SSAUpdater.cpp - Unstructured SSA Update Tool ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the SSAUpdater class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "ssaupdater"
15 #include "llvm/Instructions.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/Support/AlignOf.h"
19 #include "llvm/Support/Allocator.h"
20 #include "llvm/Support/CFG.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Transforms/Utils/SSAUpdater.h"
24 #include "llvm/Transforms/Utils/SSAUpdaterImpl.h"
27 typedef DenseMap<BasicBlock*, Value*> AvailableValsTy;
28 static AvailableValsTy &getAvailableVals(void *AV) {
29 return *static_cast<AvailableValsTy*>(AV);
32 SSAUpdater::SSAUpdater(SmallVectorImpl<PHINode*> *NewPHI)
33 : AV(0), ProtoType(0), ProtoName(), InsertedPHIs(NewPHI) {}
35 SSAUpdater::~SSAUpdater() {
36 delete &getAvailableVals(AV);
39 /// Initialize - Reset this object to get ready for a new set of SSA
40 /// updates with type 'Ty'. PHI nodes get a name based on 'Name'.
41 void SSAUpdater::Initialize(const Type *Ty, StringRef Name) {
43 AV = new AvailableValsTy();
45 getAvailableVals(AV).clear();
50 /// HasValueForBlock - Return true if the SSAUpdater already has a value for
51 /// the specified block.
52 bool SSAUpdater::HasValueForBlock(BasicBlock *BB) const {
53 return getAvailableVals(AV).count(BB);
56 /// AddAvailableValue - Indicate that a rewritten value is available in the
57 /// specified block with the specified value.
58 void SSAUpdater::AddAvailableValue(BasicBlock *BB, Value *V) {
59 assert(ProtoType != 0 && "Need to initialize SSAUpdater");
60 assert(ProtoType == V->getType() &&
61 "All rewritten values must have the same type");
62 getAvailableVals(AV)[BB] = V;
65 /// IsEquivalentPHI - Check if PHI has the same incoming value as specified
66 /// in ValueMapping for each predecessor block.
67 static bool IsEquivalentPHI(PHINode *PHI,
68 DenseMap<BasicBlock*, Value*> &ValueMapping) {
69 unsigned PHINumValues = PHI->getNumIncomingValues();
70 if (PHINumValues != ValueMapping.size())
73 // Scan the phi to see if it matches.
74 for (unsigned i = 0, e = PHINumValues; i != e; ++i)
75 if (ValueMapping[PHI->getIncomingBlock(i)] !=
76 PHI->getIncomingValue(i)) {
83 /// GetValueAtEndOfBlock - Construct SSA form, materializing a value that is
84 /// live at the end of the specified block.
85 Value *SSAUpdater::GetValueAtEndOfBlock(BasicBlock *BB) {
86 Value *Res = GetValueAtEndOfBlockInternal(BB);
90 /// GetValueInMiddleOfBlock - Construct SSA form, materializing a value that
91 /// is live in the middle of the specified block.
93 /// GetValueInMiddleOfBlock is the same as GetValueAtEndOfBlock except in one
94 /// important case: if there is a definition of the rewritten value after the
95 /// 'use' in BB. Consider code like this:
101 /// br Cond, SomeBB, OutBB
103 /// In this case, there are two values (X1 and X2) added to the AvailableVals
104 /// set by the client of the rewriter, and those values are both live out of
105 /// their respective blocks. However, the use of X happens in the *middle* of
106 /// a block. Because of this, we need to insert a new PHI node in SomeBB to
107 /// merge the appropriate values, and this value isn't live out of the block.
109 Value *SSAUpdater::GetValueInMiddleOfBlock(BasicBlock *BB) {
110 // If there is no definition of the renamed variable in this block, just use
111 // GetValueAtEndOfBlock to do our work.
112 if (!HasValueForBlock(BB))
113 return GetValueAtEndOfBlock(BB);
115 // Otherwise, we have the hard case. Get the live-in values for each
117 SmallVector<std::pair<BasicBlock*, Value*>, 8> PredValues;
118 Value *SingularValue = 0;
120 // We can get our predecessor info by walking the pred_iterator list, but it
121 // is relatively slow. If we already have PHI nodes in this block, walk one
122 // of them to get the predecessor list instead.
123 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
124 for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) {
125 BasicBlock *PredBB = SomePhi->getIncomingBlock(i);
126 Value *PredVal = GetValueAtEndOfBlock(PredBB);
127 PredValues.push_back(std::make_pair(PredBB, PredVal));
129 // Compute SingularValue.
131 SingularValue = PredVal;
132 else if (PredVal != SingularValue)
136 bool isFirstPred = true;
137 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
138 BasicBlock *PredBB = *PI;
139 Value *PredVal = GetValueAtEndOfBlock(PredBB);
140 PredValues.push_back(std::make_pair(PredBB, PredVal));
142 // Compute SingularValue.
144 SingularValue = PredVal;
146 } else if (PredVal != SingularValue)
151 // If there are no predecessors, just return undef.
152 if (PredValues.empty())
153 return UndefValue::get(ProtoType);
155 // Otherwise, if all the merged values are the same, just use it.
156 if (SingularValue != 0)
157 return SingularValue;
159 // Otherwise, we do need a PHI: check to see if we already have one available
160 // in this block that produces the right value.
161 if (isa<PHINode>(BB->begin())) {
162 DenseMap<BasicBlock*, Value*> ValueMapping(PredValues.begin(),
165 for (BasicBlock::iterator It = BB->begin();
166 (SomePHI = dyn_cast<PHINode>(It)); ++It) {
167 if (IsEquivalentPHI(SomePHI, ValueMapping))
172 // Ok, we have no way out, insert a new one now.
173 PHINode *InsertedPHI = PHINode::Create(ProtoType, ProtoName, &BB->front());
174 InsertedPHI->reserveOperandSpace(PredValues.size());
176 // Fill in all the predecessors of the PHI.
177 for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
178 InsertedPHI->addIncoming(PredValues[i].second, PredValues[i].first);
180 // See if the PHI node can be merged to a single value. This can happen in
181 // loop cases when we get a PHI of itself and one other value.
182 if (Value *V = SimplifyInstruction(InsertedPHI)) {
183 InsertedPHI->eraseFromParent();
187 // If the client wants to know about all new instructions, tell it.
188 if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);
190 DEBUG(dbgs() << " Inserted PHI: " << *InsertedPHI << "\n");
194 /// RewriteUse - Rewrite a use of the symbolic value. This handles PHI nodes,
195 /// which use their value in the corresponding predecessor.
196 void SSAUpdater::RewriteUse(Use &U) {
197 Instruction *User = cast<Instruction>(U.getUser());
200 if (PHINode *UserPN = dyn_cast<PHINode>(User))
201 V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
203 V = GetValueInMiddleOfBlock(User->getParent());
208 /// RewriteUseAfterInsertions - Rewrite a use, just like RewriteUse. However,
209 /// this version of the method can rewrite uses in the same block as a
210 /// definition, because it assumes that all uses of a value are below any
212 void SSAUpdater::RewriteUseAfterInsertions(Use &U) {
213 Instruction *User = cast<Instruction>(U.getUser());
216 if (PHINode *UserPN = dyn_cast<PHINode>(User))
217 V = GetValueAtEndOfBlock(UserPN->getIncomingBlock(U));
219 V = GetValueAtEndOfBlock(User->getParent());
224 /// PHIiter - Iterator for PHI operands. This is used for the PHI_iterator
225 /// in the SSAUpdaterImpl template.
233 explicit PHIiter(PHINode *P) // begin iterator
235 PHIiter(PHINode *P, bool) // end iterator
236 : PHI(P), idx(PHI->getNumIncomingValues()) {}
238 PHIiter &operator++() { ++idx; return *this; }
239 bool operator==(const PHIiter& x) const { return idx == x.idx; }
240 bool operator!=(const PHIiter& x) const { return !operator==(x); }
241 Value *getIncomingValue() { return PHI->getIncomingValue(idx); }
242 BasicBlock *getIncomingBlock() { return PHI->getIncomingBlock(idx); }
246 /// SSAUpdaterTraits<SSAUpdater> - Traits for the SSAUpdaterImpl template,
247 /// specialized for SSAUpdater.
250 class SSAUpdaterTraits<SSAUpdater> {
252 typedef BasicBlock BlkT;
254 typedef PHINode PhiT;
256 typedef succ_iterator BlkSucc_iterator;
257 static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return succ_begin(BB); }
258 static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return succ_end(BB); }
260 typedef PHIiter PHI_iterator;
261 static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); }
262 static inline PHI_iterator PHI_end(PhiT *PHI) {
263 return PHI_iterator(PHI, true);
266 /// FindPredecessorBlocks - Put the predecessors of Info->BB into the Preds
267 /// vector, set Info->NumPreds, and allocate space in Info->Preds.
268 static void FindPredecessorBlocks(BasicBlock *BB,
269 SmallVectorImpl<BasicBlock*> *Preds) {
270 // We can get our predecessor info by walking the pred_iterator list,
271 // but it is relatively slow. If we already have PHI nodes in this
272 // block, walk one of them to get the predecessor list instead.
273 if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
274 for (unsigned PI = 0, E = SomePhi->getNumIncomingValues(); PI != E; ++PI)
275 Preds->push_back(SomePhi->getIncomingBlock(PI));
277 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
278 Preds->push_back(*PI);
282 /// GetUndefVal - Get an undefined value of the same type as the value
284 static Value *GetUndefVal(BasicBlock *BB, SSAUpdater *Updater) {
285 return UndefValue::get(Updater->ProtoType);
288 /// CreateEmptyPHI - Create a new PHI instruction in the specified block.
289 /// Reserve space for the operands but do not fill them in yet.
290 static Value *CreateEmptyPHI(BasicBlock *BB, unsigned NumPreds,
291 SSAUpdater *Updater) {
292 PHINode *PHI = PHINode::Create(Updater->ProtoType, Updater->ProtoName,
294 PHI->reserveOperandSpace(NumPreds);
298 /// AddPHIOperand - Add the specified value as an operand of the PHI for
299 /// the specified predecessor block.
300 static void AddPHIOperand(PHINode *PHI, Value *Val, BasicBlock *Pred) {
301 PHI->addIncoming(Val, Pred);
304 /// InstrIsPHI - Check if an instruction is a PHI.
306 static PHINode *InstrIsPHI(Instruction *I) {
307 return dyn_cast<PHINode>(I);
310 /// ValueIsPHI - Check if a value is a PHI.
312 static PHINode *ValueIsPHI(Value *Val, SSAUpdater *Updater) {
313 return dyn_cast<PHINode>(Val);
316 /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source
317 /// operands, i.e., it was just added.
318 static PHINode *ValueIsNewPHI(Value *Val, SSAUpdater *Updater) {
319 PHINode *PHI = ValueIsPHI(Val, Updater);
320 if (PHI && PHI->getNumIncomingValues() == 0)
325 /// GetPHIValue - For the specified PHI instruction, return the value
327 static Value *GetPHIValue(PHINode *PHI) {
332 } // End llvm namespace
334 /// GetValueAtEndOfBlockInternal - Check to see if AvailableVals has an entry
335 /// for the specified BB and if so, return it. If not, construct SSA form by
336 /// first calculating the required placement of PHIs and then inserting new
337 /// PHIs where needed.
338 Value *SSAUpdater::GetValueAtEndOfBlockInternal(BasicBlock *BB) {
339 AvailableValsTy &AvailableVals = getAvailableVals(AV);
340 if (Value *V = AvailableVals[BB])
343 SSAUpdaterImpl<SSAUpdater> Impl(this, &AvailableVals, InsertedPHIs);
344 return Impl.GetValue(BB);