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.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/Function.h"
26 #include "llvm/BasicBlock.h"
27 #include "llvm/Constant.h"
28 #include "llvm/Type.h"
29 #include "Support/StatisticReporter.h"
31 static Statistic<> NumPromoted("mem2reg\t\t- Number of alloca's promoted");
38 struct PromotePass : public FunctionPass {
39 vector<AllocaInst*> Allocas; // the alloca instruction..
40 map<Instruction*, unsigned> AllocaLookup; // reverse mapping of above
42 vector<vector<BasicBlock*> > PhiNodes; // index corresponds to Allocas
44 // List of instructions to remove at end of pass
45 vector<Instruction *> KillList;
47 map<BasicBlock*,vector<PHINode*> > NewPhiNodes; // the PhiNodes we're adding
50 // runOnFunction - To run this pass, first we calculate the alloca
51 // instructions that are safe for promotion, then we promote each one.
53 virtual bool runOnFunction(Function &F);
55 // getAnalysisUsage - We need dominance frontiers
57 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
58 AU.addRequired<DominanceFrontier>();
63 void Traverse(BasicBlock *BB, BasicBlock *Pred, vector<Value*> &IncVals,
64 set<BasicBlock*> &Visited);
65 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx);
66 void FindSafeAllocas(Function &F);
69 RegisterOpt<PromotePass> X("mem2reg", "Promote Memory to Register");
70 } // end of anonymous namespace
73 // isSafeAlloca - This predicate controls what types of alloca instructions are
74 // allowed to be promoted...
76 static inline bool isSafeAlloca(const AllocaInst *AI) {
77 if (AI->isArrayAllocation()) return false;
79 // Only allow direct loads and stores...
80 for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end();
81 UI != UE; ++UI) // Loop over all of the uses of the alloca
82 if (!isa<LoadInst>(*UI) && !isa<StoreInst>(*UI))
83 return false; // Not a load or store?
88 // FindSafeAllocas - Find allocas that are safe to promote
90 void PromotePass::FindSafeAllocas(Function &F) {
91 BasicBlock &BB = F.getEntryNode(); // Get the entry node for the function
93 // Look at all instructions in the entry node
94 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
95 if (AllocaInst *AI = dyn_cast<AllocaInst>(&*I)) // Is it an alloca?
96 if (isSafeAlloca(AI)) { // If safe alloca, add alloca to safe list
97 AllocaLookup[AI] = Allocas.size(); // Keep reverse mapping
98 Allocas.push_back(AI);
104 bool PromotePass::runOnFunction(Function &F) {
105 // Calculate the set of safe allocas
108 // If there is nothing to do, bail out...
109 if (Allocas.empty()) return false;
111 // Add each alloca to the KillList. Note: KillList is destroyed MOST recently
112 // added to least recently.
113 KillList.assign(Allocas.begin(), Allocas.end());
115 // Calculate the set of write-locations for each alloca. This is analogous to
116 // counting the number of 'redefinitions' of each variable.
117 vector<vector<BasicBlock*> > WriteSets; // index corresponds to Allocas
118 WriteSets.resize(Allocas.size());
119 for (unsigned i = 0; i != Allocas.size(); ++i) {
120 AllocaInst *AI = Allocas[i];
121 for (Value::use_iterator U =AI->use_begin(), E = AI->use_end(); U != E; ++U)
122 if (StoreInst *SI = dyn_cast<StoreInst>(*U))
123 // jot down the basic-block it came from
124 WriteSets[i].push_back(SI->getParent());
127 // Get dominance frontier information...
128 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
130 // Compute the locations where PhiNodes need to be inserted. Look at the
131 // dominance frontier of EACH basic-block we have a write in
133 PhiNodes.resize(Allocas.size());
134 for (unsigned i = 0; i != Allocas.size(); ++i) {
135 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(), PE = S.end();
144 // Perform iterative step
145 for (unsigned k = 0; k != PhiNodes[i].size(); k++) {
146 DominanceFrontier::const_iterator it = DF.find(PhiNodes[i][k]);
147 DominanceFrontier::DomSetType S = it->second;
148 for (DominanceFrontier::DomSetType::iterator P = S.begin(), PE = S.end();
154 // Set the incoming values for the basic block to be null values for all of
155 // the alloca's. We do this in case there is a load of a value that has not
156 // been stored yet. In this case, it will get this null value.
158 vector<Value *> Values(Allocas.size());
159 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
160 Values[i] = Constant::getNullValue(Allocas[i]->getAllocatedType());
162 // Walks all basic blocks in the function performing the SSA rename algorithm
163 // and inserting the phi nodes we marked as necessary
165 set<BasicBlock*> Visited; // The basic blocks we've already visited
166 Traverse(F.begin(), 0, Values, Visited);
168 // Remove all instructions marked by being placed in the KillList...
170 while (!KillList.empty()) {
171 Instruction *I = KillList.back();
174 I->getParent()->getInstList().erase(I);
177 NumPromoted += Allocas.size();
179 // Purge data structurse so they are available the next iteration...
181 AllocaLookup.clear();
188 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
189 // Alloca returns true if there wasn't already a phi-node for that variable
191 bool PromotePass::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo) {
192 // Look up the basic-block in question
193 vector<PHINode*> &BBPNs = NewPhiNodes[BB];
194 if (BBPNs.empty()) BBPNs.resize(Allocas.size());
196 // If the BB already has a phi node added for the i'th alloca then we're done!
197 if (BBPNs[AllocaNo]) return false;
199 // Create a PhiNode using the dereferenced type... and add the phi-node to the
201 PHINode *PN = new PHINode(Allocas[AllocaNo]->getAllocatedType(),
202 Allocas[AllocaNo]->getName()+".mem2reg",
204 BBPNs[AllocaNo] = PN;
205 PhiNodes[AllocaNo].push_back(BB);
209 void PromotePass::Traverse(BasicBlock *BB, BasicBlock *Pred,
210 vector<Value*> &IncomingVals,
211 set<BasicBlock*> &Visited) {
212 // If this is a BB needing a phi node, lookup/create the phinode for each
213 // variable we need phinodes for.
214 vector<PHINode *> &BBPNs = NewPhiNodes[BB];
215 for (unsigned k = 0; k != BBPNs.size(); ++k)
216 if (PHINode *PN = BBPNs[k]) {
217 // at this point we can assume that the array has phi nodes.. let's add
219 PN->addIncoming(IncomingVals[k], Pred);
221 // also note that the active variable IS designated by the phi node
222 IncomingVals[k] = PN;
225 // don't revisit nodes
226 if (Visited.count(BB)) return;
231 // keep track of the value of each variable we're watching.. how?
232 for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II) {
233 Instruction *I = II; // get the instruction
235 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
236 Value *Ptr = LI->getPointerOperand();
238 if (AllocaInst *Src = dyn_cast<AllocaInst>(Ptr)) {
239 map<Instruction*, 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 KillList.push_back(LI); // Mark the load to be deleted
248 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
249 // delete this instruction and mark the name as the current holder of the
251 Value *Ptr = SI->getPointerOperand();
252 if (AllocaInst *Dest = dyn_cast<AllocaInst>(Ptr)) {
253 map<Instruction *, unsigned>::iterator ai = AllocaLookup.find(Dest);
254 if (ai != AllocaLookup.end()) {
255 // what value were we writing?
256 IncomingVals[ai->second] = SI->getOperand(0);
257 KillList.push_back(SI); // Mark the store to be deleted
261 } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(I)) {
262 // Recurse across our successors
263 for (unsigned i = 0; i != TI->getNumSuccessors(); i++) {
264 vector<Value*> OutgoingVals(IncomingVals);
265 Traverse(TI->getSuccessor(i), BB, OutgoingVals, Visited);
272 // createPromoteMemoryToRegister - Provide an entry point to create this pass.
274 Pass *createPromoteMemoryToRegister() {
275 return new PromotePass();