1 //===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
3 // This file promote memory references to be register references. It promotes
4 // alloca instructions which only have loads and stores as uses. An alloca is
5 // transformed by using dominator frontiers to place PHI nodes, then traversing
6 // the function in depth-first order to rewrite loads and stores as appropriate.
7 // This is just the standard SSA construction algorithm.
9 //===----------------------------------------------------------------------===//
11 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
12 #include "llvm/Analysis/Dominators.h"
13 #include "llvm/iMemory.h"
14 #include "llvm/iPHINode.h"
15 #include "llvm/Function.h"
16 #include "llvm/Constant.h"
17 #include "llvm/Support/CFG.h"
18 #include "Support/StringExtras.h"
20 /// isAllocaPromotable - Return true if this alloca is legal for promotion.
21 /// This is true if there are only loads and stores to the alloca...
23 bool isAllocaPromotable(const AllocaInst *AI, const TargetData &TD) {
24 // FIXME: If the memory unit is of pointer or integer type, we can permit
25 // assignments to subsections of the memory unit.
27 // Only allow direct loads and stores...
28 for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end();
29 UI != UE; ++UI) // Loop over all of the uses of the alloca
30 if (!isa<LoadInst>(*UI))
31 if (const StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
32 if (SI->getOperand(0) == AI)
33 return false; // Don't allow a store of the AI, only INTO the AI.
35 return false; // Not a load or store?
43 struct PromoteMem2Reg {
44 // Allocas - The alloca instructions being promoted
45 const std::vector<AllocaInst*> &Allocas;
46 DominanceFrontier &DF;
49 // AllocaLookup - Reverse mapping of Allocas
50 std::map<AllocaInst*, unsigned> AllocaLookup;
52 // NewPhiNodes - The PhiNodes we're adding.
53 std::map<BasicBlock*, std::vector<PHINode*> > NewPhiNodes;
55 // Visited - The set of basic blocks the renamer has already visited.
56 std::set<BasicBlock*> Visited;
59 PromoteMem2Reg(const std::vector<AllocaInst*> &A, DominanceFrontier &df,
60 const TargetData &td) : Allocas(A), DF(df), TD(td) {}
65 void RenamePass(BasicBlock *BB, BasicBlock *Pred,
66 std::vector<Value*> &IncVals);
67 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version);
69 } // end of anonymous namespace
71 void PromoteMem2Reg::run() {
72 Function &F = *DF.getRoot()->getParent();
74 for (unsigned i = 0; i != Allocas.size(); ++i) {
75 AllocaInst *AI = Allocas[i];
77 assert(isAllocaPromotable(AI, TD) &&
78 "Cannot promote non-promotable alloca!");
79 assert(Allocas[i]->getParent()->getParent() == &F &&
80 "All allocas should be in the same function, which is same as DF!");
82 // Calculate the set of write-locations for each alloca. This is analogous
83 // to counting the number of 'redefinitions' of each variable.
84 std::vector<BasicBlock*> DefiningBlocks;
85 for (Value::use_iterator U =AI->use_begin(), E = AI->use_end(); U != E; ++U)
86 if (StoreInst *SI = dyn_cast<StoreInst>(cast<Instruction>(*U)))
87 // jot down the basic-block it came from
88 DefiningBlocks.push_back(SI->getParent());
90 AllocaLookup[Allocas[i]] = i;
92 // PhiNodeBlocks - A list of blocks that phi nodes have been inserted for
94 std::vector<BasicBlock*> PhiNodeBlocks;
96 // Compute the locations where PhiNodes need to be inserted. Look at the
97 // dominance frontier of EACH basic-block we have a write in.
99 unsigned CurrentVersion = 0;
100 while (!DefiningBlocks.empty()) {
101 BasicBlock *BB = DefiningBlocks.back();
102 DefiningBlocks.pop_back();
104 // Look up the DF for this write, add it to PhiNodes
105 DominanceFrontier::const_iterator it = DF.find(BB);
106 if (it != DF.end()) {
107 const DominanceFrontier::DomSetType &S = it->second;
108 for (DominanceFrontier::DomSetType::iterator P = S.begin(),PE = S.end();
110 if (QueuePhiNode(*P, i, CurrentVersion))
111 DefiningBlocks.push_back(*P);
116 // Set the incoming values for the basic block to be null values for all of
117 // the alloca's. We do this in case there is a load of a value that has not
118 // been stored yet. In this case, it will get this null value.
120 std::vector<Value *> Values(Allocas.size());
121 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
122 Values[i] = Constant::getNullValue(Allocas[i]->getAllocatedType());
124 // Walks all basic blocks in the function performing the SSA rename algorithm
125 // and inserting the phi nodes we marked as necessary
127 RenamePass(F.begin(), 0, Values);
129 // The renamer uses the Visited set to avoid infinite loops. Clear it now.
132 // Remove the allocas themselves from the function...
133 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
134 Instruction *A = Allocas[i];
136 // If there are any uses of the alloca instructions left, they must be in
137 // sections of dead code that were not processed on the dominance frontier.
138 // Just delete the users now.
141 A->replaceAllUsesWith(Constant::getNullValue(A->getType()));
142 A->getParent()->getInstList().erase(A);
145 // At this point, the renamer has added entries to PHI nodes for all reachable
146 // code. Unfortunately, there may be blocks which are not reachable, which
147 // the renamer hasn't traversed. If this is the case, the PHI nodes may not
148 // have incoming values for all predecessors. Loop over all PHI nodes we have
149 // created, inserting null constants if they are missing any incoming values.
151 for (std::map<BasicBlock*, std::vector<PHINode *> >::iterator I =
152 NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E; ++I) {
154 std::vector<BasicBlock*> Preds(pred_begin(I->first), pred_end(I->first));
155 std::vector<PHINode*> &PNs = I->second;
156 assert(!PNs.empty() && "Empty PHI node list??");
158 // Only do work here if there the PHI nodes are missing incoming values. We
159 // know that all PHI nodes that were inserted in a block will have the same
160 // number of incoming values, so we can just check any PHI node.
162 for (unsigned i = 0; (FirstPHI = PNs[i]) == 0; ++i)
165 if (Preds.size() != FirstPHI->getNumIncomingValues()) {
166 // Ok, now we know that all of the PHI nodes are missing entries for some
167 // basic blocks. Start by sorting the incoming predecessors for efficient
169 std::sort(Preds.begin(), Preds.end());
171 // Now we loop through all BB's which have entries in FirstPHI and remove
172 // them from the Preds list.
173 for (unsigned i = 0, e = FirstPHI->getNumIncomingValues(); i != e; ++i) {
174 // Do a log(n) search of teh Preds list for the entry we want.
175 std::vector<BasicBlock*>::iterator EntIt =
176 std::lower_bound(Preds.begin(), Preds.end(),
177 FirstPHI->getIncomingBlock(i));
178 assert(EntIt != Preds.end() && *EntIt == FirstPHI->getIncomingBlock(i)&&
179 "PHI node has entry for a block which is not a predecessor!");
185 // At this point, the blocks left in the preds list must have dummy
186 // entries inserted into every PHI nodes for the block.
187 for (unsigned i = 0, e = PNs.size(); i != e; ++i) {
188 PHINode *PN = PNs[i];
189 Value *NullVal = Constant::getNullValue(PN->getType());
190 for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
191 PN->addIncoming(NullVal, Preds[pred]);
198 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
199 // Alloca returns true if there wasn't already a phi-node for that variable
201 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
203 // Look up the basic-block in question
204 std::vector<PHINode*> &BBPNs = NewPhiNodes[BB];
205 if (BBPNs.empty()) BBPNs.resize(Allocas.size());
207 // If the BB already has a phi node added for the i'th alloca then we're done!
208 if (BBPNs[AllocaNo]) return false;
210 // Create a PhiNode using the dereferenced type... and add the phi-node to the
212 BBPNs[AllocaNo] = new PHINode(Allocas[AllocaNo]->getAllocatedType(),
213 Allocas[AllocaNo]->getName() + "." +
214 utostr(Version++), BB->begin());
218 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
219 std::vector<Value*> &IncomingVals) {
221 // If this BB needs a PHI node, update the PHI node for each variable we need
223 std::map<BasicBlock*, std::vector<PHINode *> >::iterator
224 BBPNI = NewPhiNodes.find(BB);
225 if (BBPNI != NewPhiNodes.end()) {
226 std::vector<PHINode *> &BBPNs = BBPNI->second;
227 for (unsigned k = 0; k != BBPNs.size(); ++k)
228 if (PHINode *PN = BBPNs[k]) {
229 // Add this incoming value to the PHI node.
230 PN->addIncoming(IncomingVals[k], Pred);
232 // The currently active variable for this block is now the PHI.
233 IncomingVals[k] = PN;
237 // don't revisit nodes
238 if (Visited.count(BB)) return;
243 for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II); ) {
244 Instruction *I = II++; // get the instruction, increment iterator
246 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
247 if (AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand())) {
248 std::map<AllocaInst*, unsigned>::iterator AI = AllocaLookup.find(Src);
249 if (AI != AllocaLookup.end()) {
250 Value *V = IncomingVals[AI->second];
252 // walk the use list of this load and replace all uses with r
253 LI->replaceAllUsesWith(V);
254 BB->getInstList().erase(LI);
257 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
258 // Delete this instruction and mark the name as the current holder of the
260 if (AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand())) {
261 std::map<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
262 if (ai != AllocaLookup.end()) {
263 // what value were we writing?
264 IncomingVals[ai->second] = SI->getOperand(0);
265 BB->getInstList().erase(SI);
271 // Recurse to our successors
272 TerminatorInst *TI = BB->getTerminator();
273 for (unsigned i = 0; i != TI->getNumSuccessors(); i++) {
274 std::vector<Value*> OutgoingVals(IncomingVals);
275 RenamePass(TI->getSuccessor(i), BB, OutgoingVals);
279 /// PromoteMemToReg - Promote the specified list of alloca instructions into
280 /// scalar registers, inserting PHI nodes as appropriate. This function makes
281 /// use of DominanceFrontier information. This function does not modify the CFG
282 /// of the function at all. All allocas must be from the same function.
284 void PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
285 DominanceFrontier &DF, const TargetData &TD) {
286 // If there is nothing to do, bail out...
287 if (Allocas.empty()) return;
288 PromoteMem2Reg(Allocas, DF, TD).run();