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 // VersionNumbers - Current version counters for each alloca
53 std::vector<unsigned> VersionNumbers;
55 // NewPhiNodes - The PhiNodes we're adding.
56 std::map<BasicBlock*, std::vector<PHINode*> > NewPhiNodes;
58 // Visited - The set of basic blocks the renamer has already visited.
59 std::set<BasicBlock*> Visited;
62 PromoteMem2Reg(const std::vector<AllocaInst*> &A, DominanceFrontier &df,
63 const TargetData &td) : Allocas(A), DF(df), TD(td) {}
68 void RenamePass(BasicBlock *BB, BasicBlock *Pred,
69 std::vector<Value*> &IncVals);
70 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx);
72 } // end of anonymous namespace
74 void PromoteMem2Reg::run() {
75 Function &F = *DF.getRoot()->getParent();
77 VersionNumbers.resize(Allocas.size());
79 for (unsigned i = 0; i != Allocas.size(); ++i) {
80 AllocaInst *AI = Allocas[i];
82 assert(isAllocaPromotable(AI, TD) &&
83 "Cannot promote non-promotable alloca!");
84 assert(Allocas[i]->getParent()->getParent() == &F &&
85 "All allocas should be in the same function, which is same as DF!");
87 // Calculate the set of write-locations for each alloca. This is analogous
88 // to counting the number of 'redefinitions' of each variable.
89 std::vector<BasicBlock*> DefiningBlocks;
90 for (Value::use_iterator U =AI->use_begin(), E = AI->use_end(); U != E; ++U)
91 if (StoreInst *SI = dyn_cast<StoreInst>(cast<Instruction>(*U)))
92 // jot down the basic-block it came from
93 DefiningBlocks.push_back(SI->getParent());
95 AllocaLookup[Allocas[i]] = i;
97 // PhiNodeBlocks - A list of blocks that phi nodes have been inserted for
99 std::vector<BasicBlock*> PhiNodeBlocks;
101 // Compute the locations where PhiNodes need to be inserted. Look at the
102 // dominance frontier of EACH basic-block we have a write in.
104 while (!DefiningBlocks.empty()) {
105 BasicBlock *BB = DefiningBlocks.back();
106 DefiningBlocks.pop_back();
108 // Look up the DF for this write, add it to PhiNodes
109 DominanceFrontier::const_iterator it = DF.find(BB);
110 if (it != DF.end()) {
111 const DominanceFrontier::DomSetType &S = it->second;
112 for (DominanceFrontier::DomSetType::iterator P = S.begin(),PE = S.end();
114 if (QueuePhiNode(*P, i))
115 DefiningBlocks.push_back(*P);
120 // Set the incoming values for the basic block to be null values for all of
121 // the alloca's. We do this in case there is a load of a value that has not
122 // been stored yet. In this case, it will get this null value.
124 std::vector<Value *> Values(Allocas.size());
125 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
126 Values[i] = Constant::getNullValue(Allocas[i]->getAllocatedType());
128 // Walks all basic blocks in the function performing the SSA rename algorithm
129 // and inserting the phi nodes we marked as necessary
131 RenamePass(F.begin(), 0, Values);
133 // The renamer uses the Visited set to avoid infinite loops. Clear it now.
136 // Remove the allocas themselves from the function...
137 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
138 Instruction *A = Allocas[i];
140 // If there are any uses of the alloca instructions left, they must be in
141 // sections of dead code that were not processed on the dominance frontier.
142 // Just delete the users now.
145 A->replaceAllUsesWith(Constant::getNullValue(A->getType()));
146 A->getParent()->getInstList().erase(A);
149 // At this point, the renamer has added entries to PHI nodes for all reachable
150 // code. Unfortunately, there may be blocks which are not reachable, which
151 // the renamer hasn't traversed. If this is the case, the PHI nodes may not
152 // have incoming values for all predecessors. Loop over all PHI nodes we have
153 // created, inserting null constants if they are missing any incoming values.
155 for (std::map<BasicBlock*, std::vector<PHINode *> >::iterator I =
156 NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E; ++I) {
158 std::vector<BasicBlock*> Preds(pred_begin(I->first), pred_end(I->first));
159 std::vector<PHINode*> &PNs = I->second;
160 assert(!PNs.empty() && "Empty PHI node list??");
162 // Only do work here if there the PHI nodes are missing incoming values. We
163 // know that all PHI nodes that were inserted in a block will have the same
164 // number of incoming values, so we can just check any PHI node.
165 PHINode *FirstPHI = PNs[0];
166 if (Preds.size() != FirstPHI->getNumIncomingValues()) {
167 // Ok, now we know that all of the PHI nodes are missing entries for some
168 // basic blocks. Start by sorting the incoming predecessors for efficient
170 std::sort(Preds.begin(), Preds.end());
172 // Now we loop through all BB's which have entries in FirstPHI and remove
173 // them from the Preds list.
174 for (unsigned i = 0, e = FirstPHI->getNumIncomingValues(); i != e; ++i) {
175 // Do a log(n) search of teh Preds list for the entry we want.
176 std::vector<BasicBlock*>::iterator EntIt =
177 std::lower_bound(Preds.begin(), Preds.end(),
178 FirstPHI->getIncomingBlock(i));
179 assert(EntIt != Preds.end() && *EntIt == FirstPHI->getIncomingBlock(i)&&
180 "PHI node has entry for a block which is not a predecessor!");
186 // At this point, the blocks left in the preds list must have dummy
187 // entries inserted into every PHI nodes for the block.
188 for (unsigned i = 0, e = PNs.size(); i != e; ++i) {
189 PHINode *PN = PNs[i];
190 Value *NullVal = Constant::getNullValue(PN->getType());
191 for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
192 PN->addIncoming(NullVal, Preds[pred]);
199 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
200 // Alloca returns true if there wasn't already a phi-node for that variable
202 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(VersionNumbers[AllocaNo]++),
219 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
220 std::vector<Value*> &IncomingVals) {
222 // If this BB needs a PHI node, update the PHI node for each variable we need
224 std::map<BasicBlock*, std::vector<PHINode *> >::iterator
225 BBPNI = NewPhiNodes.find(BB);
226 if (BBPNI != NewPhiNodes.end()) {
227 std::vector<PHINode *> &BBPNs = BBPNI->second;
228 for (unsigned k = 0; k != BBPNs.size(); ++k)
229 if (PHINode *PN = BBPNs[k]) {
230 // Add this incoming value to the PHI node.
231 PN->addIncoming(IncomingVals[k], Pred);
233 // The currently active variable for this block is now the PHI.
234 IncomingVals[k] = PN;
238 // don't revisit nodes
239 if (Visited.count(BB)) return;
244 for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II); ) {
245 Instruction *I = II++; // get the instruction, increment iterator
247 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
248 if (AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand())) {
249 std::map<AllocaInst*, unsigned>::iterator AI = AllocaLookup.find(Src);
250 if (AI != AllocaLookup.end()) {
251 Value *V = IncomingVals[AI->second];
253 // walk the use list of this load and replace all uses with r
254 LI->replaceAllUsesWith(V);
255 BB->getInstList().erase(LI);
258 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
259 // Delete this instruction and mark the name as the current holder of the
261 if (AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand())) {
262 std::map<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
263 if (ai != AllocaLookup.end()) {
264 // what value were we writing?
265 IncomingVals[ai->second] = SI->getOperand(0);
266 BB->getInstList().erase(SI);
272 // Recurse to our successors
273 TerminatorInst *TI = BB->getTerminator();
274 for (unsigned i = 0; i != TI->getNumSuccessors(); i++) {
275 std::vector<Value*> OutgoingVals(IncomingVals);
276 RenamePass(TI->getSuccessor(i), BB, OutgoingVals);
280 /// PromoteMemToReg - Promote the specified list of alloca instructions into
281 /// scalar registers, inserting PHI nodes as appropriate. This function makes
282 /// use of DominanceFrontier information. This function does not modify the CFG
283 /// of the function at all. All allocas must be from the same function.
285 void PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
286 DominanceFrontier &DF, const TargetData &TD) {
287 // If there is nothing to do, bail out...
288 if (Allocas.empty()) return;
289 PromoteMem2Reg(Allocas, DF, TD).run();