1 //===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file promote memory references to be register references. It promotes
11 // alloca instructions which only have loads and stores as uses. An alloca is
12 // transformed by using dominator frontiers to place PHI nodes, then traversing
13 // the function in depth-first order to rewrite loads and stores as appropriate.
14 // This is just the standard SSA construction algorithm to construct "pruned"
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
20 #include "llvm/Constant.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Analysis/Dominators.h"
25 #include "llvm/Analysis/AliasSetTracker.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Support/CFG.h"
28 #include "llvm/Support/StableBasicBlockNumbering.h"
32 /// isAllocaPromotable - Return true if this alloca is legal for promotion.
33 /// This is true if there are only loads and stores to the alloca.
35 bool llvm::isAllocaPromotable(const AllocaInst *AI, const TargetData &TD) {
36 // FIXME: If the memory unit is of pointer or integer type, we can permit
37 // assignments to subsections of the memory unit.
39 // Only allow direct loads and stores...
40 for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end();
41 UI != UE; ++UI) // Loop over all of the uses of the alloca
42 if (isa<LoadInst>(*UI)) {
44 } else if (const StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
45 if (SI->getOperand(0) == AI)
46 return false; // Don't allow a store OF the AI, only INTO the AI.
48 return false; // Not a load or store.
55 struct PromoteMem2Reg {
56 /// Allocas - The alloca instructions being promoted.
58 std::vector<AllocaInst*> Allocas;
60 DominanceFrontier &DF;
63 /// AST - An AliasSetTracker object to update. If null, don't update it.
67 /// AllocaLookup - Reverse mapping of Allocas.
69 std::map<AllocaInst*, unsigned> AllocaLookup;
71 /// NewPhiNodes - The PhiNodes we're adding.
73 std::map<BasicBlock*, std::vector<PHINode*> > NewPhiNodes;
75 /// PointerAllocaValues - If we are updating an AliasSetTracker, then for
76 /// each alloca that is of pointer type, we keep track of what to copyValue
77 /// to the inserted PHI nodes here.
79 std::vector<Value*> PointerAllocaValues;
81 /// Visited - The set of basic blocks the renamer has already visited.
83 std::set<BasicBlock*> Visited;
85 /// BBNumbers - Contains a stable numbering of basic blocks to avoid
86 /// non-determinstic behavior.
87 StableBasicBlockNumbering BBNumbers;
90 PromoteMem2Reg(const std::vector<AllocaInst*> &A, DominatorTree &dt,
91 DominanceFrontier &df, const TargetData &td,
93 : Allocas(A), DT(dt), DF(df), TD(td), AST(ast) {}
98 void MarkDominatingPHILive(BasicBlock *BB, unsigned AllocaNum,
99 std::set<PHINode*> &DeadPHINodes);
100 void PromoteLocallyUsedAlloca(BasicBlock *BB, AllocaInst *AI);
101 void PromoteLocallyUsedAllocas(BasicBlock *BB,
102 const std::vector<AllocaInst*> &AIs);
104 void RenamePass(BasicBlock *BB, BasicBlock *Pred,
105 std::vector<Value*> &IncVals);
106 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version,
107 std::set<PHINode*> &InsertedPHINodes);
109 } // end of anonymous namespace
111 void PromoteMem2Reg::run() {
112 Function &F = *DF.getRoot()->getParent();
114 // LocallyUsedAllocas - Keep track of all of the alloca instructions which are
115 // only used in a single basic block. These instructions can be efficiently
116 // promoted by performing a single linear scan over that one block. Since
117 // individual basic blocks are sometimes large, we group together all allocas
118 // that are live in a single basic block by the basic block they are live in.
119 std::map<BasicBlock*, std::vector<AllocaInst*> > LocallyUsedAllocas;
121 if (AST) PointerAllocaValues.resize(Allocas.size());
123 for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
124 AllocaInst *AI = Allocas[AllocaNum];
126 assert(isAllocaPromotable(AI, TD) &&
127 "Cannot promote non-promotable alloca!");
128 assert(AI->getParent()->getParent() == &F &&
129 "All allocas should be in the same function, which is same as DF!");
131 if (AI->use_empty()) {
132 // If there are no uses of the alloca, just delete it now.
133 if (AST) AST->deleteValue(AI);
134 AI->getParent()->getInstList().erase(AI);
136 // Remove the alloca from the Allocas list, since it has been processed
137 Allocas[AllocaNum] = Allocas.back();
143 // Calculate the set of read and write-locations for each alloca. This is
144 // analogous to finding the 'uses' and 'definitions' of each variable.
145 std::vector<BasicBlock*> DefiningBlocks;
146 std::vector<BasicBlock*> UsingBlocks;
148 BasicBlock *OnlyBlock = 0;
149 bool OnlyUsedInOneBlock = true;
151 // As we scan the uses of the alloca instruction, keep track of stores, and
152 // decide whether all of the loads and stores to the alloca are within the
154 Value *AllocaPointerVal = 0;
155 for (Value::use_iterator U =AI->use_begin(), E = AI->use_end(); U != E;++U){
156 Instruction *User = cast<Instruction>(*U);
157 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
158 // Remember the basic blocks which define new values for the alloca
159 DefiningBlocks.push_back(SI->getParent());
160 AllocaPointerVal = SI->getOperand(0);
161 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
162 // Otherwise it must be a load instruction, keep track of variable reads
163 UsingBlocks.push_back(LI->getParent());
164 AllocaPointerVal = LI;
167 if (OnlyUsedInOneBlock) {
169 OnlyBlock = User->getParent();
170 else if (OnlyBlock != User->getParent())
171 OnlyUsedInOneBlock = false;
175 // If the alloca is only read and written in one basic block, just perform a
176 // linear sweep over the block to eliminate it.
177 if (OnlyUsedInOneBlock) {
178 LocallyUsedAllocas[OnlyBlock].push_back(AI);
180 // Remove the alloca from the Allocas list, since it will be processed.
181 Allocas[AllocaNum] = Allocas.back();
188 PointerAllocaValues[AllocaNum] = AllocaPointerVal;
190 // If we haven't computed a numbering for the BB's in the function, do so
192 BBNumbers.compute(F);
194 // Compute the locations where PhiNodes need to be inserted. Look at the
195 // dominance frontier of EACH basic-block we have a write in.
197 unsigned CurrentVersion = 0;
198 std::set<PHINode*> InsertedPHINodes;
199 std::vector<unsigned> DFBlocks;
200 while (!DefiningBlocks.empty()) {
201 BasicBlock *BB = DefiningBlocks.back();
202 DefiningBlocks.pop_back();
204 // Look up the DF for this write, add it to PhiNodes
205 DominanceFrontier::const_iterator it = DF.find(BB);
206 if (it != DF.end()) {
207 const DominanceFrontier::DomSetType &S = it->second;
209 // In theory we don't need the indirection through the DFBlocks vector.
210 // In practice, the order of calling QueuePhiNode would depend on the
211 // (unspecified) ordering of basic blocks in the dominance frontier,
212 // which would give PHI nodes non-determinstic subscripts. Fix this by
213 // processing blocks in order of the occurance in the function.
214 for (DominanceFrontier::DomSetType::iterator P = S.begin(),PE = S.end();
216 DFBlocks.push_back(BBNumbers.getNumber(*P));
218 // Sort by which the block ordering in the function.
219 std::sort(DFBlocks.begin(), DFBlocks.end());
221 for (unsigned i = 0, e = DFBlocks.size(); i != e; ++i) {
222 BasicBlock *BB = BBNumbers.getBlock(DFBlocks[i]);
223 if (QueuePhiNode(BB, AllocaNum, CurrentVersion, InsertedPHINodes))
224 DefiningBlocks.push_back(BB);
230 // Now that we have inserted PHI nodes along the Iterated Dominance Frontier
231 // of the writes to the variable, scan through the reads of the variable,
232 // marking PHI nodes which are actually necessary as alive (by removing them
233 // from the InsertedPHINodes set). This is not perfect: there may PHI
234 // marked alive because of loads which are dominated by stores, but there
235 // will be no unmarked PHI nodes which are actually used.
237 for (unsigned i = 0, e = UsingBlocks.size(); i != e; ++i)
238 MarkDominatingPHILive(UsingBlocks[i], AllocaNum, InsertedPHINodes);
241 // If there are any PHI nodes which are now known to be dead, remove them!
242 for (std::set<PHINode*>::iterator I = InsertedPHINodes.begin(),
243 E = InsertedPHINodes.end(); I != E; ++I) {
245 std::vector<PHINode*> &BBPNs = NewPhiNodes[PN->getParent()];
246 BBPNs[AllocaNum] = 0;
248 // Check to see if we just removed the last inserted PHI node from this
249 // basic block. If so, remove the entry for the basic block.
250 bool HasOtherPHIs = false;
251 for (unsigned i = 0, e = BBPNs.size(); i != e; ++i)
257 NewPhiNodes.erase(PN->getParent());
259 if (AST && isa<PointerType>(PN->getType()))
260 AST->deleteValue(PN);
261 PN->getParent()->getInstList().erase(PN);
264 // Keep the reverse mapping of the 'Allocas' array.
265 AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
268 // Process all allocas which are only used in a single basic block.
269 for (std::map<BasicBlock*, std::vector<AllocaInst*> >::iterator I =
270 LocallyUsedAllocas.begin(), E = LocallyUsedAllocas.end(); I != E; ++I){
271 const std::vector<AllocaInst*> &Allocas = I->second;
272 assert(!Allocas.empty() && "empty alloca list??");
274 // It's common for there to only be one alloca in the list. Handle it
276 if (Allocas.size() == 1)
277 PromoteLocallyUsedAlloca(I->first, Allocas[0]);
279 PromoteLocallyUsedAllocas(I->first, Allocas);
283 return; // All of the allocas must have been trivial!
285 // Set the incoming values for the basic block to be null values for all of
286 // the alloca's. We do this in case there is a load of a value that has not
287 // been stored yet. In this case, it will get this null value.
289 std::vector<Value *> Values(Allocas.size());
290 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
291 Values[i] = Constant::getNullValue(Allocas[i]->getAllocatedType());
293 // Walks all basic blocks in the function performing the SSA rename algorithm
294 // and inserting the phi nodes we marked as necessary
296 RenamePass(F.begin(), 0, Values);
298 // The renamer uses the Visited set to avoid infinite loops. Clear it now.
301 // Remove the allocas themselves from the function...
302 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
303 Instruction *A = Allocas[i];
305 // If there are any uses of the alloca instructions left, they must be in
306 // sections of dead code that were not processed on the dominance frontier.
307 // Just delete the users now.
310 A->replaceAllUsesWith(Constant::getNullValue(A->getType()));
311 if (AST) AST->deleteValue(A);
312 A->getParent()->getInstList().erase(A);
315 // At this point, the renamer has added entries to PHI nodes for all reachable
316 // code. Unfortunately, there may be blocks which are not reachable, which
317 // the renamer hasn't traversed. If this is the case, the PHI nodes may not
318 // have incoming values for all predecessors. Loop over all PHI nodes we have
319 // created, inserting null constants if they are missing any incoming values.
321 for (std::map<BasicBlock*, std::vector<PHINode *> >::iterator I =
322 NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E; ++I) {
324 std::vector<BasicBlock*> Preds(pred_begin(I->first), pred_end(I->first));
325 std::vector<PHINode*> &PNs = I->second;
326 assert(!PNs.empty() && "Empty PHI node list??");
328 // Only do work here if there the PHI nodes are missing incoming values. We
329 // know that all PHI nodes that were inserted in a block will have the same
330 // number of incoming values, so we can just check any PHI node.
332 for (unsigned i = 0; (FirstPHI = PNs[i]) == 0; ++i)
335 if (Preds.size() != FirstPHI->getNumIncomingValues()) {
336 // Ok, now we know that all of the PHI nodes are missing entries for some
337 // basic blocks. Start by sorting the incoming predecessors for efficient
339 std::sort(Preds.begin(), Preds.end());
341 // Now we loop through all BB's which have entries in FirstPHI and remove
342 // them from the Preds list.
343 for (unsigned i = 0, e = FirstPHI->getNumIncomingValues(); i != e; ++i) {
344 // Do a log(n) search of the Preds list for the entry we want.
345 std::vector<BasicBlock*>::iterator EntIt =
346 std::lower_bound(Preds.begin(), Preds.end(),
347 FirstPHI->getIncomingBlock(i));
348 assert(EntIt != Preds.end() && *EntIt == FirstPHI->getIncomingBlock(i)&&
349 "PHI node has entry for a block which is not a predecessor!");
355 // At this point, the blocks left in the preds list must have dummy
356 // entries inserted into every PHI nodes for the block.
357 for (unsigned i = 0, e = PNs.size(); i != e; ++i)
358 if (PHINode *PN = PNs[i]) {
359 Value *NullVal = Constant::getNullValue(PN->getType());
360 for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
361 PN->addIncoming(NullVal, Preds[pred]);
367 // MarkDominatingPHILive - Mem2Reg wants to construct "pruned" SSA form, not
368 // "minimal" SSA form. To do this, it inserts all of the PHI nodes on the IDF
369 // as usual (inserting the PHI nodes in the DeadPHINodes set), then processes
370 // each read of the variable. For each block that reads the variable, this
371 // function is called, which removes used PHI nodes from the DeadPHINodes set.
372 // After all of the reads have been processed, any PHI nodes left in the
373 // DeadPHINodes set are removed.
375 void PromoteMem2Reg::MarkDominatingPHILive(BasicBlock *BB, unsigned AllocaNum,
376 std::set<PHINode*> &DeadPHINodes) {
377 // Scan the immediate dominators of this block looking for a block which has a
378 // PHI node for Alloca num. If we find it, mark the PHI node as being alive!
379 for (DominatorTree::Node *N = DT[BB]; N; N = N->getIDom()) {
380 BasicBlock *DomBB = N->getBlock();
381 std::map<BasicBlock*, std::vector<PHINode*> >::iterator
382 I = NewPhiNodes.find(DomBB);
383 if (I != NewPhiNodes.end() && I->second[AllocaNum]) {
384 // Ok, we found an inserted PHI node which dominates this value.
385 PHINode *DominatingPHI = I->second[AllocaNum];
387 // Find out if we previously thought it was dead.
388 std::set<PHINode*>::iterator DPNI = DeadPHINodes.find(DominatingPHI);
389 if (DPNI != DeadPHINodes.end()) {
390 // Ok, until now, we thought this PHI node was dead. Mark it as being
392 DeadPHINodes.erase(DPNI);
394 // Now that we have marked the PHI node alive, also mark any PHI nodes
395 // which it might use as being alive as well.
396 for (pred_iterator PI = pred_begin(DomBB), PE = pred_end(DomBB);
398 MarkDominatingPHILive(*PI, AllocaNum, DeadPHINodes);
404 /// PromoteLocallyUsedAlloca - Many allocas are only used within a single basic
405 /// block. If this is the case, avoid traversing the CFG and inserting a lot of
406 /// potentially useless PHI nodes by just performing a single linear pass over
407 /// the basic block using the Alloca.
409 void PromoteMem2Reg::PromoteLocallyUsedAlloca(BasicBlock *BB, AllocaInst *AI) {
410 assert(!AI->use_empty() && "There are no uses of the alloca!");
412 // Handle degenerate cases quickly.
413 if (AI->hasOneUse()) {
414 Instruction *U = cast<Instruction>(AI->use_back());
415 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
416 // Must be a load of uninitialized value.
417 LI->replaceAllUsesWith(Constant::getNullValue(AI->getAllocatedType()));
418 if (AST && isa<PointerType>(LI->getType()))
419 AST->deleteValue(LI);
421 // Otherwise it must be a store which is never read.
422 assert(isa<StoreInst>(U));
424 BB->getInstList().erase(U);
426 // Uses of the uninitialized memory location shall get zero...
427 Value *CurVal = Constant::getNullValue(AI->getAllocatedType());
429 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
430 Instruction *Inst = I++;
431 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
432 if (LI->getOperand(0) == AI) {
433 // Loads just returns the "current value"...
434 LI->replaceAllUsesWith(CurVal);
435 if (AST && isa<PointerType>(LI->getType()))
436 AST->deleteValue(LI);
437 BB->getInstList().erase(LI);
439 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
440 if (SI->getOperand(1) == AI) {
441 // Store updates the "current value"...
442 CurVal = SI->getOperand(0);
443 BB->getInstList().erase(SI);
449 // After traversing the basic block, there should be no more uses of the
450 // alloca, remove it now.
451 assert(AI->use_empty() && "Uses of alloca from more than one BB??");
452 if (AST) AST->deleteValue(AI);
453 AI->getParent()->getInstList().erase(AI);
456 /// PromoteLocallyUsedAllocas - This method is just like
457 /// PromoteLocallyUsedAlloca, except that it processes multiple alloca
458 /// instructions in parallel. This is important in cases where we have large
459 /// basic blocks, as we don't want to rescan the entire basic block for each
460 /// alloca which is locally used in it (which might be a lot).
461 void PromoteMem2Reg::
462 PromoteLocallyUsedAllocas(BasicBlock *BB, const std::vector<AllocaInst*> &AIs) {
463 std::map<AllocaInst*, Value*> CurValues;
464 for (unsigned i = 0, e = AIs.size(); i != e; ++i)
465 CurValues[AIs[i]] = 0; // Insert with null value
467 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
468 Instruction *Inst = I++;
469 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
470 // Is this a load of an alloca we are tracking?
471 if (AllocaInst *AI = dyn_cast<AllocaInst>(LI->getOperand(0))) {
472 std::map<AllocaInst*, Value*>::iterator AIt = CurValues.find(AI);
473 if (AIt != CurValues.end()) {
474 // Loads just returns the "current value"...
475 if (AIt->second == 0) // Uninitialized value??
476 AIt->second =Constant::getNullValue(AIt->first->getAllocatedType());
477 LI->replaceAllUsesWith(AIt->second);
478 if (AST && isa<PointerType>(LI->getType()))
479 AST->deleteValue(LI);
480 BB->getInstList().erase(LI);
483 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
484 if (AllocaInst *AI = dyn_cast<AllocaInst>(SI->getOperand(1))) {
485 std::map<AllocaInst*, Value*>::iterator AIt = CurValues.find(AI);
486 if (AIt != CurValues.end()) {
487 // Store updates the "current value"...
488 AIt->second = SI->getOperand(0);
489 BB->getInstList().erase(SI);
498 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
499 // Alloca returns true if there wasn't already a phi-node for that variable
501 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
503 std::set<PHINode*> &InsertedPHINodes) {
504 // Look up the basic-block in question.
505 std::vector<PHINode*> &BBPNs = NewPhiNodes[BB];
506 if (BBPNs.empty()) BBPNs.resize(Allocas.size());
508 // If the BB already has a phi node added for the i'th alloca then we're done!
509 if (BBPNs[AllocaNo]) return false;
511 // Create a PhiNode using the dereferenced type... and add the phi-node to the
513 PHINode *PN = new PHINode(Allocas[AllocaNo]->getAllocatedType(),
514 Allocas[AllocaNo]->getName() + "." +
515 utostr(Version++), BB->begin());
516 BBPNs[AllocaNo] = PN;
517 InsertedPHINodes.insert(PN);
519 if (AST && isa<PointerType>(PN->getType()))
520 AST->copyValue(PointerAllocaValues[AllocaNo], PN);
526 // RenamePass - Recursively traverse the CFG of the function, renaming loads and
527 // stores to the allocas which we are promoting. IncomingVals indicates what
528 // value each Alloca contains on exit from the predecessor block Pred.
530 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
531 std::vector<Value*> &IncomingVals) {
533 // If this BB needs a PHI node, update the PHI node for each variable we need
535 std::map<BasicBlock*, std::vector<PHINode *> >::iterator
536 BBPNI = NewPhiNodes.find(BB);
537 if (BBPNI != NewPhiNodes.end()) {
538 std::vector<PHINode *> &BBPNs = BBPNI->second;
539 for (unsigned k = 0; k != BBPNs.size(); ++k)
540 if (PHINode *PN = BBPNs[k]) {
541 // Add this incoming value to the PHI node.
542 PN->addIncoming(IncomingVals[k], Pred);
544 // The currently active variable for this block is now the PHI.
545 IncomingVals[k] = PN;
549 // don't revisit nodes
550 if (Visited.count(BB)) return;
555 for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II); ) {
556 Instruction *I = II++; // get the instruction, increment iterator
558 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
559 if (AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand())) {
560 std::map<AllocaInst*, unsigned>::iterator AI = AllocaLookup.find(Src);
561 if (AI != AllocaLookup.end()) {
562 Value *V = IncomingVals[AI->second];
564 // walk the use list of this load and replace all uses with r
565 LI->replaceAllUsesWith(V);
566 if (AST && isa<PointerType>(LI->getType()))
567 AST->deleteValue(LI);
568 BB->getInstList().erase(LI);
571 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
572 // Delete this instruction and mark the name as the current holder of the
574 if (AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand())) {
575 std::map<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
576 if (ai != AllocaLookup.end()) {
577 // what value were we writing?
578 IncomingVals[ai->second] = SI->getOperand(0);
579 BB->getInstList().erase(SI);
585 // Recurse to our successors.
586 TerminatorInst *TI = BB->getTerminator();
587 for (unsigned i = 0; i != TI->getNumSuccessors(); i++) {
588 std::vector<Value*> OutgoingVals(IncomingVals);
589 RenamePass(TI->getSuccessor(i), BB, OutgoingVals);
593 /// PromoteMemToReg - Promote the specified list of alloca instructions into
594 /// scalar registers, inserting PHI nodes as appropriate. This function makes
595 /// use of DominanceFrontier information. This function does not modify the CFG
596 /// of the function at all. All allocas must be from the same function.
598 /// If AST is specified, the specified tracker is updated to reflect changes
601 void llvm::PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
602 DominatorTree &DT, DominanceFrontier &DF,
603 const TargetData &TD, AliasSetTracker *AST) {
604 // If there is nothing to do, bail out...
605 if (Allocas.empty()) return;
606 PromoteMem2Reg(Allocas, DT, DF, TD, AST).run();