1 //===- PromoteMemoryToRegister.cpp - Convert memory refs to regs ----------===//
3 // This file is used to promote memory references to be register references. A
4 // simple example of the transformation performed by this function is:
7 // %X = alloca int, uint 1 ret int 42
8 // store int 42, int *%X
12 // The code is transformed by looping over all of the alloca instruction,
13 // calculating dominator frontiers, then inserting phi-nodes following the usual
14 // SSA construction algorithm. This code does not modify the CFG of the
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
20 #include "llvm/Analysis/Dominators.h"
21 #include "llvm/iMemory.h"
22 #include "llvm/iPHINode.h"
23 #include "llvm/iTerminators.h"
24 #include "llvm/Function.h"
25 #include "llvm/Constant.h"
26 #include "llvm/Type.h"
27 #include "llvm/Support/CFG.h"
28 #include "Support/StringExtras.h"
30 /// isAllocaPromotable - Return true if this alloca is legal for promotion.
31 /// This is true if there are only loads and stores to the alloca...
33 bool isAllocaPromotable(const AllocaInst *AI, const TargetData &TD) {
34 // FIXME: If the memory unit is of pointer or integer type, we can permit
35 // assignments to subsections of the memory unit.
37 // Only allow direct loads and stores...
38 for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end();
39 UI != UE; ++UI) // Loop over all of the uses of the alloca
40 if (!isa<LoadInst>(*UI))
41 if (const StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
42 if (SI->getOperand(0) == AI)
43 return false; // Don't allow a store of the AI, only INTO the AI.
45 return false; // Not a load or store?
53 struct PromoteMem2Reg {
54 // Allocas - The alloca instructions being promoted
55 const std::vector<AllocaInst*> &Allocas;
56 DominanceFrontier &DF;
59 // AllocaLookup - Reverse mapping of Allocas
60 std::map<AllocaInst*, unsigned> AllocaLookup;
62 // VersionNumbers - Current version counters for each alloca
63 std::vector<unsigned> VersionNumbers;
65 // NewPhiNodes - The PhiNodes we're adding.
66 std::map<BasicBlock*, std::vector<PHINode*> > NewPhiNodes;
68 // Visited - The set of basic blocks the renamer has already visited.
69 std::set<BasicBlock*> Visited;
72 PromoteMem2Reg(const std::vector<AllocaInst*> &A, DominanceFrontier &df,
73 const TargetData &td) : Allocas(A), DF(df), TD(td) {}
78 void RenamePass(BasicBlock *BB, BasicBlock *Pred,
79 std::vector<Value*> &IncVals);
80 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx);
82 } // end of anonymous namespace
85 void PromoteMem2Reg::run() {
86 Function &F = *DF.getRoot()->getParent();
88 VersionNumbers.resize(Allocas.size());
90 for (unsigned i = 0; i != Allocas.size(); ++i) {
91 AllocaInst *AI = Allocas[i];
93 assert(isAllocaPromotable(AI, TD) &&
94 "Cannot promote non-promotable alloca!");
95 assert(Allocas[i]->getParent()->getParent() == &F &&
96 "All allocas should be in the same function, which is same as DF!");
98 // Calculate the set of write-locations for each alloca. This is analogous
99 // to counting the number of 'redefinitions' of each variable.
100 std::vector<BasicBlock*> WriteSets;
101 for (Value::use_iterator U =AI->use_begin(), E = AI->use_end(); U != E; ++U)
102 if (StoreInst *SI = dyn_cast<StoreInst>(cast<Instruction>(*U)))
103 // jot down the basic-block it came from
104 WriteSets.push_back(SI->getParent());
106 AllocaLookup[Allocas[i]] = i;
108 // PhiNodeBlocks - A list of blocks that phi nodes have been inserted for
110 std::vector<BasicBlock*> PhiNodeBlocks;
112 // Compute the locations where PhiNodes need to be inserted. Look at the
113 // dominance frontier of EACH basic-block we have a write in.
115 for (unsigned j = 0; j != WriteSets.size(); j++) {
116 // Look up the DF for this write, add it to PhiNodes
117 DominanceFrontier::const_iterator it = DF.find(WriteSets[j]);
118 if (it != DF.end()) {
119 const DominanceFrontier::DomSetType &S = it->second;
120 for (DominanceFrontier::DomSetType::iterator P = S.begin(),PE = S.end();
122 if (QueuePhiNode(*P, i))
123 PhiNodeBlocks.push_back(*P);
127 // Perform iterative step
128 for (unsigned k = 0; k != PhiNodeBlocks.size(); k++) {
129 DominanceFrontier::const_iterator it = DF.find(PhiNodeBlocks[k]);
130 if (it != DF.end()) {
131 const DominanceFrontier::DomSetType &S = it->second;
132 for (DominanceFrontier::DomSetType::iterator
133 P = S.begin(), PE = S.end(); P != PE; ++P)
134 if (QueuePhiNode(*P, i))
135 PhiNodeBlocks.push_back(*P);
140 // Set the incoming values for the basic block to be null values for all of
141 // the alloca's. We do this in case there is a load of a value that has not
142 // been stored yet. In this case, it will get this null value.
144 std::vector<Value *> Values(Allocas.size());
145 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
146 Values[i] = Constant::getNullValue(Allocas[i]->getAllocatedType());
148 // Walks all basic blocks in the function performing the SSA rename algorithm
149 // and inserting the phi nodes we marked as necessary
151 RenamePass(F.begin(), 0, Values);
154 // Remove the allocas themselves from the function...
155 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
156 Instruction *A = Allocas[i];
158 // If there are any uses of the alloca instructions left, they must be in
159 // sections of dead code that were not processed on the dominance frontier.
160 // Just delete the users now.
163 A->replaceAllUsesWith(Constant::getNullValue(A->getType()));
164 A->getParent()->getInstList().erase(A);
169 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
170 // Alloca returns true if there wasn't already a phi-node for that variable
172 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo) {
173 // Look up the basic-block in question
174 std::vector<PHINode*> &BBPNs = NewPhiNodes[BB];
175 if (BBPNs.empty()) BBPNs.resize(Allocas.size());
177 // If the BB already has a phi node added for the i'th alloca then we're done!
178 if (BBPNs[AllocaNo]) return false;
180 // Create a PhiNode using the dereferenced type... and add the phi-node to the
182 PHINode *PN = new PHINode(Allocas[AllocaNo]->getAllocatedType(),
183 Allocas[AllocaNo]->getName() + "." +
184 utostr(VersionNumbers[AllocaNo]++),
187 // Add null incoming values for all predecessors. This ensures that if one of
188 // the predecessors is not found in the depth-first traversal of the CFG (ie,
189 // because it is an unreachable predecessor), that all PHI nodes will have the
190 // correct number of entries for their predecessors.
191 Value *NullVal = Constant::getNullValue(PN->getType());
193 // This is necessary because adding incoming values to the PHI node adds uses
194 // to the basic blocks being used, which can invalidate the predecessor
196 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
197 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
198 PN->addIncoming(NullVal, Preds[i]);
200 BBPNs[AllocaNo] = PN;
204 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
205 std::vector<Value*> &IncomingVals) {
206 // If this BB needs a PHI node, update the PHI node for each variable we need
208 std::map<BasicBlock*, std::vector<PHINode *> >::iterator
209 BBPNI = NewPhiNodes.find(BB);
210 if (BBPNI != NewPhiNodes.end()) {
211 std::vector<PHINode *> &BBPNs = BBPNI->second;
212 for (unsigned k = 0; k != BBPNs.size(); ++k)
213 if (PHINode *PN = BBPNs[k]) {
214 // The PHI node may have multiple entries for this predecessor. We must
215 // make sure we update all of them.
216 for (unsigned i = 0, e = PN->getNumOperands(); i != e; i += 2) {
217 if (PN->getOperand(i+1) == Pred)
218 // At this point we can assume that the array has phi nodes.. let's
219 // update the incoming data.
220 PN->setOperand(i, IncomingVals[k]);
222 // also note that the active variable IS designated by the phi node
223 IncomingVals[k] = PN;
227 // don't revisit nodes
228 if (Visited.count(BB)) return;
233 BasicBlock::iterator II = BB->begin();
235 Instruction *I = II++; // get the instruction, increment iterator
237 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
238 if (AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand())) {
239 std::map<AllocaInst*, unsigned>::iterator AI = AllocaLookup.find(Src);
240 if (AI != AllocaLookup.end()) {
241 Value *V = IncomingVals[AI->second];
243 // walk the use list of this load and replace all uses with r
244 LI->replaceAllUsesWith(V);
245 BB->getInstList().erase(LI);
248 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
249 // Delete this instruction and mark the name as the current holder of the
251 if (AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand())) {
252 std::map<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
253 if (ai != AllocaLookup.end()) {
254 // what value were we writing?
255 IncomingVals[ai->second] = SI->getOperand(0);
256 BB->getInstList().erase(SI);
260 } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(I)) {
261 // Recurse across our successors
262 for (unsigned i = 0; i != TI->getNumSuccessors(); i++) {
263 std::vector<Value*> OutgoingVals(IncomingVals);
264 RenamePass(TI->getSuccessor(i), BB, OutgoingVals);
271 /// PromoteMemToReg - Promote the specified list of alloca instructions into
272 /// scalar registers, inserting PHI nodes as appropriate. This function makes
273 /// use of DominanceFrontier information. This function does not modify the CFG
274 /// of the function at all. All allocas must be from the same function.
276 void PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
277 DominanceFrontier &DF, const TargetData &TD) {
278 // If there is nothing to do, bail out...
279 if (Allocas.empty()) return;
280 PromoteMem2Reg(Allocas, DF, TD).run();