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 looping over all of the alloca
17 // instruction, calculating dominator frontiers, then inserting phi-nodes
18 // following the usual SSA construction algorithm.
20 //===----------------------------------------------------------------------===//
22 #include "llvm/Transforms/Scalar.h"
23 #include "llvm/Analysis/Dominators.h"
24 #include "llvm/iMemory.h"
25 #include "llvm/iPHINode.h"
26 #include "llvm/iTerminators.h"
27 #include "llvm/Function.h"
28 #include "llvm/Constant.h"
29 #include "llvm/Type.h"
30 #include "Support/Statistic.h"
33 Statistic<> NumPromoted("mem2reg", "Number of alloca's promoted");
35 struct PromotePass : public FunctionPass {
36 std::vector<AllocaInst*> Allocas; // the alloca instruction..
37 std::map<Instruction*, unsigned> AllocaLookup; // reverse mapping of above
39 std::vector<std::vector<BasicBlock*> > PhiNodes;// Idx corresponds 2 Allocas
41 // List of instructions to remove at end of pass
42 std::vector<Instruction *> KillList;
45 std::vector<PHINode*> > NewPhiNodes; // the PhiNodes we're adding
48 // runOnFunction - To run this pass, first we calculate the alloca
49 // instructions that are safe for promotion, then we promote each one.
51 virtual bool runOnFunction(Function &F);
53 // getAnalysisUsage - We need dominance frontiers
55 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
56 AU.addRequired<DominanceFrontier>();
61 void RenamePass(BasicBlock *BB, BasicBlock *Pred,
62 std::vector<Value*> &IncVals,
63 std::set<BasicBlock*> &Visited);
64 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx);
65 void FindSafeAllocas(Function &F);
68 RegisterOpt<PromotePass> X("mem2reg", "Promote Memory to Register");
69 } // end of anonymous namespace
72 // isSafeAlloca - This predicate controls what types of alloca instructions are
73 // allowed to be promoted...
75 static inline bool isSafeAlloca(const AllocaInst *AI) {
76 if (AI->isArrayAllocation()) return false;
78 // Only allow direct loads and stores...
79 for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end();
80 UI != UE; ++UI) // Loop over all of the uses of the alloca
81 if (!isa<LoadInst>(*UI))
82 if (const StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
83 if (SI->getOperand(0) == AI)
84 return false; // Don't allow a store of the AI, only INTO the AI.
86 return false; // Not a load or store?
92 // FindSafeAllocas - Find allocas that are safe to promote
94 void PromotePass::FindSafeAllocas(Function &F) {
95 BasicBlock &BB = F.getEntryNode(); // Get the entry node for the function
97 // Look at all instructions in the entry node
98 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
99 if (AllocaInst *AI = dyn_cast<AllocaInst>(&*I)) // Is it an alloca?
100 if (isSafeAlloca(AI)) { // If safe alloca, add alloca to safe list
101 AllocaLookup[AI] = Allocas.size(); // Keep reverse mapping
102 Allocas.push_back(AI);
108 bool PromotePass::runOnFunction(Function &F) {
109 // Calculate the set of safe allocas
112 // If there is nothing to do, bail out...
113 if (Allocas.empty()) return false;
115 // Add each alloca to the KillList. Note: KillList is destroyed MOST recently
116 // added to least recently.
117 KillList.assign(Allocas.begin(), Allocas.end());
119 // Calculate the set of write-locations for each alloca. This is analogous to
120 // counting the number of 'redefinitions' of each variable.
121 std::vector<std::vector<BasicBlock*> > WriteSets;// Idx corresponds to Allocas
122 WriteSets.resize(Allocas.size());
123 for (unsigned i = 0; i != Allocas.size(); ++i) {
124 AllocaInst *AI = Allocas[i];
125 for (Value::use_iterator U =AI->use_begin(), E = AI->use_end(); U != E; ++U)
126 if (StoreInst *SI = dyn_cast<StoreInst>(*U))
127 // jot down the basic-block it came from
128 WriteSets[i].push_back(SI->getParent());
131 // Get dominance frontier information...
132 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
134 // Compute the locations where PhiNodes need to be inserted. Look at the
135 // dominance frontier of EACH basic-block we have a write in
137 PhiNodes.resize(Allocas.size());
138 for (unsigned i = 0; i != Allocas.size(); ++i) {
139 for (unsigned j = 0; j != WriteSets[i].size(); j++) {
140 // Look up the DF for this write, add it to PhiNodes
141 DominanceFrontier::const_iterator it = DF.find(WriteSets[i][j]);
142 DominanceFrontier::DomSetType S = it->second;
143 for (DominanceFrontier::DomSetType::iterator P = S.begin(), PE = S.end();
148 // Perform iterative step
149 for (unsigned k = 0; k != PhiNodes[i].size(); k++) {
150 DominanceFrontier::const_iterator it = DF.find(PhiNodes[i][k]);
151 DominanceFrontier::DomSetType S = it->second;
152 for (DominanceFrontier::DomSetType::iterator P = S.begin(), PE = S.end();
158 // Set the incoming values for the basic block to be null values for all of
159 // the alloca's. We do this in case there is a load of a value that has not
160 // been stored yet. In this case, it will get this null value.
162 std::vector<Value *> Values(Allocas.size());
163 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
164 Values[i] = Constant::getNullValue(Allocas[i]->getAllocatedType());
166 // Walks all basic blocks in the function performing the SSA rename algorithm
167 // and inserting the phi nodes we marked as necessary
169 std::set<BasicBlock*> Visited; // The basic blocks we've already visited
170 RenamePass(F.begin(), 0, Values, Visited);
172 // Remove all instructions marked by being placed in the KillList...
174 while (!KillList.empty()) {
175 Instruction *I = KillList.back();
178 I->getParent()->getInstList().erase(I);
181 NumPromoted += Allocas.size();
183 // Purge data structurse so they are available the next iteration...
185 AllocaLookup.clear();
192 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
193 // Alloca returns true if there wasn't already a phi-node for that variable
195 bool PromotePass::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo) {
196 // Look up the basic-block in question
197 std::vector<PHINode*> &BBPNs = NewPhiNodes[BB];
198 if (BBPNs.empty()) BBPNs.resize(Allocas.size());
200 // If the BB already has a phi node added for the i'th alloca then we're done!
201 if (BBPNs[AllocaNo]) return false;
203 // Create a PhiNode using the dereferenced type... and add the phi-node to the
205 PHINode *PN = new PHINode(Allocas[AllocaNo]->getAllocatedType(),
206 Allocas[AllocaNo]->getName()+".mem2reg",
208 BBPNs[AllocaNo] = PN;
209 PhiNodes[AllocaNo].push_back(BB);
213 void PromotePass::RenamePass(BasicBlock *BB, BasicBlock *Pred,
214 std::vector<Value*> &IncomingVals,
215 std::set<BasicBlock*> &Visited) {
216 // If this is a BB needing a phi node, lookup/create the phinode for each
217 // variable we need phinodes for.
218 std::vector<PHINode *> &BBPNs = NewPhiNodes[BB];
219 for (unsigned k = 0; k != BBPNs.size(); ++k)
220 if (PHINode *PN = BBPNs[k]) {
221 // at this point we can assume that the array has phi nodes.. let's add
223 PN->addIncoming(IncomingVals[k], Pred);
225 // also note that the active variable IS designated by the phi node
226 IncomingVals[k] = PN;
229 // don't revisit nodes
230 if (Visited.count(BB)) return;
235 // keep track of the value of each variable we're watching.. how?
236 for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II) {
237 Instruction *I = II; // get the instruction
239 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
240 if (AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand())) {
241 std::map<Instruction*, unsigned>::iterator AI = AllocaLookup.find(Src);
242 if (AI != AllocaLookup.end()) {
243 Value *V = IncomingVals[AI->second];
245 // walk the use list of this load and replace all uses with r
246 LI->replaceAllUsesWith(V);
247 KillList.push_back(LI); // Mark the load to be deleted
250 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
251 // Delete this instruction and mark the name as the current holder of the
253 if (AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand())) {
254 std::map<Instruction *, unsigned>::iterator ai =AllocaLookup.find(Dest);
255 if (ai != AllocaLookup.end()) {
256 // what value were we writing?
257 IncomingVals[ai->second] = SI->getOperand(0);
258 KillList.push_back(SI); // Mark the store to be deleted
262 } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(I)) {
263 // Recurse across our successors
264 for (unsigned i = 0; i != TI->getNumSuccessors(); i++) {
265 std::vector<Value*> OutgoingVals(IncomingVals);
266 RenamePass(TI->getSuccessor(i), BB, OutgoingVals, Visited);
273 // createPromoteMemoryToRegister - Provide an entry point to create this pass.
275 Pass *createPromoteMemoryToRegister() {
276 return new PromotePass();