1 //===- PromoteMemoryToRegister.cpp - Convert memory refs to regs ----------===//
3 // This pass is used to promote memory references to be register references. A
4 // simple example of the transformation performed by this pass is:
7 // %X = alloca int, uint 1 ret int 42
8 // store int 42, int *%X
12 // To do this transformation, a simple analysis is done to ensure it is safe.
13 // Currently this just loops over all alloca instructions, looking for
14 // instructions that are only used in simple load and stores.
16 // After this, the code is transformed by...something magical :)
18 //===----------------------------------------------------------------------===//
20 #include "llvm/Transforms/Scalar/PromoteMemoryToRegister.h"
21 #include "llvm/Analysis/Dominators.h"
22 #include "llvm/iMemory.h"
23 #include "llvm/iPHINode.h"
24 #include "llvm/iTerminators.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Function.h"
27 #include "llvm/BasicBlock.h"
28 #include "llvm/ConstantVals.h"
34 //instance of the promoter -- to keep all the local function data.
35 // gets re-created for each function processed
39 vector<AllocaInst*> Allocas; // the alloca instruction..
40 map<Instruction *, int> AllocaLookup; //reverse mapping of above
42 vector<vector<BasicBlock *> > WriteSets; // index corresponds to Allocas
43 vector<vector<BasicBlock *> > PhiNodes; // index corresponds to Allocas
44 vector<vector<Value *> > CurrentValue; //the current value stack
46 //list of instructions to remove at end of pass :)
47 vector<Instruction *> killlist;
49 set<BasicBlock *> visited; //the basic blocks we've already visited
50 map<BasicBlock *, vector<PHINode *> > new_phinodes; //the phinodes we're adding
53 void traverse(BasicBlock *f, BasicBlock * predecessor);
54 bool PromoteFunction(Function *F, DominanceFrontier &DF);
55 bool queuePhiNode(BasicBlock *bb, int alloca_index);
56 void findSafeAllocas(Function *M);
59 // I do this so that I can force the deconstruction of the local variables
60 PromoteInstance(Function *F, DominanceFrontier &DF)
62 didchange=PromoteFunction(F, DF);
64 //This returns whether the pass changes anything
65 operator bool () { return didchange; }
68 } // end of anonymous namespace
70 // findSafeAllocas - Find allocas that are safe to promote
72 void PromoteInstance::findSafeAllocas(Function *F)
74 BasicBlock *BB = F->getEntryNode(); // Get the entry node for the function
76 // Look at all instructions in the entry node
77 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
78 if (AllocaInst *AI = dyn_cast<AllocaInst>(*I)) // Is it an alloca?
79 if (!AI->isArrayAllocation()) {
81 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
82 UI != UE; ++UI) { // Loop over all of the uses of the alloca
84 // Only allow nonindexed memory access instructions...
85 if (MemAccessInst *MAI = dyn_cast<MemAccessInst>(*UI)) {
86 if (MAI->hasIndices()) { // indexed?
87 // Allow the access if there is only one index and the index is zero.
88 if (*MAI->idx_begin() != ConstantUInt::get(Type::UIntTy, 0) ||
89 MAI->idx_begin()+1 != MAI->idx_end()) {
90 isSafe = false; break;
94 isSafe = false; break; // Not a load or store?
97 if (isSafe) // If all checks pass, add alloca to safe list
99 AllocaLookup[AI]=Allocas.size();
100 Allocas.push_back(AI);
107 bool PromoteInstance::PromoteFunction(Function *F, DominanceFrontier & DF) {
108 // Calculate the set of safe allocas
111 // Add each alloca to the killlist
112 // note: killlist is destroyed MOST recently added to least recently.
113 killlist.assign(Allocas.begin(), Allocas.end());
115 // Calculate the set of write-locations for each alloca.
116 // this is analogous to counting the number of 'redefinitions' of each variable.
117 for (unsigned i = 0; i<Allocas.size(); ++i)
119 AllocaInst * AI = Allocas[i];
120 WriteSets.push_back(std::vector<BasicBlock *>()); //add a new set
121 for (Value::use_iterator U = AI->use_begin();U!=AI->use_end();++U)
123 if (MemAccessInst *MAI = dyn_cast<StoreInst>(*U)) {
124 WriteSets[i].push_back(MAI->getParent()); // jot down the basic-block it came from
129 // Compute the locations where PhiNodes need to be inserted
130 // look at the dominance frontier of EACH basic-block we have a write in
131 PhiNodes.resize(Allocas.size());
132 for (unsigned i = 0; i<Allocas.size(); ++i)
134 for (unsigned j = 0; j<WriteSets[i].size(); j++)
136 //look up the DF for this write, add it to PhiNodes
137 DominanceFrontier::const_iterator it = DF.find(WriteSets[i][j]);
138 DominanceFrontier::DomSetType s = (*it).second;
139 for (DominanceFrontier::DomSetType::iterator p = s.begin();p!=s.end(); ++p)
141 if (queuePhiNode(*p, i))
142 PhiNodes[i].push_back(*p);
145 // perform iterative step
146 for (unsigned k = 0; k<PhiNodes[i].size(); k++)
148 DominanceFrontier::const_iterator it = DF.find(PhiNodes[i][k]);
149 DominanceFrontier::DomSetType s = it->second;
150 for (DominanceFrontier::DomSetType::iterator p = s.begin(); p!=s.end(); ++p)
152 if (queuePhiNode(*p,i))
153 PhiNodes[i].push_back(*p);
158 // Walks all basic blocks in the function
159 // performing the SSA rename algorithm
160 // and inserting the phi nodes we marked as necessary
161 BasicBlock * f = F->front(); //get root basic-block
163 CurrentValue.push_back(vector<Value *>(Allocas.size()));
165 traverse(f, NULL); // there is no predecessor of the root node
168 // ** REMOVE EVERYTHING IN THE KILL-LIST **
169 // we need to kill 'uses' before root values
170 // so we should probably run through in reverse
171 for (vector<Instruction *>::reverse_iterator i = killlist.rbegin(); i!=killlist.rend(); ++i)
173 Instruction * r = *i;
174 BasicBlock * o = r->getParent();
177 BasicBlock::InstListType & l = o->getInstList();
178 o->getInstList().remove(r);
182 return !Allocas.empty();
187 void PromoteInstance::traverse(BasicBlock *f, BasicBlock * predecessor)
189 vector<Value *> * tos = &CurrentValue.back(); //look at top-
191 //if this is a BB needing a phi node, lookup/create the phinode for
192 // each variable we need phinodes for.
193 map<BasicBlock *, vector<PHINode *> >::iterator nd = new_phinodes.find(f);
194 if (nd!=new_phinodes.end())
196 for (unsigned k = 0; k!=nd->second.size(); ++k)
199 //at this point we can assume that the array has phi nodes.. let's
200 // add the incoming data
202 nd->second[k]->addIncoming((*tos)[k],predecessor);
203 //also note that the active variable IS designated by the phi node
204 (*tos)[k] = nd->second[k];
208 //don't revisit nodes
209 if (visited.find(f)!=visited.end())
214 BasicBlock::iterator i = f->begin();
215 //keep track of the value of each variable we're watching.. how?
218 Instruction * inst = *i; //get the instruction
219 //is this a write/read?
220 if (LoadInst * LI = dyn_cast<LoadInst>(inst))
222 // This is a bit weird...
223 Value * ptr = LI->getPointerOperand(); //of type value
224 if (AllocaInst * srcinstr = dyn_cast<AllocaInst>(ptr))
226 map<Instruction *, int>::iterator ai = AllocaLookup.find(srcinstr);
227 if (ai!=AllocaLookup.end())
229 if (Value *r = (*tos)[ai->second])
231 //walk the use list of this load and replace
233 LI->replaceAllUsesWith(r);
234 //now delete the instruction.. somehow..
235 killlist.push_back((Instruction *)LI);
240 else if (StoreInst * SI = dyn_cast<StoreInst>(inst))
242 // delete this instruction and mark the name as the
243 // current holder of the value
244 Value * ptr = SI->getPointerOperand(); //of type value
245 if (Instruction * srcinstr = dyn_cast<Instruction>(ptr))
247 map<Instruction *, int>::iterator ai = AllocaLookup.find(srcinstr);
248 if (ai!=AllocaLookup.end())
250 //what value were we writing?
251 Value * writeval = SI->getOperand(0);
253 (*tos)[ai->second] = writeval;
254 //now delete it.. somehow?
255 killlist.push_back((Instruction *)SI);
260 else if (TerminatorInst * TI = dyn_cast<TerminatorInst>(inst))
262 // Recurse across our sucessors
263 for (unsigned i = 0; i!=TI->getNumSuccessors(); i++)
265 CurrentValue.push_back(CurrentValue.back());
266 traverse(TI->getSuccessor(i),f); //this node IS the predecessor
267 CurrentValue.pop_back();
274 // queues a phi-node to be added to a basic-block for a specific Alloca
275 // returns true if there wasn't already a phi-node for that variable
278 bool PromoteInstance::queuePhiNode(BasicBlock *bb, int i /*the alloca*/)
280 map<BasicBlock *, vector<PHINode *> >::iterator nd;
281 //look up the basic-block in question
282 nd = new_phinodes.find(bb);
283 //if the basic-block has no phi-nodes added, or at least none
284 //for the i'th alloca. then add.
285 if (nd==new_phinodes.end() || nd->second[i]==NULL)
287 //we're not added any phi nodes to this basicblock yet
288 // create the phi-node array.
289 if (nd==new_phinodes.end())
291 new_phinodes[bb] = vector<PHINode *>(Allocas.size());
292 nd = new_phinodes.find(bb);
295 //find the type the alloca returns
296 const PointerType * pt = Allocas[i]->getType();
297 //create a phi-node using the DEREFERENCED type
298 PHINode * ph = new PHINode(pt->getElementType(), Allocas[i]->getName()+".mem2reg");
300 //add the phi-node to the basic-block
301 bb->getInstList().push_front(ph);
309 struct PromotePass : public FunctionPass {
311 // runOnFunction - To run this pass, first we calculate the alloca
312 // instructions that are safe for promotion, then we promote each one.
314 virtual bool runOnFunction(Function *F) {
315 return (bool)PromoteInstance(F, getAnalysis<DominanceFrontier>());
319 // getAnalysisUsage - We need dominance frontiers
321 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
322 AU.addRequired(DominanceFrontier::ID);
328 // createPromoteMemoryToRegister - Provide an entry point to create this pass.
330 Pass *createPromoteMemoryToRegister() {
331 return new PromotePass();